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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1396  ! raeburn     4: # $Id: lonnet.pm,v 1.1395 2018/12/08 17:38:47 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.486     www        74: use HTTP::Date;
1.977     amueller   75: use Image::Magick;
1.1389    raeburn    76: use CGI::Cookie;
1.1182    foxr       77: 
1.1173    foxr       78: use Encode;
                     79: 
1.1245    raeburn    80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     82:             %managerstab);
1.871     albertel   83: 
                     84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        87:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        88: 
1.1       albertel   89: use IO::Socket;
1.31      www        90: use GDBM_File;
1.208     albertel   91: use HTML::LCParser;
1.88      www        92: use Fcntl qw(:flock);
1.870     albertel   93: use Storable qw(thaw nfreeze);
1.1289    damieng    94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   95: use Cache::Memcached;
1.676     albertel   96: use Digest::MD5;
1.790     albertel   97: use Math::Random;
1.1024    raeburn    98: use File::MMagic;
1.807     albertel   99: use LONCAPA qw(:DEFAULT :match);
1.740     www       100: use LONCAPA::Configuration;
1.1160    www       101: use LONCAPA::lonmetadata;
1.1167    droeschl  102: use LONCAPA::Lond;
1.1345    raeburn   103: use LONCAPA::LWPReq;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
1.1359    raeburn   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.1359    raeburn   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.1359    raeburn   174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  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 {
1.1383    raeburn   233:     my ($lonhost,$hostname,$context) = @_;
                    234:     return if ($lonhost eq '');
                    235:     if ($hostname eq '') {
                    236:         $hostname = &hostname($lonhost);
                    237:     }
                    238:     return if ($hostname eq '');
1.1315    raeburn   239:     my ($rep,$uselocal);
1.1388    raeburn   240:     if ($context eq 'install') {
1.1387    raeburn   241:         $uselocal = 1;
                    242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   243:         $uselocal = 1;
                    244:     }
1.1387    raeburn   245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   247:         if ($distro eq '') {
                    248:             $uselocal = 0;
                    249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   250:             if ($1 < 6) {
                    251:                 $uselocal = 0;
                    252:             }
1.1346    raeburn   253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    254:             if ($1 < 12) {
                    255:                 $uselocal = 0;
                    256:             }
1.1315    raeburn   257:         }
                    258:     }
                    259:     if ($uselocal) {
1.1383    raeburn   260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   261:     } else {
                    262:         $rep=&reply('servercerts',$lonhost);
                    263:     }
                    264:     my ($result,%returnhash);
                    265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    266:         ($rep eq 'unknown_cmd')) {
                    267:         $result = $rep;
                    268:     } else {
                    269:         $result = 'ok';
                    270:         my @pairs=split(/\&/,$rep);
                    271:         foreach my $item (@pairs) {
                    272:             my ($key,$value)=split(/=/,$item,2);
                    273:             my $what = &unescape($key);
                    274:             $returnhash{$what}=&thaw_unescape($value);
                    275:         }
                    276:     }
                    277:     return ($result,\%returnhash);
                    278: }
                    279: 
1.993     raeburn   280: sub get_server_loncaparev {
1.1073    raeburn   281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   282:     if (defined($lonhost)) {
                    283:         if (!defined(&hostname($lonhost))) {
                    284:             undef($lonhost);
                    285:         }
                    286:     }
                    287:     if (!defined($lonhost)) {
                    288:         if (defined(&domain($dom,'primary'))) {
                    289:             $lonhost=&domain($dom,'primary');
                    290:             if ($lonhost eq 'no_host') {
                    291:                 undef($lonhost);
                    292:             }
                    293:         }
                    294:     }
                    295:     if (defined($lonhost)) {
1.1073    raeburn   296:         my $cachetime = 12*3600;
                    297:         if (!$ignore_cache) {
                    298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    299:             if (defined($cached)) {
                    300:                 return $loncaparev;
                    301:             }
                    302:         }
                    303:         my ($answer,$loncaparev);
                    304:         my @ids=&current_machine_ids();
                    305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    306:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   308:                 $loncaparev = $1;
                    309:             }
                    310:         } else {
                    311:             $answer = &reply('serverloncaparev',$lonhost);
                    312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    313:                 if ($caller eq 'loncron') {
                    314:                     my $protocol = $protocol{$lonhost};
                    315:                     $protocol = 'http' if ($protocol ne 'https');
                    316:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    317:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   318:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   319:                     unless ($response->is_error()) {
                    320:                         my $content = $response->content;
1.1081    raeburn   321:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   322:                             $loncaparev = $1;
                    323:                         }
                    324:                     }
                    325:                 } else {
                    326:                     $loncaparev = $loncaparevs{$lonhost};
                    327:                 }
1.1081    raeburn   328:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   329:                 $loncaparev = $1;
                    330:             }
1.993     raeburn   331:         }
1.1073    raeburn   332:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   333:     }
                    334: }
                    335: 
1.1074    raeburn   336: sub get_server_homeID {
                    337:     my ($hostname,$ignore_cache,$caller) = @_;
                    338:     unless ($ignore_cache) {
                    339:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    340:         if (defined($cached)) {
                    341:             return $serverhomeID;
                    342:         }
                    343:     }
                    344:     my $cachetime = 12*3600;
                    345:     my $serverhomeID;
                    346:     if ($caller eq 'loncron') { 
                    347:         my @machine_ids = &machine_ids($hostname);
                    348:         foreach my $id (@machine_ids) {
                    349:             my $response = &reply('serverhomeID',$id);
                    350:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    351:                 $serverhomeID = $response;
                    352:                 last;
                    353:             }
                    354:         }
                    355:         if ($serverhomeID eq '') {
                    356:             $serverhomeID = $machine_ids[-1];
                    357:         }
                    358:     } else {
                    359:         $serverhomeID = $serverhomeIDs{$hostname};
                    360:     }
                    361:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    362: }
                    363: 
1.1121    raeburn   364: sub get_remote_globals {
                    365:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   366:     my ($result,%returnhash,%whatneeded);
                    367:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   368:         foreach my $what (sort(keys(%{$whathash}))) {
                    369:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   370:             my ($response,$cached);
1.1121    raeburn   371:             unless ($ignore_cache) {
1.1125    raeburn   372:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   373:             }
                    374:             if (defined($cached)) {
1.1125    raeburn   375:                 $returnhash{$what} = $response;
1.1121    raeburn   376:             } else {
1.1125    raeburn   377:                 $whatneeded{$what} = 1;
1.1121    raeburn   378:             }
                    379:         }
1.1125    raeburn   380:         if (keys(%whatneeded) == 0) {
                    381:             $result = 'ok';
                    382:         } else {
1.1121    raeburn   383:             my $requested = &freeze_escape(\%whatneeded);
                    384:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   385:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    386:                 ($rep eq 'unknown_cmd')) {
                    387:                 $result = $rep;
                    388:             } else {
                    389:                 $result = 'ok';
1.1121    raeburn   390:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   391:                 foreach my $item (@pairs) {
                    392:                     my ($key,$value)=split(/=/,$item,2);
                    393:                     my $what = &unescape($key);
                    394:                     my $hashid = $lonhost.'-'.$what;
                    395:                     $returnhash{$what}=&thaw_unescape($value);
                    396:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   397:                 }
                    398:             }
                    399:         }
                    400:     }
1.1125    raeburn   401:     return ($result,\%returnhash);
1.1121    raeburn   402: }
                    403: 
1.1124    raeburn   404: sub remote_devalidate_cache {
1.1241    raeburn   405:     my ($lonhost,$cachekeys) = @_;
                    406:     my $items;
                    407:     return unless (ref($cachekeys) eq 'ARRAY');
                    408:     my $cachestr = join('&',@{$cachekeys});
                    409:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   410:     return $response;
                    411: }
                    412: 
1.1       albertel  413: # -------------------------------------------------- Non-critical communication
                    414: sub subreply {
                    415:     my ($cmd,$server)=@_;
1.838     albertel  416:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      417:     #
                    418:     #  With loncnew process trimming, there's a timing hole between lonc server
                    419:     #  process exit and the master server picking up the listen on the AF_UNIX
                    420:     #  socket.  In that time interval, a lock file will exist:
                    421: 
                    422:     my $lockfile=$peerfile.".lock";
                    423:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   424: 	sleep(0.1);
1.549     foxr      425:     }
                    426:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      427:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      428:     #
1.550     foxr      429:     #   We'll give the connection a few tries before abandoning it.  If
                    430:     #   connection is not possible, we'll con_lost back to the client.
                    431:     #   
                    432:     my $client;
                    433:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    434: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    435: 				      Type    => SOCK_STREAM,
                    436: 				      Timeout => 10);
1.869     albertel  437: 	if ($client) {
1.550     foxr      438: 	    last;		# Connected!
1.850     albertel  439: 	} else {
1.853     albertel  440: 	    &create_connection(&hostname($server),$server);
1.550     foxr      441: 	}
1.1289    damieng   442:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      443:     }
                    444:     my $answer;
                    445:     if ($client) {
1.704     albertel  446: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      447: 	$answer=<$client>;
                    448: 	if (!$answer) { $answer="con_lost"; }
                    449: 	chomp($answer);
                    450:     } else {
                    451: 	$answer = 'con_lost';	# Failed connection.
                    452:     }
1.1       albertel  453:     return $answer;
                    454: }
                    455: 
                    456: sub reply {
                    457:     my ($cmd,$server)=@_;
1.838     albertel  458:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  459:     my $answer=subreply($cmd,$server);
1.65      www       460:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396  ! raeburn   461:         my $logged = $cmd;
        !           462:         if ($cmd =~ /^encrypt:([^:]+):/) {
        !           463:             my $subcmd = $1;
        !           464:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
        !           465:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
        !           466:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
        !           467:                 (undef,undef,my @rest) = split(/:/,$cmd);
        !           468:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
        !           469:                     splice(@rest,2,1,'Hidden');
        !           470:                 } elsif ($subcmd eq 'passwd') {
        !           471:                     splice(@rest,2,2,('Hidden','Hidden'));
        !           472:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
        !           473:                          ($subcmd eq 'autoexportgrades')) {
        !           474:                     splice(@rest,3,1,'Hidden');
        !           475:                 }
        !           476:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
        !           477:             }
        !           478:         }
        !           479:         &logthis("<font color=\"blue\">WARNING:".
        !           480:                  " $logged to $server returned $answer</font>");
1.12      www       481:     }
1.1       albertel  482:     return $answer;
                    483: }
                    484: 
                    485: # ----------------------------------------------------------- Send USR1 to lonc
                    486: 
                    487: sub reconlonc {
1.891     albertel  488:     my ($lonid) = @_;
                    489:     if ($lonid) {
1.1295    raeburn   490:         my $hostname = &hostname($lonid);
1.891     albertel  491: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    492: 	if ($hostname && -e $peerfile) {
                    493: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    494: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    495: 					     Type    => SOCK_STREAM,
                    496: 					     Timeout => 10);
                    497: 	    if ($client) {
                    498: 		print $client ("reset_retries\n");
                    499: 		my $answer=<$client>;
                    500: 		#reset just this one.
                    501: 	    }
                    502: 	}
                    503: 	return;
                    504:     }
                    505: 
1.836     www       506:     &logthis("Trying to reconnect lonc");
1.1       albertel  507:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   508:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  509: 	my $loncpid=<$fh>;
                    510:         chomp($loncpid);
                    511:         if (kill 0 => $loncpid) {
                    512: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    513:             kill USR1 => $loncpid;
                    514:             sleep 1;
1.1295    raeburn   515:         } else {
1.12      www       516: 	    &logthis(
1.672     albertel  517:                "<font color=\"blue\">WARNING:".
1.12      www       518:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  519:         }
                    520:     } else {
1.836     www       521: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  522:     }
                    523: }
                    524: 
                    525: # ------------------------------------------------------ Critical communication
1.12      www       526: 
1.1       albertel  527: sub critical {
                    528:     my ($cmd,$server)=@_;
1.838     albertel  529:     unless (&hostname($server)) {
1.672     albertel  530:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       531:                " Critical message to unknown server ($server)</font>");
                    532:         return 'no_such_host';
                    533:     }
1.1       albertel  534:     my $answer=reply($cmd,$server);
                    535:     if ($answer eq 'con_lost') {
1.1295    raeburn   536: 	&reconlonc($server);
1.589     albertel  537: 	my $answer=reply($cmd,$server);
1.1       albertel  538:         if ($answer eq 'con_lost') {
                    539:             my $now=time;
                    540:             my $middlename=$cmd;
1.5       www       541:             $middlename=substr($middlename,0,16);
1.1       albertel  542:             $middlename=~s/\W//g;
                    543:             my $dfilename=
1.305     www       544:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    545:             $dumpcount++;
1.1       albertel  546:             {
1.448     albertel  547: 		my $dfh;
1.1359    raeburn   548: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  549: 		    print $dfh "$cmd\n"; 
                    550: 		    close($dfh);
                    551: 		}
1.1       albertel  552:             }
1.1288    damieng   553:             sleep 1;
1.1       albertel  554:             my $wcmd='';
                    555:             {
1.448     albertel  556: 		my $dfh;
1.1359    raeburn   557: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  558: 		    $wcmd=<$dfh>; 
                    559: 		    close($dfh);
                    560: 		}
1.1       albertel  561:             }
                    562:             chomp($wcmd);
1.7       www       563:             if ($wcmd eq $cmd) {
1.672     albertel  564: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       565:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  566:                 &logperm("D:$server:$cmd");
                    567: 	        return 'con_delayed';
                    568:             } else {
1.672     albertel  569:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       570:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  571:                 &logperm("F:$server:$cmd");
                    572:                 return 'con_failed';
                    573:             }
                    574:         }
                    575:     }
                    576:     return $answer;
1.405     albertel  577: }
                    578: 
1.755     albertel  579: # ------------------------------------------- check if return value is an error
                    580: 
                    581: sub error {
                    582:     my ($result) = @_;
1.756     albertel  583:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  584: 	if ($2 == 2) { return undef; }
                    585: 	return $1;
                    586:     }
                    587:     return undef;
                    588: }
                    589: 
1.783     albertel  590: sub convert_and_load_session_env {
                    591:     my ($lonidsdir,$handle)=@_;
                    592:     my @profile;
                    593:     {
1.917     albertel  594: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    595: 	if (!$opened) {
1.915     albertel  596: 	    return 0;
                    597: 	}
1.783     albertel  598: 	flock($idf,LOCK_SH);
                    599: 	@profile=<$idf>;
                    600: 	close($idf);
                    601:     }
                    602:     my %temp_env;
                    603:     foreach my $line (@profile) {
1.786     albertel  604: 	if ($line !~ m/=/) {
                    605: 	    return 0;
                    606: 	}
1.783     albertel  607: 	chomp($line);
                    608: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    609: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    610:     }
                    611:     unlink("$lonidsdir/$handle.id");
                    612:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    613: 	    0640)) {
                    614: 	%disk_env = %temp_env;
                    615: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    616: 	untie(%disk_env);
                    617:     }
1.786     albertel  618:     return 1;
1.783     albertel  619: }
                    620: 
1.374     www       621: # ------------------------------------------- Transfer profile into environment
1.780     albertel  622: my $env_loaded;
                    623: sub transfer_profile_to_env {
1.788     albertel  624:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    625:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       626: 
1.720     albertel  627:     if (!defined($lonidsdir)) {
                    628: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    629:     }
                    630:     if (!defined($handle)) {
                    631:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    632:     }
                    633: 
1.786     albertel  634:     my $convert;
                    635:     {
1.917     albertel  636:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    637: 	if (!$opened) {
1.915     albertel  638: 	    return;
                    639: 	}
1.786     albertel  640: 	flock($idf,LOCK_SH);
                    641: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    642: 		&GDBM_READER(),0640)) {
                    643: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    644: 	    untie(%disk_env);
                    645: 	} else {
                    646: 	    $convert = 1;
                    647: 	}
                    648:     }
                    649:     if ($convert) {
                    650: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    651: 	    &logthis("Failed to load session, or convert session.");
                    652: 	}
1.374     www       653:     }
1.783     albertel  654: 
1.786     albertel  655:     my %remove;
1.783     albertel  656:     while ( my $envname = each(%env) ) {
1.433     matthew   657:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    658:             if ($time < time-300) {
1.783     albertel  659:                 $remove{$key}++;
1.433     matthew   660:             }
                    661:         }
                    662:     }
1.783     albertel  663: 
1.619     albertel  664:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  665:     $env_loaded=1;
1.783     albertel  666:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   667:         &delenv($expired_key);
1.374     www       668:     }
1.1       albertel  669: }
                    670: 
1.916     albertel  671: # ---------------------------------------------------- Check for valid session 
                    672: sub check_for_valid_session {
1.1355    raeburn   673:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  674:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   675:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    676:     if ($name eq 'lonDAV') {
                    677:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    678:     } else {
                    679:         $lonidsdir=$r->dir_config('lonIDsDir');
                    680:         if ($name eq '') {
                    681:             $name = 'lonID';
                    682:         }
                    683:     }
                    684:     if ($name eq 'lonID') {
                    685:         $secure = 'lonSID';
1.1337    raeburn   686:         $linkname = 'lonLinkID';
                    687:         $pubname = 'lonPubID';
1.1378    raeburn   688:         if (exists($cookies{$secure})) {
                    689:             $lonid=$cookies{$secure};
                    690:         } elsif (exists($cookies{$name})) {
                    691:             $lonid=$cookies{$name};
                    692:         } elsif (exists($cookies{$linkname})) {
1.1337    raeburn   693:             $lonid=$cookies{$linkname};
1.1378    raeburn   694:         } elsif (exists($cookies{$pubname})) {
                    695:             $lonid=$cookies{$pubname};
1.1337    raeburn   696:         }
1.1378    raeburn   697:     } else {
                    698:         $lonid=$cookies{$name};
1.1337    raeburn   699:     }
1.916     albertel  700:     return undef if (!$lonid);
                    701: 
                    702:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   703:     if (-l "$lonidsdir/$handle.id") {
                    704:         my $link = readlink("$lonidsdir/$handle.id");
                    705:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    706:             $handle = $1;
                    707:         }
1.1155    raeburn   708:     }
1.1355    raeburn   709:     if (!-e "$lonidsdir/$handle.id") {
                    710:         if ((ref($domref)) && ($name eq 'lonID') && 
                    711:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    712:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    713:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    714:                 $$domref = $possudom;
                    715:             }
                    716:         }
                    717:         return undef;
                    718:     }
1.916     albertel  719: 
1.917     albertel  720:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    721:     return undef if (!$opened);
1.916     albertel  722: 
                    723:     flock($idf,LOCK_SH);
                    724:     my %disk_env;
                    725:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    726: 	    &GDBM_READER(),0640)) {
                    727: 	return undef;	
                    728:     }
                    729: 
                    730:     if (!defined($disk_env{'user.name'})
                    731: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   732:         untie(%disk_env);
1.916     albertel  733: 	return undef;
                    734:     }
1.1245    raeburn   735: 
                    736:     if (ref($userhashref) eq 'HASH') {
                    737:         $userhashref->{'name'} = $disk_env{'user.name'};
                    738:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   739:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   740:         if ($userhashref->{'lti'}) {
                    741:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    742:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    743:         }
1.1212    raeburn   744:     }
1.1394    raeburn   745:     untie(%disk_env);
1.1245    raeburn   746: 
1.916     albertel  747:     return $handle;
                    748: }
                    749: 
1.830     albertel  750: sub timed_flock {
                    751:     my ($file,$lock_type) = @_;
                    752:     my $failed=0;
                    753:     eval {
                    754: 	local $SIG{__DIE__}='DEFAULT';
                    755: 	local $SIG{ALRM}=sub {
                    756: 	    $failed=1;
                    757: 	    die("failed lock");
                    758: 	};
                    759: 	alarm(13);
                    760: 	flock($file,$lock_type);
                    761: 	alarm(0);
                    762:     };
                    763:     if ($failed) {
                    764: 	return undef;
                    765:     } else {
                    766: 	return 1;
                    767:     }
                    768: }
                    769: 
1.1392    raeburn   770: sub get_sessionfile_vars {
                    771:     my ($handle,$lonidsdir,$storearr) = @_;
                    772:     my %returnhash;
                    773:     unless (ref($storearr) eq 'ARRAY') {
                    774:         return %returnhash;
                    775:     }
                    776:     if (-l "$lonidsdir/$handle.id") {
                    777:         my $link = readlink("$lonidsdir/$handle.id");
                    778:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    779:             $handle = $1;
                    780:         }
                    781:     }
                    782:     if ((-e "$lonidsdir/$handle.id") &&
                    783:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    784:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    785:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    786:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    787:                 flock($idf,LOCK_SH);
                    788:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    789:                         &GDBM_READER(),0640)) {
                    790:                     foreach my $item (@{$storearr}) {
                    791:                         $returnhash{$item} = $disk_env{$item};
                    792:                     }
                    793:                     untie(%disk_env);
                    794:                 }
                    795:             }
                    796:         }
                    797:     }
                    798:     return %returnhash;
                    799: }
                    800: 
1.5       www       801: # ---------------------------------------------------------- Append Environment
                    802: 
                    803: sub appenv {
1.949     raeburn   804:     my ($newenv,$roles) = @_;
                    805:     if (ref($newenv) eq 'HASH') {
                    806:         foreach my $key (keys(%{$newenv})) {
                    807:             my $refused = 0;
                    808: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    809:                 $refused = 1;
                    810:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   811:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   812:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    813:                         $refused = 0;
                    814:                     }
                    815:                 }
                    816:             }
                    817:             if ($refused) {
                    818:                 &logthis("<font color=\"blue\">WARNING: ".
                    819:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    820:                          .'</font>');
                    821: 	        delete($newenv->{$key});
                    822:             } else {
                    823:                 $env{$key}=$newenv->{$key};
                    824:             }
                    825:         }
1.1376    raeburn   826:         my $lonids = $perlvar{'lonIDsDir'};
                    827:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    828:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    829:             if ($opened
                    830: 	        && &timed_flock($env_file,LOCK_EX)
                    831: 	        &&
                    832: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    833: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    834: 	        while (my ($key,$value) = each(%{$newenv})) {
                    835: 	            $disk_env{$key} = $value;
                    836: 	        }
                    837: 	        untie(%disk_env);
                    838:             }
1.35      www       839:         }
1.191     harris41  840:     }
1.56      www       841:     return 'ok';
                    842: }
                    843: # ----------------------------------------------------- Delete from Environment
                    844: 
                    845: sub delenv {
1.1104    raeburn   846:     my ($delthis,$regexp,$roles) = @_;
                    847:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    848:         my $refused = 1;
                    849:         if (ref($roles) eq 'ARRAY') {
                    850:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    851:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    852:                 $refused = 0;
                    853:             }
                    854:         }
                    855:         if ($refused) {
                    856:             &logthis("<font color=\"blue\">WARNING: ".
                    857:                      "Attempt to delete from environment ".$delthis);
                    858:             return 'error';
                    859:         }
1.56      www       860:     }
1.917     albertel  861:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    862:     if ($opened
1.915     albertel  863: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  864: 	&&
                    865: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    866: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  867: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   868: 	    if ($regexp) {
                    869:                 if ($key=~/^$delthis/) {
                    870:                     delete($env{$key});
                    871:                     delete($disk_env{$key});
                    872:                 } 
                    873:             } else {
                    874:                 if ($key=~/^\Q$delthis\E/) {
                    875: 		    delete($env{$key});
                    876: 		    delete($disk_env{$key});
                    877: 	        }
                    878:             }
1.448     albertel  879: 	}
1.783     albertel  880: 	untie(%disk_env);
1.5       www       881:     }
                    882:     return 'ok';
1.369     albertel  883: }
                    884: 
1.790     albertel  885: sub get_env_multiple {
                    886:     my ($name) = @_;
                    887:     my @values;
                    888:     if (defined($env{$name})) {
                    889:         # exists is it an array
                    890:         if (ref($env{$name})) {
                    891:             @values=@{ $env{$name} };
                    892:         } else {
                    893:             $values[0]=$env{$name};
                    894:         }
                    895:     }
                    896:     return(@values);
                    897: }
                    898: 
1.958     www       899: # ------------------------------------------------------------------- Locking
                    900: 
                    901: sub set_lock {
                    902:     my ($text)=@_;
                    903:     $locknum++;
                    904:     my $id=$$.'-'.$locknum;
                    905:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    906:              'session.lock.'.$id => $text});
                    907:     return $id;
                    908: }
                    909: 
                    910: sub get_locks {
                    911:     my $num=0;
                    912:     my %texts=();
                    913:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    914:        if ($lock=~/\w/) {
                    915:           $num++;
                    916:           $texts{$lock}=$env{'session.lock.'.$lock};
                    917:        }
                    918:    }
                    919:    return ($num,%texts);
                    920: }
                    921: 
                    922: sub remove_lock {
                    923:     my ($id)=@_;
                    924:     my $newlocks='';
                    925:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    926:        if (($lock=~/\w/) && ($lock ne $id)) {
                    927:           $newlocks.=','.$lock;
                    928:        }
                    929:     }
                    930:     &appenv({'session.locks' => $newlocks});
                    931:     &delenv('session.lock.'.$id);
                    932: }
                    933: 
                    934: sub remove_all_locks {
                    935:     my $activelocks=$env{'session.locks'};
                    936:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    937:        if ($lock=~/\w/) {
                    938:           &remove_lock($lock);
                    939:        }
                    940:     }
                    941: }
                    942: 
                    943: 
1.369     albertel  944: # ------------------------------------------ Find out current server userload
                    945: sub userload {
                    946:     my $numusers=0;
                    947:     {
                    948: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    949: 	my $filename;
                    950: 	my $curtime=time;
                    951: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  952: 	    next if ($filename eq '.' || $filename eq '..');
                    953: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   954:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  955: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  956: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  957: 	}
                    958: 	closedir(LONIDS);
                    959:     }
                    960:     my $userloadpercent=0;
                    961:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    962:     if ($maxuserload) {
1.371     albertel  963: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  964:     }
1.372     albertel  965:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  966:     return $userloadpercent;
1.283     www       967: }
                    968: 
1.1       albertel  969: # ------------------------------ Find server with least workload from spare.tab
1.11      www       970: 
1.1       albertel  971: sub spareserver {
1.1083    raeburn   972:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  973:     my $spare_server;
1.370     albertel  974:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  975:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    976:                                                      :  $userloadpercent;
1.1083    raeburn   977:     my ($uint_dom,$remotesessions);
                    978:     if (($udom ne '') && (&domain($udom) ne '')) {
                    979:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    980:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    981:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    982:         $remotesessions = $udomdefaults{'remotesessions'};
                    983:     }
1.1123    raeburn   984:     my $spareshash = &this_host_spares($udom);
                    985:     if (ref($spareshash) eq 'HASH') {
                    986:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    987:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   988:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    989:                                              $try_server));
1.1123    raeburn   990: 	        ($spare_server, $lowest_load) =
                    991: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    992:             }
1.1083    raeburn   993:         }
1.784     albertel  994: 
1.1123    raeburn   995:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    996: 
                    997:         if (!$found_server) {
                    998:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    999: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn  1000:                     next unless (&spare_can_host($udom,$uint_dom,
                   1001:                                                  $remotesessions,$try_server));
1.1123    raeburn  1002: 	            ($spare_server, $lowest_load) =
                   1003: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1004:                 }
                   1005: 	    }
                   1006:         }
1.784     albertel 1007:     }
                   1008: 
                   1009:     if (!$want_server_name) {
1.968     raeburn  1010:         my $protocol = 'http';
                   1011:         if ($protocol{$spare_server} eq 'https') {
                   1012:             $protocol = $protocol{$spare_server};
                   1013:         }
1.1001    raeburn  1014:         if (defined($spare_server)) {
                   1015:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1016:             if (defined($hostname)) {
1.1001    raeburn  1017: 	        $spare_server = $protocol.'://'.$hostname;
                   1018:             }
                   1019:         }
1.784     albertel 1020:     }
                   1021:     return $spare_server;
                   1022: }
                   1023: 
                   1024: sub compare_server_load {
1.1253    raeburn  1025:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1026: 
                   1027:     if ($required) {
                   1028:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1029:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1030:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1031:         if (($major eq '' && $minor eq '') ||
                   1032:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1033:             return ($spare_server,$lowest_load);
                   1034:         }
                   1035:     }
1.784     albertel 1036: 
                   1037:     my $loadans     = &reply('load',    $try_server);
                   1038:     my $userloadans = &reply('userload',$try_server);
                   1039: 
                   1040:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1041: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1042:     }
                   1043: 
                   1044:     my $load;
                   1045:     if ($loadans =~ /\d/) {
                   1046: 	if ($userloadans =~ /\d/) {
                   1047: 	    #both are numbers, pick the bigger one
                   1048: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1049: 		                              : $userloadans;
1.411     albertel 1050: 	} else {
1.784     albertel 1051: 	    $load = $loadans;
1.411     albertel 1052: 	}
1.784     albertel 1053:     } else {
                   1054: 	$load = $userloadans;
                   1055:     }
                   1056: 
                   1057:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1058: 	$spare_server = $try_server;
                   1059: 	$lowest_load  = $load;
1.370     albertel 1060:     }
1.784     albertel 1061:     return ($spare_server,$lowest_load);
1.202     matthew  1062: }
1.914     albertel 1063: 
                   1064: # --------------------------- ask offload servers if user already has a session
                   1065: sub find_existing_session {
                   1066:     my ($udom,$uname) = @_;
1.1123    raeburn  1067:     my $spareshash = &this_host_spares($udom);
                   1068:     if (ref($spareshash) eq 'HASH') {
                   1069:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1070:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1071:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1072:             }
                   1073:         }
                   1074:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1075:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1076:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1077:             }
                   1078:         }
1.914     albertel 1079:     }
                   1080:     return;
                   1081: }
                   1082: 
1.1389    raeburn  1083: # check if user's browser sent load balancer cookie and server still has session
                   1084: # and is not overloaded.
                   1085: sub check_for_balancer_cookie {
                   1086:     my ($r,$update_mtime) = @_;
                   1087:     my ($otherserver,$cookie);
                   1088:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1089:     if (exists($cookies{'balanceID'})) {
                   1090:         my $balid = $cookies{'balanceID'};
                   1091:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1092:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1093:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1094:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1095:                 my ($possudom,$possuname) = ($1,$2);
                   1096:                 my $has_session = 0;
                   1097:                 if ((&domain($possudom) ne '') &&
                   1098:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1099:                     my $try_server;
                   1100:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1101:                     if ($opened) {
                   1102:                         flock($idf,LOCK_SH);
                   1103:                         while (my $line = <$idf>) {
                   1104:                             chomp($line);
                   1105:                             if (&hostname($line) ne '') {
                   1106:                                 $try_server = $line;
                   1107:                                 last;
                   1108:                             }
                   1109:                         }
                   1110:                         close($idf);
                   1111:                         if (($try_server) &&
                   1112:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1113:                             my $lowest_load = 30000;
                   1114:                             ($otherserver,$lowest_load) =
                   1115:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1116:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1117:                                 $has_session = 1;
                   1118:                             } else {
                   1119:                                 undef($otherserver);
                   1120:                             }
                   1121:                         }
                   1122:                     }
                   1123:                 }
                   1124:                 if ($has_session) {
                   1125:                     if ($update_mtime) {
                   1126:                         my $atime = my $mtime = time;
                   1127:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1128:                     }
                   1129:                 } else {
                   1130:                     unlink("$balancedir/$cookie.id");
                   1131:                 }
                   1132:             }
                   1133:         }
                   1134:     }
                   1135:     return ($otherserver,$cookie);
                   1136: }
                   1137: 
                   1138: sub delbalcookie {
                   1139:     my ($cookie,$balancer) =@_;
                   1140:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1141:         my ($udom,$uname) = ($1,$2);
                   1142:         my $uprimary_id = &domain($udom,'primary');
                   1143:         my $uintdom = &internet_dom($uprimary_id);
                   1144:         my $intdom = &internet_dom($balancer);
                   1145:         my $serverhomedom = &host_domain($balancer);
                   1146:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1147:             return &reply("delbalcookie:$cookie",$balancer);
                   1148:         }
                   1149:     }
                   1150: }
                   1151: 
1.914     albertel 1152: # -------------------------------- ask if server already has a session for user
                   1153: sub has_user_session {
                   1154:     my ($lonid,$udom,$uname) = @_;
                   1155:     my $result = &reply(join(':','userhassession',
                   1156: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1157:     return 1 if ($result eq 'ok');
                   1158: 
                   1159:     return 0;
                   1160: }
                   1161: 
1.1076    raeburn  1162: # --------- determine least loaded server in a user's domain which allows login
                   1163: 
                   1164: sub choose_server {
1.1259    raeburn  1165:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1166:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1167:     my %servers = &get_servers($udom);
1.1076    raeburn  1168:     my $lowest_load = 30000;
1.1259    raeburn  1169:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1170:     if ($skiploadbal) {
                   1171:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1172:         unless (defined($cached)) {
                   1173:             my $cachetime = 60*60*24;
                   1174:             my %domconfig =
                   1175:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1176:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1177:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1178:                                            $cachetime);
                   1179:             }
                   1180:         }
                   1181:     }
1.1076    raeburn  1182:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1183:         if ($skiploadbal) {
                   1184:             if (ref($balancers) eq 'HASH') {
                   1185:                 next if (exists($balancers->{$lonhost}));
                   1186:             }
1.1389    raeburn  1187:         }
1.1115    raeburn  1188:         my $loginvia;
                   1189:         if ($checkloginvia) {
                   1190:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1191:             if ($loginvia) {
                   1192:                 my ($server,$path) = split(/:/,$loginvia);
                   1193:                 ($login_host, $lowest_load) =
1.1253    raeburn  1194:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1195:                 if ($login_host eq $server) {
                   1196:                     $portal_path = $path;
1.1151    raeburn  1197:                     $isredirect = 1;
1.1116    raeburn  1198:                 }
                   1199:             } else {
                   1200:                 ($login_host, $lowest_load) =
1.1253    raeburn  1201:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1202:                 if ($login_host eq $lonhost) {
                   1203:                     $portal_path = '';
1.1151    raeburn  1204:                     $isredirect = ''; 
1.1116    raeburn  1205:                 }
                   1206:             }
                   1207:         } else {
1.1076    raeburn  1208:             ($login_host, $lowest_load) =
1.1253    raeburn  1209:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1210:         }
                   1211:     }
                   1212:     if ($login_host ne '') {
1.1116    raeburn  1213:         $hostname = &hostname($login_host);
1.1076    raeburn  1214:     }
1.1331    raeburn  1215:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1216: }
                   1217: 
1.202     matthew  1218: # --------------------------------------------- Try to change a user's password
                   1219: 
                   1220: sub changepass {
1.799     raeburn  1221:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1222:     $currentpass = &escape($currentpass);
                   1223:     $newpass     = &escape($newpass);
1.1030    raeburn  1224:     my $lonhost = $perlvar{'lonHostID'};
                   1225:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1226: 		       $server);
                   1227:     if (! $answer) {
                   1228: 	&logthis("No reply on password change request to $server ".
                   1229: 		 "by $uname in domain $udom.");
                   1230:     } elsif ($answer =~ "^ok") {
                   1231:         &logthis("$uname in $udom successfully changed their password ".
                   1232: 		 "on $server.");
                   1233:     } elsif ($answer =~ "^pwchange_failure") {
                   1234: 	&logthis("$uname in $udom was unable to change their password ".
                   1235: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1236: 		 "or pwchange");
                   1237:     } elsif ($answer =~ "^non_authorized") {
                   1238:         &logthis("$uname in $udom did not get their password correct when ".
                   1239: 		 "attempting to change it on $server.");
                   1240:     } elsif ($answer =~ "^auth_mode_error") {
                   1241:         &logthis("$uname in $udom attempted to change their password despite ".
                   1242: 		 "not being locally or internally authenticated on $server.");
                   1243:     } elsif ($answer =~ "^unknown_user") {
                   1244:         &logthis("$uname in $udom attempted to change their password ".
                   1245: 		 "on $server but were unable to because $server is not ".
                   1246: 		 "their home server.");
                   1247:     } elsif ($answer =~ "^refused") {
                   1248: 	&logthis("$server refused to change $uname in $udom password because ".
                   1249: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1250:     } elsif ($answer =~ "invalid_client") {
                   1251:         &logthis("$server refused to change $uname in $udom password because ".
                   1252:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1253:     }
                   1254:     return $answer;
1.1       albertel 1255: }
                   1256: 
1.169     harris41 1257: # ----------------------- Try to determine user's current authentication scheme
                   1258: 
                   1259: sub queryauthenticate {
                   1260:     my ($uname,$udom)=@_;
1.456     albertel 1261:     my $uhome=&homeserver($uname,$udom);
                   1262:     if (!$uhome) {
                   1263: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1264: 	return 'no_host';
                   1265:     }
                   1266:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1267:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1268: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1269:     }
1.456     albertel 1270:     return $answer;
1.169     harris41 1271: }
                   1272: 
1.1       albertel 1273: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1274: 
1.1       albertel 1275: sub authenticate {
1.1073    raeburn  1276:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1277:     $upass=&escape($upass);
                   1278:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1279:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1280:     my $newhome;
1.836     www      1281:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1282: # Maybe the machine was offline and only re-appeared again recently?
                   1283:         &reconlonc();
                   1284: # One more
1.952     raeburn  1285: 	$uhome=&homeserver($uname,$udom,1);
                   1286:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1287:             if (defined(&domain($udom,'primary'))) {
                   1288:                 $newhome=&domain($udom,'primary');
                   1289:             }
                   1290:             if ($newhome ne '') {
                   1291:                 $uhome = $newhome;
                   1292:             }
                   1293:         }
1.836     www      1294: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1295: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1296: 	    return 'no_host';
                   1297:         }
1.1       albertel 1298:     }
1.1073    raeburn  1299:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1300:     if ($answer eq 'authorized') {
1.952     raeburn  1301:         if ($newhome) {
                   1302:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1303:             return 'no_account_on_host'; 
                   1304:         } else {
                   1305:             &logthis("User $uname at $udom authorized by $uhome");
                   1306:             return $uhome;
                   1307:         }
1.471     albertel 1308:     }
                   1309:     if ($answer eq 'non_authorized') {
                   1310: 	&logthis("User $uname at $udom rejected by $uhome");
                   1311: 	return 'no_host'; 
1.9       www      1312:     }
1.471     albertel 1313:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1314:     return 'no_host';
                   1315: }
                   1316: 
1.1073    raeburn  1317: sub can_host_session {
1.1074    raeburn  1318:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1319:     my $canhost = 1;
1.1074    raeburn  1320:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1321:     if (ref($remotesessions) eq 'HASH') {
                   1322:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1323:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1324:                 $canhost = 0;
                   1325:             } else {
                   1326:                 $canhost = 1;
                   1327:             }
                   1328:         }
                   1329:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1330:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1331:                 $canhost = 1;
                   1332:             } else {
                   1333:                 $canhost = 0;
                   1334:             }
                   1335:         }
                   1336:         if ($canhost) {
                   1337:             if ($remotesessions->{'version'} ne '') {
                   1338:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1339:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1340:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1341:                         my $major = $1;
                   1342:                         my $minor = $2;
                   1343:                         if (($major < $reqmajor ) ||
                   1344:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1345:                             $canhost = 0;
                   1346:                         }
                   1347:                     } else {
                   1348:                         $canhost = 0;
                   1349:                     }
                   1350:                 }
                   1351:             }
                   1352:         }
                   1353:     }
                   1354:     if ($canhost) {
                   1355:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1356:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1357:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1358:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1359:                 if (($uint_dom ne '') && 
                   1360:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1361:                     $canhost = 0;
                   1362:                 } else {
                   1363:                     $canhost = 1;
                   1364:                 }
                   1365:             }
                   1366:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1367:                 if (($uint_dom ne '') && 
                   1368:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1369:                     $canhost = 1;
                   1370:                 } else {
                   1371:                     $canhost = 0;
                   1372:                 }
                   1373:             }
                   1374:         }
                   1375:     }
                   1376:     return $canhost;
                   1377: }
                   1378: 
1.1083    raeburn  1379: sub spare_can_host {
                   1380:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1381:     my $canhost=1;
1.1279    raeburn  1382:     my $try_server_hostname = &hostname($try_server);
                   1383:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1384:     my $serverhomedom = &host_domain($serverhomeID);
                   1385:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1386:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1387:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1388:             $canhost = 0;
                   1389:         }
                   1390:     }
                   1391:     if (($canhost) && ($uint_dom)) {
                   1392:         my @intdoms;
                   1393:         my $internet_names = &get_internet_names($try_server);
                   1394:         if (ref($internet_names) eq 'ARRAY') {
                   1395:             @intdoms = @{$internet_names};
                   1396:         }
                   1397:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1398:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1399:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1400:                                          $remotesessions,
                   1401:                                          $defdomdefaults{'hostedsessions'});
                   1402:         }
1.1083    raeburn  1403:     }
                   1404:     return $canhost;
                   1405: }
                   1406: 
1.1123    raeburn  1407: sub this_host_spares {
                   1408:     my ($dom) = @_;
1.1126    raeburn  1409:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1410:     my @hosts = &current_machine_ids();
                   1411:     foreach my $lonhost (@hosts) {
                   1412:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1413:             $dom_in_use = $dom;
                   1414:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1415:             last;
                   1416:         }
                   1417:     }
1.1126    raeburn  1418:     if ($dom_in_use ne '') {
                   1419:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1420:     }
                   1421:     if (ref($result) ne 'HASH') {
                   1422:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1423:         $dom_in_use = &host_domain($lonhost_in_use);
                   1424:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1425:         if (ref($result) ne 'HASH') {
                   1426:             $result = \%spareid;
                   1427:         }
                   1428:     }
                   1429:     return $result;
                   1430: }
                   1431: 
                   1432: sub spares_for_offload  {
                   1433:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1434:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1435:     if (defined($cached)) {
                   1436:         return $result;
                   1437:     } else {
1.1126    raeburn  1438:         my $cachetime = 60*60*24;
                   1439:         my %domconfig =
                   1440:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1441:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1442:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1443:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1444:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1445:                 }
                   1446:             }
                   1447:         }
                   1448:     }
1.1126    raeburn  1449:     return;
1.1123    raeburn  1450: }
                   1451: 
1.1129    raeburn  1452: sub get_lonbalancer_config {
                   1453:     my ($servers) = @_;
                   1454:     my ($currbalancer,$currtargets);
                   1455:     if (ref($servers) eq 'HASH') {
                   1456:         foreach my $server (keys(%{$servers})) {
                   1457:             my %what = (
                   1458:                          spareid => 1,
                   1459:                          perlvar => 1,
                   1460:                        );
                   1461:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1462:             if ($result eq 'ok') {
                   1463:                 if (ref($returnhash) eq 'HASH') {
                   1464:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1465:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1466:                             $currbalancer = $server;
                   1467:                             $currtargets = {};
                   1468:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1469:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1470:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1471:                                 }
                   1472:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1473:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1474:                                 }
                   1475:                             }
                   1476:                             last;
                   1477:                         }
                   1478:                     }
                   1479:                 }
                   1480:             }
                   1481:         }
                   1482:     }
                   1483:     return ($currbalancer,$currtargets);
                   1484: }
                   1485: 
                   1486: sub check_loadbalancing {
1.1331    raeburn  1487:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1488:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1489:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1490:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1491:     my @hosts = &current_machine_ids();
1.1129    raeburn  1492:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1493:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1494:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1495:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1496:     my $domneedscache;
1.1129    raeburn  1497:     my $cachetime = 60*60*24;
                   1498: 
                   1499:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1500:         $dom_in_use = $udom;
                   1501:         $homeintdom = 1;
                   1502:     } else {
                   1503:         $dom_in_use = $serverhomedom;
                   1504:     }
                   1505:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1506:     unless (defined($cached)) {
                   1507:         my %domconfig =
                   1508:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1509:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1510:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1511:         } else {
                   1512:             $domneedscache = $dom_in_use;
1.1129    raeburn  1513:         }
                   1514:     }
                   1515:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1516:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1517:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1518:         if ($is_balancer) {
                   1519:             if (ref($currrules) eq 'HASH') {
                   1520:                 if ($homeintdom) {
                   1521:                     if ($uname ne '') {
                   1522:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1523:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1524:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1525:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1526:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1527:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1528:                             }
                   1529:                         }
                   1530:                         if ($rule_in_effect eq '') {
                   1531:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1532:                             if ($userenv{'inststatus'} ne '') {
                   1533:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1534:                                 my ($othertitle,$usertypes,$types) =
                   1535:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1536:                                 if (ref($types) eq 'ARRAY') {
                   1537:                                     foreach my $type (@{$types}) {
                   1538:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1539:                                             if (exists($currrules->{$type})) {
                   1540:                                                 $rule_in_effect = $currrules->{$type};
                   1541:                                             }
                   1542:                                         }
                   1543:                                     }
                   1544:                                 }
                   1545:                             } else {
                   1546:                                 if (exists($currrules->{'default'})) {
                   1547:                                     $rule_in_effect = $currrules->{'default'};
                   1548:                                 }
                   1549:                             }
                   1550:                         }
                   1551:                     } else {
                   1552:                         if (exists($currrules->{'default'})) {
                   1553:                             $rule_in_effect = $currrules->{'default'};
                   1554:                         }
                   1555:                     }
                   1556:                 } else {
                   1557:                     if ($currrules->{'_LC_external'} ne '') {
                   1558:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1559:                     }
                   1560:                 }
                   1561:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1562:                                                        $uname,$udom);
                   1563:             }
                   1564:         }
                   1565:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1566:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1567:         unless (defined($cached)) {
                   1568:             my %domconfig =
                   1569:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1570:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1571:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1572:             } else {
                   1573:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1574:             }
                   1575:         }
                   1576:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1577:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1578:                 &check_balancer_result($result,@hosts);
                   1579:             if ($is_balancer) {
1.1129    raeburn  1580:                 if (ref($currrules) eq 'HASH') {
                   1581:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1582:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1583:                     }
                   1584:                 }
                   1585:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1586:                                                        $uname,$udom);
                   1587:             }
                   1588:         } else {
                   1589:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1590:                 $is_balancer = 1;
                   1591:                 $offloadto = &this_host_spares($dom_in_use);
                   1592:             }
1.1307    raeburn  1593:             unless (defined($cached)) {
                   1594:                 $domneedscache = $serverhomedom;
                   1595:             }
1.1129    raeburn  1596:         }
                   1597:     } else {
                   1598:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1599:             $is_balancer = 1;
                   1600:             $offloadto = &this_host_spares($dom_in_use);
                   1601:         }
1.1307    raeburn  1602:         unless (defined($cached)) {
                   1603:             $domneedscache = $serverhomedom;
                   1604:         }
                   1605:     }
                   1606:     if ($domneedscache) {
                   1607:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1608:     }
1.1176    raeburn  1609:     if ($is_balancer) {
                   1610:         my $lowest_load = 30000;
                   1611:         if (ref($offloadto) eq 'HASH') {
                   1612:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1613:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1614:                     ($otherserver,$lowest_load) =
                   1615:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1616:                 }
1.1129    raeburn  1617:             }
1.1176    raeburn  1618:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1619: 
1.1176    raeburn  1620:             if (!$found_server) {
                   1621:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1622:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1623:                         ($otherserver,$lowest_load) =
                   1624:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1625:                     }
                   1626:                 }
                   1627:             }
                   1628:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1629:             if (@{$offloadto} == 1) {
                   1630:                 $otherserver = $offloadto->[0];
                   1631:             } elsif (@{$offloadto} > 1) {
                   1632:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1633:                     ($otherserver,$lowest_load) =
                   1634:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1635:                 }
                   1636:             }
                   1637:         }
1.1331    raeburn  1638:         unless ($caller eq 'login') {
                   1639:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1640:                 $is_balancer = 0;
                   1641:                 if ($uname ne '' && $udom ne '') {
                   1642:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1643:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1644:                                  'user.loadbalcheck.time' => time});
                   1645:                     }
1.1176    raeburn  1646:                 }
1.1129    raeburn  1647:             }
                   1648:         }
1.1389    raeburn  1649:         unless ($homeintdom) {
                   1650:             undef($setcookie);
                   1651:         }
1.1129    raeburn  1652:     }
1.1391    raeburn  1653:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1654: }
                   1655: 
1.1191    raeburn  1656: sub check_balancer_result {
                   1657:     my ($result,@hosts) = @_;
1.1391    raeburn  1658:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1659:     if (ref($result) eq 'HASH') {
                   1660:         if ($result->{'lonhost'} ne '') {
                   1661:             my $currbalancer = $result->{'lonhost'};
                   1662:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1663:                 $is_balancer = 1;
                   1664:                 $currtargets = $result->{'targets'};
                   1665:                 $currrules = $result->{'rules'};
                   1666:             }
1.1391    raeburn  1667:             $dom_balancers = $currbalancer;
1.1191    raeburn  1668:         } else {
1.1391    raeburn  1669:             if (keys(%{$result})) {
                   1670:                 foreach my $key (keys(%{$result})) {
                   1671:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1672:                         (ref($result->{$key}) eq 'HASH')) {
                   1673:                         $is_balancer = 1;
                   1674:                         $currrules = $result->{$key}{'rules'};
                   1675:                         $currtargets = $result->{$key}{'targets'};
                   1676:                         $setcookie = $result->{$key}{'cookie'};
                   1677:                         last;
                   1678:                     }
1.1191    raeburn  1679:                 }
1.1391    raeburn  1680:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1681:             }
                   1682:         }
                   1683:     }
1.1391    raeburn  1684:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1685: }
                   1686: 
1.1129    raeburn  1687: sub get_loadbalancer_targets {
                   1688:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1689:     my $offloadto;
1.1175    raeburn  1690:     if ($rule_in_effect eq 'none') {
                   1691:         return [$perlvar{'lonHostID'}];
                   1692:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1693:         $offloadto = $currtargets;
                   1694:     } else {
                   1695:         if ($rule_in_effect eq 'homeserver') {
                   1696:             my $homeserver = &homeserver($uname,$udom);
                   1697:             if ($homeserver ne 'no_host') {
                   1698:                 $offloadto = [$homeserver];
                   1699:             }
                   1700:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1701:             my %domconfig =
                   1702:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1703:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1704:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1705:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1706:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1707:                     }
                   1708:                 }
                   1709:             } else {
1.1178    raeburn  1710:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1711:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1712:                 if (&hostname($remotebalancer) ne '') {
                   1713:                     $offloadto = [$remotebalancer];
                   1714:                 }
                   1715:             }
                   1716:         } elsif (&hostname($rule_in_effect) ne '') {
                   1717:             $offloadto = [$rule_in_effect];
                   1718:         }
                   1719:     }
                   1720:     return $offloadto;
                   1721: }
                   1722: 
1.1127    raeburn  1723: sub internet_dom_servers {
                   1724:     my ($dom) = @_;
                   1725:     my (%uniqservers,%servers);
                   1726:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1727:     my @machinedoms = &machine_domains($primaryserver);
                   1728:     foreach my $mdom (@machinedoms) {
                   1729:         my %currservers = %servers;
                   1730:         my %server = &get_servers($mdom);
                   1731:         %servers = (%currservers,%server);
                   1732:     }
                   1733:     my %by_hostname;
                   1734:     foreach my $id (keys(%servers)) {
                   1735:         push(@{$by_hostname{$servers{$id}}},$id);
                   1736:     }
                   1737:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1738:         if (@{$by_hostname{$hostname}} > 1) {
                   1739:             my $match = 0;
                   1740:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1741:                 if (&host_domain($id) eq $dom) {
                   1742:                     $uniqservers{$id} = $hostname;
                   1743:                     $match = 1;
                   1744:                 }
                   1745:             }
                   1746:             unless ($match) {
                   1747:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1748:             }
                   1749:         } else {
                   1750:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1751:         }
                   1752:     }
                   1753:     return %uniqservers;
                   1754: }
                   1755: 
1.1347    raeburn  1756: sub trusted_domains {
                   1757:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1758:     my ($trusted,$untrusted);
1.1347    raeburn  1759:     if (&domain($calldom) eq '') {
1.1349    raeburn  1760:         return ($trusted,$untrusted);
1.1347    raeburn  1761:     }
1.1395    raeburn  1762:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1763:         return ($trusted,$untrusted);
1.1347    raeburn  1764:     }
                   1765:     my $callprimary = &domain($calldom,'primary');
                   1766:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1767:     if ($intcalldom eq '') {
1.1349    raeburn  1768:         return ($trusted,$untrusted);
1.1347    raeburn  1769:     }
                   1770: 
                   1771:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1772:     unless (defined($cached)) {
                   1773:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1774:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1775:         $trustconfig = $domconfig{'trust'};
                   1776:     }
                   1777:     if (ref($trustconfig)) {
                   1778:         my (%possexc,%possinc,@allexc,@allinc); 
                   1779:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1780:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1781:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1782:             }
                   1783:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1784:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1785:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1786:             }
                   1787:         }
                   1788:         if (keys(%possexc)) {
                   1789:             if (keys(%possinc)) {
                   1790:                 foreach my $key (sort(keys(%possexc))) {
                   1791:                     next if ($key eq $intcalldom);
                   1792:                     unless ($possinc{$key}) {
                   1793:                         push(@allexc,$key);
                   1794:                     }
                   1795:                 }
                   1796:             } else {
                   1797:                 @allexc = sort(keys(%possexc));
                   1798:             }
                   1799:         }
                   1800:         if (keys(%possinc)) {
                   1801:             $possinc{$intcalldom} = 1;
                   1802:             @allinc = sort(keys(%possinc));
                   1803:         }
                   1804:         if ((@allexc > 0) || (@allinc > 0)) {
                   1805:             my %doms_by_intdom;
                   1806:             my %allintdoms = &all_host_intdom();
                   1807:             my %alldoms = &all_host_domain();
                   1808:             foreach my $key (%allintdoms) {
                   1809:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1810:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1811:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1812:                     }
                   1813:                 } else {
                   1814:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1815:                 }
                   1816:             }
                   1817:             foreach my $exc (@allexc) {
                   1818:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1819:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1820:                 }
                   1821:             }
                   1822:             foreach my $inc (@allinc) {
                   1823:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1824:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1825:                 }
                   1826:             }
                   1827:         }
                   1828:     }
1.1349    raeburn  1829:     return ($trusted,$untrusted);
1.1347    raeburn  1830: }
                   1831: 
                   1832: sub will_trust {
                   1833:     my ($cmdtype,$domain,$possdom) = @_;
                   1834:     return 1 if ($domain eq $possdom);
                   1835:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1836:     my $willtrust; 
                   1837:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1838:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1839:             $willtrust = 1;
                   1840:         }
                   1841:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1842:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1843:             $willtrust = 1;
                   1844:         }
                   1845:     } else {
                   1846:         $willtrust = 1;
                   1847:     }
                   1848:     return $willtrust;
                   1849: }
                   1850: 
1.1       albertel 1851: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1852: 
1.599     albertel 1853: my %homecache;
1.1       albertel 1854: sub homeserver {
1.230     stredwic 1855:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1856:     my $index="$uname:$udom";
1.426     albertel 1857: 
1.599     albertel 1858:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1859: 
                   1860:     my %servers = &get_servers($udom,'library');
                   1861:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1862:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1863: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1864: 
                   1865: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1866: 	if ($answer eq 'found') {
                   1867: 	    delete($badServerCache{$tryserver}); 
                   1868: 	    return $homecache{$index}=$tryserver;
                   1869: 	} elsif ($answer eq 'no_host') {
                   1870: 	    $badServerCache{$tryserver}=1;
                   1871: 	}
1.1       albertel 1872:     }    
                   1873:     return 'no_host';
1.70      www      1874: }
                   1875: 
1.1300    raeburn  1876: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1877: 
                   1878: sub idget {
1.1300    raeburn  1879:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1880:     my %returnhash=();
1.1300    raeburn  1881:     my @ids=(); 
                   1882:     if (ref($idsref) eq 'ARRAY') {
                   1883:         @ids = @{$idsref};
                   1884:     } else {
                   1885:         return %returnhash; 
                   1886:     }
                   1887:     if ($namespace eq '') {
                   1888:         $namespace = 'ids';
                   1889:     }
1.70      www      1890:     
1.841     albertel 1891:     my %servers = &get_servers($udom,'library');
                   1892:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1893: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1894: 	if ($namespace eq 'ids') {
                   1895: 	    $idlist=~tr/A-Z/a-z/;
                   1896: 	}
                   1897: 	my $reply;
                   1898: 	if ($namespace eq 'ids') {
                   1899: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1900: 	} else {
                   1901: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1902: 	}
1.841     albertel 1903: 	my @answer=();
                   1904: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1905: 	    @answer=split(/\&/,$reply);
                   1906: 	}                    ;
                   1907: 	my $i;
                   1908: 	for ($i=0;$i<=$#ids;$i++) {
                   1909: 	    if ($answer[$i]) {
1.1299    raeburn  1910: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1911: 	    }
1.841     albertel 1912: 	}
1.1300    raeburn  1913:     }
1.70      www      1914:     return %returnhash;
                   1915: }
                   1916: 
                   1917: # ------------------------------------- Find the IDs behind a list of usernames
                   1918: 
                   1919: sub idrget {
                   1920:     my ($udom,@unames)=@_;
                   1921:     my %returnhash=();
1.800     albertel 1922:     foreach my $uname (@unames) {
                   1923:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1924:     }
1.70      www      1925:     return %returnhash;
                   1926: }
                   1927: 
1.1300    raeburn  1928: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1929: 
                   1930: sub idput {
1.1300    raeburn  1931:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1932:     my %servers=();
1.1300    raeburn  1933:     my %ids=();
                   1934:     my %byid = ();
                   1935:     if (ref($idsref) eq 'HASH') {
                   1936:         %ids=%{$idsref};
                   1937:     }
                   1938:     if ($namespace eq '') {
                   1939:         $namespace = 'ids'; 
                   1940:     }
1.800     albertel 1941:     foreach my $uname (keys(%ids)) {
                   1942: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1943:         if ($uhom eq '') {
                   1944:             $uhom=&homeserver($uname,$udom);
                   1945:         }
1.70      www      1946:         if ($uhom ne 'no_host') {
1.800     albertel 1947:             my $esc_unam=&escape($uname);
1.1300    raeburn  1948:             if ($namespace eq 'ids') {
                   1949:                 my $id=&escape($ids{$uname});
                   1950:                 $id=~tr/A-Z/a-z/;
                   1951:                 my $esc_unam=&escape($uname);
                   1952:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1953:             } else {
1.1300    raeburn  1954:                 my @currids = split(/,/,$ids{$uname});
                   1955:                 foreach my $id (@currids) {
                   1956:                     $byid{$uhom}{$id} .= $uname.',';
                   1957:                 }
                   1958:             }
                   1959:         }
                   1960:     }
                   1961:     if ($namespace eq 'clickers') {
                   1962:         foreach my $server (keys(%byid)) {
                   1963:             if (ref($byid{$server}) eq 'HASH') {
                   1964:                 foreach my $id (keys(%{$byid{$server}})) {
                   1965:                     $byid{$server} =~ s/,$//;
                   1966:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1967:                 }
1.70      www      1968:             }
                   1969:         }
1.191     harris41 1970:     }
1.800     albertel 1971:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1972:         $servers{$server} =~ s/\&$//;
                   1973:         if ($namespace eq 'ids') {     
                   1974:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1975:         } else {
                   1976:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1977:         }
1.191     harris41 1978:     }
1.344     www      1979: }
                   1980: 
1.1300    raeburn  1981: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1982: 
                   1983: sub iddel {
1.1300    raeburn  1984:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1985:     my %result=();
1.1300    raeburn  1986:     my %ids=();
                   1987:     my %byid = ();
                   1988:     if (ref($idshashref) eq 'HASH') {
                   1989:         %ids=%{$idshashref};
                   1990:     } else {
1.1231    raeburn  1991:         return %result;
                   1992:     }
1.1300    raeburn  1993:     if ($namespace eq '') {
                   1994:         $namespace = 'ids';
                   1995:     }
1.1231    raeburn  1996:     my %servers=();
1.1300    raeburn  1997:     while (my ($id,$unamestr) = each(%ids)) {
                   1998:         if ($namespace eq 'ids') {
                   1999:             my $uhom = $uhome;
                   2000:             if ($uhom eq '') { 
                   2001:                 $uhom=&homeserver($unamestr,$udom);
                   2002:             }
                   2003:             if ($uhom ne 'no_host') {
                   2004:                 $servers{$uhom}.='&'.&escape($id);
                   2005:             }
                   2006:          } else {
                   2007:             my @curritems = split(/,/,$ids{$id});
                   2008:             foreach my $uname (@curritems) {
                   2009:                 my $uhom = $uhome;
                   2010:                 if ($uhom eq '') {
                   2011:                     $uhom=&homeserver($uname,$udom);
                   2012:                 }
                   2013:                 if ($uhom ne 'no_host') { 
                   2014:                     $byid{$uhom}{$id} .= $uname.',';
                   2015:                 }
                   2016:             }
1.1231    raeburn  2017:         }
1.1300    raeburn  2018:     }
                   2019:     if ($namespace eq 'clickers') {
                   2020:         foreach my $server (keys(%byid)) {
                   2021:             if (ref($byid{$server}) eq 'HASH') {
                   2022:                 foreach my $id (keys(%{$byid{$server}})) {
                   2023:                     $byid{$server}{$id} =~ s/,$//;
                   2024:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2025:                 }
1.1231    raeburn  2026:             }
                   2027:         }
                   2028:     }
                   2029:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2030:         $servers{$server} =~ s/\&$//;
                   2031:         if ($namespace eq 'ids') {
                   2032:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2033:         } elsif ($namespace eq 'clickers') {
                   2034:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2035:         }
1.1231    raeburn  2036:     }
                   2037:     return %result;
                   2038: }
                   2039: 
1.1300    raeburn  2040: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2041: 
                   2042: sub updateclickers {
                   2043:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2044:     my %clickers;
                   2045:     if (ref($idshashref) eq 'HASH') {
                   2046:         %clickers=%{$idshashref};
                   2047:     } else {
                   2048:         return;
                   2049:     }
                   2050:     my $items='';
                   2051:     foreach my $item (keys(%clickers)) {
                   2052:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2053:     }
                   2054:     $items=~s/\&$//;
                   2055:     my $request = "updateclickers:$udom:$action:$items";
                   2056:     if ($critical) {
                   2057:         return &critical($request,$uhome);
                   2058:     } else {
                   2059:         return &reply($request,$uhome);
                   2060:     }
                   2061: }
                   2062: 
1.1023    raeburn  2063: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2064: sub dump_dom {
1.1165    droeschl 2065:     my ($namespace, $udom, $regexp) = @_;
                   2066: 
                   2067:     $udom ||= $env{'user.domain'};
                   2068: 
                   2069:     return () unless $udom;
                   2070: 
                   2071:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2072: }
                   2073: 
1.1023    raeburn  2074: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2075: 
                   2076: sub get_dom {
1.860     raeburn  2077:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2078:     return if ($udom eq 'public');
1.806     raeburn  2079:     my $items='';
                   2080:     foreach my $item (@$storearr) {
                   2081:         $items.=&escape($item).'&';
                   2082:     }
                   2083:     $items=~s/\&$//;
1.860     raeburn  2084:     if (!$udom) {
                   2085:         $udom=$env{'user.domain'};
1.1267    raeburn  2086:         return if ($udom eq 'public');
1.860     raeburn  2087:         if (defined(&domain($udom,'primary'))) {
                   2088:             $uhome=&domain($udom,'primary');
                   2089:         } else {
1.874     albertel 2090:             undef($uhome);
1.860     raeburn  2091:         }
                   2092:     } else {
                   2093:         if (!$uhome) {
                   2094:             if (defined(&domain($udom,'primary'))) {
                   2095:                 $uhome=&domain($udom,'primary');
                   2096:             }
                   2097:         }
                   2098:     }
                   2099:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2100:         my $rep;
                   2101:         if ($namespace =~ /^enc/) {
                   2102:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2103:         } else {
                   2104:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2105:         }
1.866     raeburn  2106:         my %returnhash;
1.875     albertel 2107:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2108:             return %returnhash;
                   2109:         }
1.806     raeburn  2110:         my @pairs=split(/\&/,$rep);
                   2111:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2112:             return @pairs;
                   2113:         }
                   2114:         my $i=0;
                   2115:         foreach my $item (@$storearr) {
                   2116:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2117:             $i++;
                   2118:         }
                   2119:         return %returnhash;
                   2120:     } else {
1.880     banghart 2121:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2122:     }
                   2123: }
                   2124: 
                   2125: # -------------------------------------------- put items in domain db files 
                   2126: 
                   2127: sub put_dom {
1.860     raeburn  2128:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2129:     if (!$udom) {
                   2130:         $udom=$env{'user.domain'};
                   2131:         if (defined(&domain($udom,'primary'))) {
                   2132:             $uhome=&domain($udom,'primary');
                   2133:         } else {
1.874     albertel 2134:             undef($uhome);
1.860     raeburn  2135:         }
                   2136:     } else {
                   2137:         if (!$uhome) {
                   2138:             if (defined(&domain($udom,'primary'))) {
                   2139:                 $uhome=&domain($udom,'primary');
                   2140:             }
                   2141:         }
                   2142:     } 
                   2143:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2144:         my $items='';
                   2145:         foreach my $item (keys(%$storehash)) {
                   2146:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2147:         }
                   2148:         $items=~s/\&$//;
1.1344    raeburn  2149:         if ($namespace =~ /^enc/) {
                   2150:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2151:         } else {
                   2152:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2153:         }
1.806     raeburn  2154:     } else {
1.860     raeburn  2155:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2156:     }
                   2157: }
                   2158: 
1.1023    raeburn  2159: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2160: sub newput_dom {
1.1023    raeburn  2161:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2162:     my $result;
                   2163:     if (!$udom) {
                   2164:         $udom=$env{'user.domain'};
                   2165:     }
1.1023    raeburn  2166:     if ($udom) {
                   2167:         my $uname = &get_domainconfiguser($udom);
                   2168:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2169:     }
                   2170:     return $result;
                   2171: }
                   2172: 
1.1023    raeburn  2173: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2174: sub del_dom {
1.1023    raeburn  2175:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2176:     if (ref($storearr) eq 'ARRAY') {
                   2177:         if (!$udom) {
                   2178:             $udom=$env{'user.domain'};
                   2179:         }
1.1023    raeburn  2180:         if ($udom) {
                   2181:             my $uname = &get_domainconfiguser($udom); 
                   2182:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2183:         }
                   2184:     }
                   2185: }
                   2186: 
1.1023    raeburn  2187: # ----------------------------------construct domainconfig user for a domain 
                   2188: sub get_domainconfiguser {
                   2189:     my ($udom) = @_;
                   2190:     return $udom.'-domainconfig';
                   2191: }
                   2192: 
1.837     raeburn  2193: sub retrieve_inst_usertypes {
                   2194:     my ($udom) = @_;
                   2195:     my (%returnhash,@order);
1.989     raeburn  2196:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2197:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2198:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2199:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2200:     } else {
                   2201:         if (defined(&domain($udom,'primary'))) {
                   2202:             my $uhome=&domain($udom,'primary');
                   2203:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2204:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2205:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2206:                 return (\%returnhash,\@order);
                   2207:             }
                   2208:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2209:             my @pairs=split(/\&/,$hashitems);
                   2210:             foreach my $item (@pairs) {
                   2211:                 my ($key,$value)=split(/=/,$item,2);
                   2212:                 $key = &unescape($key);
                   2213:                 next if ($key =~ /^error: 2 /);
                   2214:                 $returnhash{$key}=&thaw_unescape($value);
                   2215:             }
                   2216:             my @esc_order = split(/\&/,$orderitems);
                   2217:             foreach my $item (@esc_order) {
                   2218:                 push(@order,&unescape($item));
                   2219:             }
                   2220:         } else {
1.1256    raeburn  2221:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2222:         }
1.1256    raeburn  2223:         return (\%returnhash,\@order);
1.837     raeburn  2224:     }
                   2225: }
                   2226: 
1.868     raeburn  2227: sub is_domainimage {
                   2228:     my ($url) = @_;
1.1306    raeburn  2229:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2230:         if (&domain($1) ne '') {
                   2231:             return '1';
                   2232:         }
                   2233:     }
                   2234:     return;
                   2235: }
                   2236: 
1.899     raeburn  2237: sub inst_directory_query {
                   2238:     my ($srch) = @_;
                   2239:     my $udom = $srch->{'srchdomain'};
                   2240:     my %results;
                   2241:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2242:     my $outcome;
1.899     raeburn  2243:     if ($homeserver ne '') {
1.1357    raeburn  2244:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2245:             if ($srch->{'srchby'} eq 'email') {
                   2246:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2247:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2248:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2249:                     (($major == 2) && ($minor < 12))) {
                   2250:                     return;
                   2251:                 }
                   2252:             }
                   2253:         }
1.904     albertel 2254: 	my $queryid=&reply("querysend:instdirsearch:".
                   2255: 			   &escape($srch->{'srchby'}).':'.
                   2256: 			   &escape($srch->{'srchterm'}).':'.
                   2257: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2258: 	my $host=&hostname($homeserver);
                   2259: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2260: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2261: 	    return;
                   2262: 	}
                   2263: 	my $response = &get_query_reply($queryid);
                   2264: 	my $maxtries = 5;
                   2265: 	my $tries = 1;
                   2266: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2267: 	    $response = &get_query_reply($queryid);
                   2268: 	    $tries ++;
                   2269: 	}
                   2270: 
                   2271:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2272:             if ($response eq 'unavailable') {
                   2273:                 $outcome = $response;
                   2274:             } else {
                   2275:                 $outcome = 'ok';
                   2276:                 my @matches = split(/\n/,$response);
                   2277:                 foreach my $match (@matches) {
                   2278:                     my ($key,$value) = split(/=/,$match);
                   2279:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2280:                 }
1.899     raeburn  2281:             }
                   2282:         }
                   2283:     }
1.909     raeburn  2284:     return ($outcome,%results);
1.899     raeburn  2285: }
                   2286: 
                   2287: sub usersearch {
                   2288:     my ($srch) = @_;
                   2289:     my $dom = $srch->{'srchdomain'};
                   2290:     my %results;
                   2291:     my %libserv = &all_library();
                   2292:     my $query = 'usersearch';
                   2293:     foreach my $tryserver (keys(%libserv)) {
                   2294:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2295:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2296:                 if ($srch->{'srchby'} eq 'email') {
                   2297:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2298:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2299:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2300:                              (($major == 2) && ($minor < 12)));
                   2301:                 }
                   2302:             }
1.899     raeburn  2303:             my $host=&hostname($tryserver);
                   2304:             my $queryid=
1.911     raeburn  2305:                 &reply("querysend:".&escape($query).':'.
                   2306:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2307:                        &escape($srch->{'srchtype'}).':'.
                   2308:                        &escape($srch->{'srchterm'}),$tryserver);
                   2309:             if ($queryid !~/^\Q$host\E\_/) {
                   2310:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2311:                 next;
1.899     raeburn  2312:             }
                   2313:             my $reply = &get_query_reply($queryid);
                   2314:             my $maxtries = 1;
                   2315:             my $tries = 1;
                   2316:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2317:                 $reply = &get_query_reply($queryid);
                   2318:                 $tries ++;
                   2319:             }
                   2320:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2321:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2322:             } else {
1.911     raeburn  2323:                 my @matches;
                   2324:                 if ($reply =~ /\n/) {
                   2325:                     @matches = split(/\n/,$reply);
                   2326:                 } else {
                   2327:                     @matches = split(/\&/,$reply);
                   2328:                 }
1.899     raeburn  2329:                 foreach my $match (@matches) {
                   2330:                     my ($uname,$udom,%userhash);
1.911     raeburn  2331:                     foreach my $entry (split(/:/,$match)) {
                   2332:                         my ($key,$value) =
                   2333:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2334:                         $userhash{$key} = $value;
                   2335:                         if ($key eq 'username') {
                   2336:                             $uname = $value;
                   2337:                         } elsif ($key eq 'domain') {
                   2338:                             $udom = $value;
1.911     raeburn  2339:                         }
1.899     raeburn  2340:                     }
                   2341:                     $results{$uname.':'.$udom} = \%userhash;
                   2342:                 }
                   2343:             }
                   2344:         }
                   2345:     }
                   2346:     return %results;
                   2347: }
                   2348: 
1.912     raeburn  2349: sub get_instuser {
                   2350:     my ($udom,$uname,$id) = @_;
                   2351:     my $homeserver = &domain($udom,'primary');
                   2352:     my ($outcome,%results);
                   2353:     if ($homeserver ne '') {
                   2354:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2355:                            &escape($id).':'.&escape($udom),$homeserver);
                   2356:         my $host=&hostname($homeserver);
                   2357:         if ($queryid !~/^\Q$host\E\_/) {
                   2358:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2359:             return;
                   2360:         }
                   2361:         my $response = &get_query_reply($queryid);
                   2362:         my $maxtries = 5;
                   2363:         my $tries = 1;
                   2364:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2365:             $response = &get_query_reply($queryid);
                   2366:             $tries ++;
                   2367:         }
                   2368:         if (!&error($response) && $response ne 'refused') {
                   2369:             if ($response eq 'unavailable') {
                   2370:                 $outcome = $response;
                   2371:             } else {
                   2372:                 $outcome = 'ok';
                   2373:                 my @matches = split(/\n/,$response);
                   2374:                 foreach my $match (@matches) {
                   2375:                     my ($key,$value) = split(/=/,$match);
                   2376:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2377:                 }
                   2378:             }
                   2379:         }
                   2380:     }
                   2381:     my %userinfo;
                   2382:     if (ref($results{$uname}) eq 'HASH') {
                   2383:         %userinfo = %{$results{$uname}};
                   2384:     } 
                   2385:     return ($outcome,%userinfo);
                   2386: }
                   2387: 
1.1290    raeburn  2388: sub get_multiple_instusers {
                   2389:     my ($udom,$users,$caller) = @_;
                   2390:     my ($outcome,$results);
                   2391:     if (ref($users) eq 'HASH') {
                   2392:         my $count = keys(%{$users}); 
                   2393:         my $requested = &freeze_escape($users);
                   2394:         my $homeserver = &domain($udom,'primary');
                   2395:         if ($homeserver ne '') {
                   2396:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2397:             my $host=&hostname($homeserver);
                   2398:             if ($queryid !~/^\Q$host\E\_/) {
                   2399:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2400:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2401:                 return ($outcome,$results);
                   2402:             }
                   2403:             my $response = &get_query_reply($queryid);
                   2404:             my $maxtries = 5;
                   2405:             if ($count > 100) {
                   2406:                 $maxtries = 1+int($count/20);
                   2407:             }
                   2408:             my $tries = 1;
                   2409:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2410:                 $response = &get_query_reply($queryid);
                   2411:                 $tries ++;
                   2412:             }
                   2413:             if ($response eq '') {
                   2414:                 $results = {};
                   2415:                 foreach my $key (keys(%{$users})) {
                   2416:                     my ($uname,$id);
                   2417:                     if ($caller eq 'id') {
                   2418:                         $id = $key;
                   2419:                     } else {
                   2420:                         $uname = $key;
                   2421:                     }
                   2422:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2423:                     $outcome = $resp;
1.1290    raeburn  2424:                     if ($resp eq 'ok') {
                   2425:                         %{$results} = (%{$results}, %info);
                   2426:                     } else {
                   2427:                         last;
                   2428:                     }
                   2429:                 }
                   2430:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2431:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2432:                     $outcome = $response;
                   2433:                 } else {
1.1291    raeburn  2434:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2435:                     if ($outcome eq 'ok') {
                   2436:                         $results = &thaw_unescape($userdata); 
                   2437:                     }
                   2438:                 }
                   2439:             }
                   2440:         }
                   2441:     }
                   2442:     return ($outcome,$results);
                   2443: }
                   2444: 
1.912     raeburn  2445: sub inst_rulecheck {
1.923     raeburn  2446:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2447:     my %returnhash;
                   2448:     if ($udom ne '') {
                   2449:         if (ref($rules) eq 'ARRAY') {
                   2450:             @{$rules} = map {&escape($_);} (@{$rules});
                   2451:             my $rulestr = join(':',@{$rules});
                   2452:             my $homeserver=&domain($udom,'primary');
                   2453:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2454:                 my $response;
                   2455:                 if ($item eq 'username') {                
                   2456:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2457:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2458:                                               $homeserver));
1.923     raeburn  2459:                 } elsif ($item eq 'id') {
                   2460:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2461:                                               ':'.&escape($id).':'.$rulestr,
                   2462:                                               $homeserver));
1.945     raeburn  2463:                 } elsif ($item eq 'selfcreate') {
                   2464:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2465:                                                &escape($udom).':'.&escape($uname).
                   2466:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2467:                 }
1.912     raeburn  2468:                 if ($response ne 'refused') {
                   2469:                     my @pairs=split(/\&/,$response);
                   2470:                     foreach my $item (@pairs) {
                   2471:                         my ($key,$value)=split(/=/,$item,2);
                   2472:                         $key = &unescape($key);
                   2473:                         next if ($key =~ /^error: 2 /);
                   2474:                         $returnhash{$key}=&thaw_unescape($value);
                   2475:                     }
                   2476:                 }
                   2477:             }
                   2478:         }
                   2479:     }
                   2480:     return %returnhash;
                   2481: }
                   2482: 
                   2483: sub inst_userrules {
1.923     raeburn  2484:     my ($udom,$check) = @_;
1.912     raeburn  2485:     my (%ruleshash,@ruleorder);
                   2486:     if ($udom ne '') {
                   2487:         my $homeserver=&domain($udom,'primary');
                   2488:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2489:             my $response;
                   2490:             if ($check eq 'id') {
                   2491:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2492:                                  $homeserver);
1.943     raeburn  2493:             } elsif ($check eq 'email') {
                   2494:                 $response=&reply('instemailrules:'.&escape($udom),
                   2495:                                  $homeserver);
1.923     raeburn  2496:             } else {
                   2497:                 $response=&reply('instuserrules:'.&escape($udom),
                   2498:                                  $homeserver);
                   2499:             }
1.912     raeburn  2500:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2501:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2502:                 ($response ne 'no_such_host')) {
                   2503:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2504:                 my @pairs=split(/\&/,$hashitems);
                   2505:                 foreach my $item (@pairs) {
                   2506:                     my ($key,$value)=split(/=/,$item,2);
                   2507:                     $key = &unescape($key);
                   2508:                     next if ($key =~ /^error: 2 /);
                   2509:                     $ruleshash{$key}=&thaw_unescape($value);
                   2510:                 }
                   2511:                 my @esc_order = split(/\&/,$orderitems);
                   2512:                 foreach my $item (@esc_order) {
                   2513:                     push(@ruleorder,&unescape($item));
                   2514:                 }
                   2515:             }
                   2516:         }
                   2517:     }
                   2518:     return (\%ruleshash,\@ruleorder);
                   2519: }
                   2520: 
1.976     raeburn  2521: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2522: 
                   2523: sub get_domain_defaults {
1.1240    raeburn  2524:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2525:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2526:     my $cachetime = 60*60*24;
1.1240    raeburn  2527:     unless ($ignore_cache) {
                   2528:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2529:         if (defined($cached)) {
                   2530:             if (ref($result) eq 'HASH') {
                   2531:                 return %{$result};
                   2532:             }
1.943     raeburn  2533:         }
                   2534:     }
                   2535:     my %domdefaults;
                   2536:     my %domconfig =
1.989     raeburn  2537:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2538:                                   'requestcourses','inststatus',
1.1183    raeburn  2539:                                   'coursedefaults','usersessions',
1.1258    raeburn  2540:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2541:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2542:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2543:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2544:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2545:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2546:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2547:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2548:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2549:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2550:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2551:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2552:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2553:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2554:     } else {
                   2555:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2556:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2557:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2558:     }
1.976     raeburn  2559:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2560:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2561:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2562:         } else {
                   2563:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2564:         }
1.1177    raeburn  2565:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2566:         foreach my $item (@usertools) {
                   2567:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2568:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2569:             }
                   2570:         }
1.1229    raeburn  2571:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2572:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2573:         }
1.976     raeburn  2574:     }
1.985     raeburn  2575:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2576:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2577:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2578:         }
                   2579:     }
1.1183    raeburn  2580:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2581:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2582:     }
1.989     raeburn  2583:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2584:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2585:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2586:         }
                   2587:     }
1.1047    raeburn  2588:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2589:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2590:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2591:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2592:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2593:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2594:         }
1.1254    raeburn  2595:         foreach my $type (@coursetypes) {
                   2596:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2597:                 unless ($type eq 'community') {
                   2598:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2599:                 }
                   2600:             }
                   2601:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2602:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2603:             }
1.1277    raeburn  2604:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2605:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2606:                     $domdefaults{$type.'postsubtimeout'} = 
                   2607:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2608:                 }
                   2609:             }
1.1230    raeburn  2610:         }
1.1286    raeburn  2611:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2612:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2613:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2614:                 if (@clonecodes) {
                   2615:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2616:                 }
                   2617:             }
                   2618:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2619:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2620:         }
1.1356    raeburn  2621:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2622:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2623:         } 
1.1047    raeburn  2624:     }
1.1073    raeburn  2625:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2626:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2627:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2628:         }
                   2629:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2630:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2631:         }
1.1279    raeburn  2632:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2633:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2634:         }
1.1073    raeburn  2635:     }
1.1254    raeburn  2636:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2637:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2638:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2639:                             'approval','limit');
                   2640:             foreach my $type (@coursetypes) {
                   2641:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2642:                     my @mgrdc = ();
                   2643:                     foreach my $item (@settings) {
                   2644:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2645:                             push(@mgrdc,$item);
                   2646:                         }
                   2647:                     }
                   2648:                     if (@mgrdc) {
                   2649:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2650:                     }
                   2651:                 }
                   2652:             }
                   2653:         }
                   2654:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2655:             foreach my $type (@coursetypes) {
                   2656:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2657:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2658:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2659:                     }
                   2660:                 }
                   2661:             }
                   2662:         }
                   2663:     }
1.1258    raeburn  2664:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2665:         $domdefaults{'catauth'} = 'std';
                   2666:         $domdefaults{'catunauth'} = 'std';
                   2667:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2668:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2669:         }
                   2670:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2671:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2672:         }
                   2673:     }
1.1315    raeburn  2674:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2675:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2676:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2677:         }
1.1338    raeburn  2678:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2679:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2680:         }
                   2681:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2682:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2683:         }
                   2684:     }
1.1320    raeburn  2685:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2686:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2687:         foreach my $prefix (@prefixes) {
                   2688:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2689:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2690:             }
                   2691:         }
                   2692:     }
1.1314    raeburn  2693:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2694:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2695:     }
1.1332    raeburn  2696:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2697:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2698:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2699:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2700:         }
                   2701:     }
1.1219    raeburn  2702:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2703:     return %domdefaults;
                   2704: }
                   2705: 
1.1311    raeburn  2706: sub course_portal_url {
                   2707:     my ($cnum,$cdom) = @_;
                   2708:     my $chome = &homeserver($cnum,$cdom);
                   2709:     my $hostname = &hostname($chome);
                   2710:     my $protocol = $protocol{$chome};
                   2711:     $protocol = 'http' if ($protocol ne 'https');
                   2712:     my %domdefaults = &get_domain_defaults($cdom);
                   2713:     my $firsturl;
                   2714:     if ($domdefaults{'portal_def'}) {
                   2715:         $firsturl = $domdefaults{'portal_def'};
                   2716:     } else {
                   2717:         $firsturl = $protocol.'://'.$hostname;
                   2718:     }
                   2719:     return $firsturl;
                   2720: }
                   2721: 
1.344     www      2722: # --------------------------------------------------- Assign a key to a student
                   2723: 
                   2724: sub assign_access_key {
1.364     www      2725: #
                   2726: # a valid key looks like uname:udom#comments
                   2727: # comments are being appended
                   2728: #
1.498     www      2729:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2730:     $kdom=
1.620     albertel 2731:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2732:     $knum=
1.620     albertel 2733:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2734:     $cdom=
1.620     albertel 2735:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2736:     $cnum=
1.620     albertel 2737:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2738:     $udom=$env{'user.name'} unless (defined($udom));
                   2739:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2740:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2741:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2742:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2743:                                                   # assigned to this person
                   2744:                                                   # - this should not happen,
1.345     www      2745:                                                   # unless something went wrong
                   2746:                                                   # the first time around
                   2747: # ready to assign
1.364     www      2748:         $logentry=$1.'; '.$logentry;
1.496     www      2749:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2750:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2751: # key now belongs to user
1.346     www      2752: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2753:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2754:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2755:                 return 'ok';
                   2756:             } else {
                   2757:                 return 
                   2758:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2759: 	    }
                   2760:         } else {
                   2761:             return 'error: Could not assign key, try again later.';
                   2762:         }
1.364     www      2763:     } elsif (!$existing{$ckey}) {
1.345     www      2764: # the key does not exist
                   2765: 	return 'error: The key does not exist';
                   2766:     } else {
                   2767: # the key is somebody else's
                   2768: 	return 'error: The key is already in use';
                   2769:     }
1.344     www      2770: }
                   2771: 
1.364     www      2772: # ------------------------------------------ put an additional comment on a key
                   2773: 
                   2774: sub comment_access_key {
                   2775: #
                   2776: # a valid key looks like uname:udom#comments
                   2777: # comments are being appended
                   2778: #
                   2779:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2780:     $cdom=
1.620     albertel 2781:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2782:     $cnum=
1.620     albertel 2783:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2784:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2785:     if ($existing{$ckey}) {
                   2786:         $existing{$ckey}.='; '.$logentry;
                   2787: # ready to assign
1.367     www      2788:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2789:                                                  $cdom,$cnum) eq 'ok') {
                   2790: 	    return 'ok';
                   2791:         } else {
                   2792: 	    return 'error: Count not store comment.';
                   2793:         }
                   2794:     } else {
                   2795: # the key does not exist
                   2796: 	return 'error: The key does not exist';
                   2797:     }
                   2798: }
                   2799: 
1.344     www      2800: # ------------------------------------------------------ Generate a set of keys
                   2801: 
                   2802: sub generate_access_keys {
1.364     www      2803:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2804:     $cdom=
1.620     albertel 2805:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2806:     $cnum=
1.620     albertel 2807:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2808:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2809:     unless (($cdom) && ($cnum)) { return 0; }
                   2810:     if ($number>10000) { return 0; }
                   2811:     sleep(2); # make sure don't get same seed twice
                   2812:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2813:     my $total=0;
                   2814:     for (my $i=1;$i<=$number;$i++) {
                   2815:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2816:                   sprintf("%lx",int(100000*rand)).'-'.
                   2817:                   sprintf("%lx",int(100000*rand));
                   2818:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2819:        $newkey=~s/0/h/g; # and also 0 and O
                   2820:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2821:        if ($existing{$newkey}) {
                   2822:            $i--;
                   2823:        } else {
1.364     www      2824: 	  if (&put('accesskeys',
                   2825:               { $newkey => '# generated '.localtime().
1.620     albertel 2826:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2827:                            '; '.$logentry },
                   2828: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2829:               $total++;
                   2830: 	  }
                   2831:        }
                   2832:     }
1.620     albertel 2833:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2834:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2835:     return $total;
                   2836: }
                   2837: 
                   2838: # ------------------------------------------------------- Validate an accesskey
                   2839: 
                   2840: sub validate_access_key {
                   2841:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2842:     $cdom=
1.620     albertel 2843:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2844:     $cnum=
1.620     albertel 2845:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2846:     $udom=$env{'user.domain'} unless (defined($udom));
                   2847:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2848:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2849:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2850: }
                   2851: 
                   2852: # ------------------------------------- Find the section of student in a course
1.652     albertel 2853: sub devalidate_getsection_cache {
                   2854:     my ($udom,$unam,$courseid)=@_;
                   2855:     my $hashid="$udom:$unam:$courseid";
                   2856:     &devalidate_cache_new('getsection',$hashid);
                   2857: }
1.298     matthew  2858: 
1.815     albertel 2859: sub courseid_to_courseurl {
                   2860:     my ($courseid) = @_;
                   2861:     #already url style courseid
                   2862:     return $courseid if ($courseid =~ m{^/});
                   2863: 
                   2864:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2865: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2866: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2867: 	return "/$cdom/$cnum";
                   2868:     }
                   2869: 
                   2870:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2871:     if (exists($courseinfo{'num'})) {
                   2872: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2873:     }
                   2874: 
                   2875:     return undef;
                   2876: }
                   2877: 
1.298     matthew  2878: sub getsection {
                   2879:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2880:     my $cachetime=1800;
1.551     albertel 2881: 
                   2882:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2883:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2884:     if (defined($cached)) { return $result; }
                   2885: 
1.298     matthew  2886:     my %Pending; 
                   2887:     my %Expired;
                   2888:     #
                   2889:     # Each role can either have not started yet (pending), be active, 
                   2890:     #    or have expired.
                   2891:     #
                   2892:     # If there is an active role, we are done.
                   2893:     #
                   2894:     # If there is more than one role which has not started yet, 
                   2895:     #     choose the one which will start sooner
                   2896:     # If there is one role which has not started yet, return it.
                   2897:     #
                   2898:     # If there is more than one expired role, choose the one which ended last.
                   2899:     # If there is a role which has expired, return it.
                   2900:     #
1.815     albertel 2901:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2902:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2903:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2904:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2905:         my $section=$1;
                   2906:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2907:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2908:         my $now=time;
1.548     albertel 2909:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2910:             $Expired{$end}=$section;
                   2911:             next;
                   2912:         }
1.548     albertel 2913:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2914:             $Pending{$start}=$section;
                   2915:             next;
                   2916:         }
1.599     albertel 2917:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2918:     }
                   2919:     #
                   2920:     # Presumedly there will be few matching roles from the above
                   2921:     # loop and the sorting time will be negligible.
                   2922:     if (scalar(keys(%Pending))) {
                   2923:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2924:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2925:     } 
                   2926:     if (scalar(keys(%Expired))) {
                   2927:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2928:         my $time = pop(@sorted);
1.599     albertel 2929:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2930:     }
1.599     albertel 2931:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2932: }
1.70      www      2933: 
1.599     albertel 2934: sub save_cache {
                   2935:     &purge_remembered();
1.722     albertel 2936:     #&Apache::loncommon::validate_page();
1.620     albertel 2937:     undef(%env);
1.780     albertel 2938:     undef($env_loaded);
1.599     albertel 2939: }
1.452     albertel 2940: 
1.599     albertel 2941: my $to_remember=-1;
                   2942: my %remembered;
                   2943: my %accessed;
                   2944: my $kicks=0;
                   2945: my $hits=0;
1.849     albertel 2946: sub make_key {
                   2947:     my ($name,$id) = @_;
1.872     albertel 2948:     if (length($id) > 65 
                   2949: 	&& length(&escape($id)) > 200) {
                   2950: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2951:     }
1.849     albertel 2952:     return &escape($name.':'.$id);
                   2953: }
                   2954: 
1.599     albertel 2955: sub devalidate_cache_new {
                   2956:     my ($name,$id,$debug) = @_;
                   2957:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2958:     my $remembered_id=$name.':'.$id;
1.849     albertel 2959:     $id=&make_key($name,$id);
1.599     albertel 2960:     $memcache->delete($id);
1.1319    damieng  2961:     delete($remembered{$remembered_id});
                   2962:     delete($accessed{$remembered_id});
1.599     albertel 2963: }
                   2964: 
                   2965: sub is_cached_new {
                   2966:     my ($name,$id,$debug) = @_;
1.1319    damieng  2967:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2968:     if (exists($remembered{$remembered_id})) {
                   2969: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2970: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2971: 	$hits++;
1.1319    damieng  2972: 	return ($remembered{$remembered_id},1);
1.599     albertel 2973:     }
1.1319    damieng  2974:     $id=&make_key($name,$id);
1.599     albertel 2975:     my $value = $memcache->get($id);
                   2976:     if (!(defined($value))) {
                   2977: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2978: 	return (undef,undef);
1.416     albertel 2979:     }
1.599     albertel 2980:     if ($value eq '__undef__') {
                   2981: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2982: 	$value=undef;
                   2983:     }
1.1319    damieng  2984:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2985:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2986:     return ($value,1);
                   2987: }
                   2988: 
                   2989: sub do_cache_new {
                   2990:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2991:     my $remembered_id=$name.':'.$id;
1.849     albertel 2992:     $id=&make_key($name,$id);
1.599     albertel 2993:     my $setvalue=$value;
                   2994:     if (!defined($setvalue)) {
                   2995: 	$setvalue='__undef__';
                   2996:     }
1.623     albertel 2997:     if (!defined($time) ) {
                   2998: 	$time=600;
                   2999:     }
1.599     albertel 3000:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3001:     my $result = $memcache->set($id,$setvalue,$time);
                   3002:     if (! $result) {
1.872     albertel 3003: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3004: 	$memcache->disconnect_all();
1.872     albertel 3005:     }
1.600     albertel 3006:     # need to make a copy of $value
1.1319    damieng  3007:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3008:     return $value;
                   3009: }
                   3010: 
                   3011: sub make_room {
1.1319    damieng  3012:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3013: 
1.1319    damieng  3014:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3015:                                     : $value;
1.599     albertel 3016:     if ($to_remember<0) { return; }
1.1319    damieng  3017:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3018:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3019:     my $to_kick;
                   3020:     my $max_time=0;
                   3021:     foreach my $other (keys(%accessed)) {
                   3022: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3023: 	    $to_kick=$other;
                   3024: 	    $max_time=&tv_interval($accessed{$other});
                   3025: 	}
                   3026:     }
                   3027:     delete($remembered{$to_kick});
                   3028:     delete($accessed{$to_kick});
                   3029:     $kicks++;
                   3030:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3031:     return;
                   3032: }
                   3033: 
1.599     albertel 3034: sub purge_remembered {
1.604     albertel 3035:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3036:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3037:     undef(%remembered);
                   3038:     undef(%accessed);
1.428     albertel 3039: }
1.70      www      3040: # ------------------------------------- Read an entry from a user's environment
                   3041: 
                   3042: sub userenvironment {
                   3043:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3044:     my $items;
                   3045:     foreach my $item (@what) {
                   3046:         $items.=&escape($item).'&';
                   3047:     }
                   3048:     $items=~s/\&$//;
1.70      www      3049:     my %returnhash=();
1.1009    raeburn  3050:     my $uhome = &homeserver($unam,$udom);
                   3051:     unless ($uhome eq 'no_host') {
                   3052:         my @answer=split(/\&/, 
                   3053:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3054:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3055:             return %returnhash;
                   3056:         }
1.1009    raeburn  3057:         my $i;
                   3058:         for ($i=0;$i<=$#what;$i++) {
                   3059: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3060:         }
1.70      www      3061:     }
                   3062:     return %returnhash;
1.1       albertel 3063: }
                   3064: 
1.617     albertel 3065: # ---------------------------------------------------------- Get a studentphoto
                   3066: sub studentphoto {
                   3067:     my ($udom,$unam,$ext) = @_;
                   3068:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3069:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3070:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3071:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3072:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3073:             } else {
                   3074:                 my ($result,$perm_reqd)=
1.707     albertel 3075: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3076:                 if ($result eq 'ok') {
                   3077:                     if (!($perm_reqd eq 'yes')) {
                   3078:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3079:                     }
                   3080:                 }
                   3081:             }
                   3082:         }
                   3083:     } else {
                   3084:         my ($result,$perm_reqd) = 
1.707     albertel 3085: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3086:         if ($result eq 'ok') {
                   3087:             if (!($perm_reqd eq 'yes')) {
                   3088:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3089:             }
                   3090:         }
                   3091:     }
                   3092:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3093: }
                   3094: 
                   3095: sub retrievestudentphoto {
                   3096:     my ($udom,$unam,$ext,$type) = @_;
                   3097:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3098:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3099:     if ($ret eq 'ok') {
                   3100:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3101:         if ($type eq 'thumbnail') {
                   3102:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3103:         }
                   3104:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3105:         return $tokenurl;
                   3106:     } else {
                   3107:         if ($type eq 'thumbnail') {
                   3108:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3109:         } else { 
                   3110:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3111:         }
1.617     albertel 3112:     }
                   3113: }
                   3114: 
1.263     www      3115: # -------------------------------------------------------------------- New chat
                   3116: 
                   3117: sub chatsend {
1.724     raeburn  3118:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3119:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3120:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3121:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3122:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3123: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3124: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3125: }
                   3126: 
                   3127: # ------------------------------------------ Find current version of a resource
                   3128: 
                   3129: sub getversion {
                   3130:     my $fname=&clutter(shift);
1.1189    raeburn  3131:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3132:     return &currentversion(&filelocation('',$fname));
                   3133: }
                   3134: 
                   3135: sub currentversion {
                   3136:     my $fname=shift;
                   3137:     my $author=$fname;
                   3138:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3139:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3140:     my $home=&homeserver($uname,$udom);
1.292     www      3141:     if ($home eq 'no_host') { 
                   3142:         return -1; 
                   3143:     }
1.1112    www      3144:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3145:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3146: 	return -1;
                   3147:     }
1.1112    www      3148:     return $answer;
1.263     www      3149: }
                   3150: 
1.1111    www      3151: #
                   3152: # Return special version number of resource if set by override, empty otherwise
                   3153: #
                   3154: sub usedversion {
                   3155:     my $fname=shift;
                   3156:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3157:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3158:     if ($urlversion) { return $urlversion; }
                   3159:     return '';
                   3160: }
                   3161: 
1.1       albertel 3162: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3163: 
1.1       albertel 3164: sub subscribe {
                   3165:     my $fname=shift;
1.761     raeburn  3166:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3167:     $fname=~s/[\n\r]//g;
1.1       albertel 3168:     my $author=$fname;
                   3169:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3170:     my ($udom,$uname)=split(/\//,$author);
                   3171:     my $home=homeserver($uname,$udom);
1.335     albertel 3172:     if ($home eq 'no_host') {
                   3173:         return 'not_found';
1.1       albertel 3174:     }
                   3175:     my $answer=reply("sub:$fname",$home);
1.64      www      3176:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3177: 	$answer.=' by '.$home;
                   3178:     }
1.1       albertel 3179:     return $answer;
                   3180: }
                   3181:     
1.8       www      3182: # -------------------------------------------------------------- Replicate file
                   3183: 
                   3184: sub repcopy {
                   3185:     my $filename=shift;
1.23      www      3186:     $filename=~s/\/+/\//g;
1.1142    raeburn  3187:     my $londocroot = $perlvar{'lonDocRoot'};
                   3188:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3189:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3190:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3191: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3192: 	return &repcopy_userfile($filename);
                   3193:     }
1.532     albertel 3194:     $filename=~s/[\n\r]//g;
1.8       www      3195:     my $transname="$filename.in.transfer";
1.828     www      3196: # FIXME: this should flock
1.607     raeburn  3197:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3198:     my $remoteurl=subscribe($filename);
1.64      www      3199:     if ($remoteurl =~ /^con_lost by/) {
                   3200: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3201:            return 'unavailable';
1.8       www      3202:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3203: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3204: 	   return 'not_found';
1.64      www      3205:     } elsif ($remoteurl =~ /^rejected by/) {
                   3206: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3207:            return 'forbidden';
1.20      www      3208:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3209:            return 'ok';
1.8       www      3210:     } else {
1.290     www      3211:         my $author=$filename;
                   3212:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3213:         my ($udom,$uname)=split(/\//,$author);
                   3214:         my $home=homeserver($uname,$udom);
                   3215:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3216:            my @parts=split(/\//,$filename);
                   3217:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3218:            if ($path ne "$londocroot/res") {
1.8       www      3219:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3220: 	       return 'bad_request';
1.8       www      3221:            }
                   3222:            my $count;
                   3223:            for ($count=5;$count<$#parts;$count++) {
                   3224:                $path.="/$parts[$count]";
                   3225:                if ((-e $path)!=1) {
                   3226: 		   mkdir($path,0777);
                   3227:                }
                   3228:            }
                   3229:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3230:            my $response;
                   3231:            if ($remoteurl =~ m{/raw/}) {
                   3232:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3233:            } else {
                   3234:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3235:            }
1.8       www      3236:            if ($response->is_error()) {
                   3237: 	       unlink($transname);
                   3238:                my $message=$response->status_line;
1.672     albertel 3239:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3240:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3241:                return 'unavailable';
1.8       www      3242:            } else {
1.16      www      3243: 	       if ($remoteurl!~/\.meta$/) {
                   3244:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3245:                   my $mresponse;
                   3246:                   if ($remoteurl =~ m{/raw/}) {
                   3247:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3248:                   } else {
                   3249:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3250:                   }
1.16      www      3251:                   if ($mresponse->is_error()) {
                   3252: 		      unlink($filename.'.meta');
                   3253:                       &logthis(
1.672     albertel 3254:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3255:                   }
                   3256: 	       }
1.8       www      3257:                rename($transname,$filename);
1.607     raeburn  3258:                return 'ok';
1.8       www      3259:            }
1.290     www      3260:        }
1.8       www      3261:     }
1.330     www      3262: }
                   3263: 
                   3264: # ------------------------------------------------ Get server side include body
                   3265: sub ssi_body {
1.381     albertel 3266:     my ($filelink,%form)=@_;
1.606     matthew  3267:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3268:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3269:     }
1.953     www      3270:     my $output='';
                   3271:     my $response;
1.980     raeburn  3272:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3273:        ($output,$response)=&externalssi($filelink);
1.953     www      3274:     } else {
1.1004    droeschl 3275:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3276:        $filelink .= 'inhibitmenu=yes';
1.953     www      3277:        ($output,$response)=&ssi($filelink,%form);
                   3278:     }
1.778     albertel 3279:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3280:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3281:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3282:     if (wantarray) {
                   3283:         return ($output, $response);
                   3284:     } else {
                   3285:         return $output;
                   3286:     }
1.8       www      3287: }
                   3288: 
1.15      www      3289: # --------------------------------------------------------- Server Side Include
                   3290: 
1.782     albertel 3291: sub absolute_url {
                   3292:     my ($host_name) = @_;
                   3293:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3294:     if ($host_name eq '') {
                   3295: 	$host_name = $ENV{'SERVER_NAME'};
                   3296:     }
                   3297:     return $protocol.$host_name;
                   3298: }
                   3299: 
1.942     foxr     3300: #
                   3301: #   Server side include.
                   3302: # Parameters:
                   3303: #  fn     Possibly encrypted resource name/id.
                   3304: #  form   Hash that describes how the rendering should be done
                   3305: #         and other things.
1.944     foxr     3306: # Returns:
1.950     raeburn  3307: #   Scalar context: The content of the response.
                   3308: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3309: #     
1.15      www      3310: sub ssi {
                   3311: 
1.944     foxr     3312:     my ($fn,%form)=@_;
1.23      www      3313:     my $request;
1.711     albertel 3314: 
                   3315:     $form{'no_update_last_known'}=1;
1.895     albertel 3316:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3317:     if (%form) {
1.782     albertel 3318:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3319:       $request->content(join('&',map { 
                   3320:             my $name = escape($_);
                   3321:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3322:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3323:             : &escape($form{$_}) );    
                   3324:         } keys(%form)));
1.23      www      3325:     } else {
1.782     albertel 3326:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3327:     }
                   3328: 
1.15      www      3329:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3330:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3331:     my $islocal;
                   3332:     if (($env{'request.course.id'}) &&
                   3333:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3334:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3335:         ($form{'grade_symb'} ne '') &&
                   3336:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3337:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3338:         $islocal = 1;
                   3339:     }
1.1384    raeburn  3340:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3341:                                                 '','','',$islocal);
1.1182    foxr     3342: 
1.944     foxr     3343:     if (wantarray) {
1.1345    raeburn  3344: 	return ($response->content, $response);
1.944     foxr     3345:     } else {
1.1345    raeburn  3346: 	return $response->content;
1.942     foxr     3347:     }
1.324     www      3348: }
                   3349: 
                   3350: sub externalssi {
                   3351:     my ($url)=@_;
                   3352:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3353:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3354:     if (wantarray) {
                   3355:         return ($response->content, $response);
                   3356:     } else {
                   3357:         return $response->content;
                   3358:     }
1.15      www      3359: }
1.254     www      3360: 
1.1354    raeburn  3361: 
                   3362: # If the local copy of a replicated resource is outdated, trigger a  
                   3363: # connection from the homeserver to flush the delayed queue. If no update 
                   3364: # happens, remove local copies of outdated resource (and corresponding
                   3365: # metadata file).
                   3366: 
1.1352    raeburn  3367: sub remove_stale_resfile {
                   3368:     my ($url) = @_;
1.1354    raeburn  3369:     my $removed;
1.1352    raeburn  3370:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3371:         my $audom = $1;
                   3372:         my $auname = $2;
1.1353    raeburn  3373:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3374:             my $homeserver = &homeserver($auname,$audom);
                   3375:             unless (($homeserver eq 'no_host') ||
                   3376:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3377:                 my $fname = &filelocation('',$url);
                   3378:                 if (-e $fname) {
                   3379:                     my $protocol = $protocol{$homeserver};
                   3380:                     $protocol = 'http' if ($protocol ne 'https');
                   3381:                     my $hostname = &hostname($homeserver);
                   3382:                     if ($hostname) {
                   3383:                         my $uri = &declutter($url);
                   3384:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3385:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3386:                         if ($response->is_success()) {
                   3387:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3388:                             my $locmodtime = (stat($fname))[9];
                   3389:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3390:                                 my $stale;
                   3391:                                 my $answer = &reply('pong',$homeserver);
                   3392:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3393:                                     sleep(0.2);
                   3394:                                     $locmodtime = (stat($fname))[9];
                   3395:                                     if ($locmodtime < $remmodtime) {
                   3396:                                         my $posstransfer = $fname.'.in.transfer';
                   3397:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3398:                                             $removed = 1;
                   3399:                                         } else {
                   3400:                                             $stale = 1;
                   3401:                                         }
                   3402:                                     } else {
                   3403:                                         $removed = 1;
                   3404:                                     }
                   3405:                                 } else {
                   3406:                                     $stale = 1;
                   3407:                                 }
                   3408:                                 if ($stale) {
                   3409:                                     unlink($fname);
                   3410:                                     if ($uri!~/\.meta$/) {
                   3411:                                         unlink($fname.'.meta');
                   3412:                                     }
                   3413:                                     &reply("unsub:$fname",$homeserver);
                   3414:                                     $removed = 1;
1.1352    raeburn  3415:                                 }
                   3416:                             }
                   3417:                         }
                   3418:                     }
                   3419:                 }
                   3420:             }
                   3421:         }
                   3422:     }
1.1354    raeburn  3423:     return $removed;
1.1352    raeburn  3424: }
                   3425: 
1.492     albertel 3426: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3427: 
                   3428: sub allowuploaded {
                   3429:     my ($srcurl,$url)=@_;
                   3430:     $url=&clutter(&declutter($url));
                   3431:     my $dir=$url;
                   3432:     $dir=~s/\/[^\/]+$//;
                   3433:     my %httpref=();
                   3434:     my $httpurl=&hreflocation('',$url);
                   3435:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3436:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3437: }
1.477     raeburn  3438: 
1.1193    raeburn  3439: #
                   3440: # Determine if the current user should be able to edit a particular resource,
                   3441: # when viewing in course context.
                   3442: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3443: #     Functions.
                   3444: # (b) When displaying folder contents in course editor, used to determine if
                   3445: #     "Edit" link will be displayed alongside resource.
                   3446: #
1.1196    raeburn  3447: #  input: six args -- filename (decluttered), course number, course domain,
                   3448: #                   url, symb (if registered) and group (if this is a group
                   3449: #                   item -- e.g., bulletin board, group page etc.).
                   3450: #  output: array of five scalars -- 
1.1193    raeburn  3451: #          $cfile -- url for file editing if editable on current server
                   3452: #          $home -- homeserver of resource (i.e., for author if published,
                   3453: #                                           or course if uploaded.).
                   3454: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3455: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3456: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3457: #
                   3458: 
                   3459: sub can_edit_resource {
1.1194    raeburn  3460:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3461:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3462: #
                   3463: # For aboutme pages user can only edit his/her own.
                   3464: #
1.1199    raeburn  3465:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3466:         my ($sdom,$sname) = ($1,$2);
                   3467:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3468:             $home = $env{'user.home'};
                   3469:             $cfile = $resurl;
                   3470:             if ($env{'form.forceedit'}) {
                   3471:                 $forceview = 1;
                   3472:             } else {
                   3473:                 $forceedit = 1;
                   3474:             }
                   3475:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3476:         } else {
                   3477:             return;
                   3478:         }
                   3479:     }
                   3480: 
                   3481:     if ($env{'request.course.id'}) {
                   3482:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3483:         if ($group ne '') {
                   3484: # if this is a group homepage or group bulletin board, check group privs
                   3485:             my $allowed = 0;
1.1197    raeburn  3486:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3487:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3488:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3489:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3490:                     $allowed = 1;
                   3491:                 }
1.1197    raeburn  3492:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3493:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3494:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3495:                     $allowed = 1;
                   3496:                 }
                   3497:             }
                   3498:             if ($allowed) {
                   3499:                 $home=&homeserver($cnum,$cdom);
                   3500:                 if ($env{'form.forceedit'}) {
                   3501:                     $forceview = 1;
                   3502:                 } else {
                   3503:                     $forceedit = 1;
                   3504:                 }
                   3505:                 $cfile = $resurl;
                   3506:             } else {
                   3507:                 return;
                   3508:             }
                   3509:         } else {
1.1208    raeburn  3510:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3511:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3512:                     return;
                   3513:                 }
                   3514:             } elsif (!$crsedit) {
1.1194    raeburn  3515: #
                   3516: # No edit allowed where CC has switched to student role.
                   3517: #
                   3518:                 return;
                   3519:             }
                   3520:         }
                   3521:     }
                   3522: 
1.1193    raeburn  3523:     if ($file ne '') {
                   3524:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3525:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3526:                 $uploaded = 1;
                   3527:                 $incourse = 1;
1.1193    raeburn  3528:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3529:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3530:                     if ($env{'form.forceedit'}) {
                   3531:                         $forceview = 1;
                   3532:                     } else {
                   3533:                         $forceedit = 1;
                   3534:                     }
1.1194    raeburn  3535:                 }
                   3536:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3537:                 $incourse = 1;
                   3538:                 if ($env{'form.forceedit'}) {
                   3539:                     $forceview = 1;
                   3540:                 } else {
                   3541:                     $forceedit = 1;
                   3542:                 }
                   3543:                 $cfile = $resurl;
                   3544:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3545:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3546:                     $incourse = 1;
                   3547:                     if ($env{'form.forceedit'}) {
                   3548:                         $forceview = 1;
                   3549:                     } else {
                   3550:                         $forceedit = 1;
                   3551:                     }
                   3552:                     $cfile = $resurl;
1.1199    raeburn  3553:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3554:                     $incourse = 1;
                   3555:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3556:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3557:                     $incourse = 1;
1.1199    raeburn  3558:                     if ($env{'form.forceedit'}) {
                   3559:                         $forceview = 1;
                   3560:                     } else {
                   3561:                         $forceedit = 1;
                   3562:                     }
                   3563:                     $cfile = $resurl;
1.1343    raeburn  3564:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3565:                     $incourse = 1;
                   3566:                     if ($env{'form.forceedit'}) {
                   3567:                         $forceview = 1;
                   3568:                     } else {
                   3569:                         $forceedit = 1;
                   3570:                     }
                   3571:                     $cfile = $resurl;
1.1208    raeburn  3572:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3573:                     $incourse = 1;
                   3574:                     if ($env{'form.forceedit'}) {
                   3575:                         $forceview = 1;
                   3576:                     } else {
                   3577:                         $forceedit = 1;
                   3578:                     }
                   3579:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3580:                 }
                   3581:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3582:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3583:                 if (&is_on_map($template)) { 
                   3584:                     $incourse = 1;
                   3585:                     $forceview = 1;
                   3586:                     $cfile = $template;
1.1193    raeburn  3587:                 }
1.1199    raeburn  3588:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3589:                     $incourse = 1;
                   3590:                     if ($env{'form.forceedit'}) {
                   3591:                         $forceview = 1;
                   3592:                     } else {
                   3593:                         $forceedit = 1;
                   3594:                     }
                   3595:                     $cfile = $resurl;
1.1343    raeburn  3596:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3597:                 $incourse = 1;
                   3598:                 if ($env{'form.forceedit'}) {
                   3599:                     $forceview = 1;
                   3600:                 } else {
                   3601:                     $forceedit = 1;
                   3602:                 }
                   3603:                 $cfile = $resurl;
1.1199    raeburn  3604:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3605:                 $incourse = 1;
                   3606:                 $forceview = 1;
                   3607:                 if ($symb) {
                   3608:                     my ($map,$id,$res)=&decode_symb($symb);
                   3609:                     $env{'request.symb'} = $symb;
                   3610:                     $cfile = &clutter($res);
                   3611:                 } else {
                   3612:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3613:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3614:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3615:                         $cfile = '/adm/wrapper'.$escfile;
                   3616:                     } else {
                   3617:                         $escfile =~ s{^http://}{};
                   3618:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3619:                     }
1.1199    raeburn  3620:                 }
1.1234    raeburn  3621:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3622:                 if ($env{'form.forceedit'}) {
                   3623:                     $forceview = 1;
                   3624:                 } else {
                   3625:                     $forceedit = 1;
                   3626:                 }
                   3627:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3628:             }
                   3629:         }
1.1194    raeburn  3630:         if ($uploaded || $incourse) {
                   3631:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3632:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3633:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3634:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3635:             # Check that the user has permission to edit this resource
                   3636:             my $setpriv = 1;
                   3637:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3638:             if (defined($cfudom)) {
                   3639:                 $home=&homeserver($cfuname,$cfudom);
                   3640:                 $cfile=$file;
                   3641:             }
                   3642:         }
1.1194    raeburn  3643:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3644:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3645:             my @ids=&current_machine_ids();
                   3646:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3647:                 $switchserver=1;
                   3648:             }
                   3649:         }
                   3650:     }
1.1194    raeburn  3651:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3652: }
                   3653: 
                   3654: sub is_course_upload {
                   3655:     my ($file,$cnum,$cdom) = @_;
                   3656:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3657:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3658:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3659:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3660:         return 1;
                   3661:     }
                   3662:     return;
                   3663: }
                   3664: 
1.1194    raeburn  3665: sub in_course {
1.1195    raeburn  3666:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3667:     if ($hideprivileged) {
                   3668:         my $skipuser;
1.1219    raeburn  3669:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3670:         my @possdoms = ($cdom);  
                   3671:         if ($coursehash{'checkforpriv'}) { 
                   3672:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3673:         }
                   3674:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3675:             $skipuser = 1;
                   3676:             if ($coursehash{'nothideprivileged'}) {
                   3677:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3678:                     my $user;
                   3679:                     if ($item =~ /:/) {
                   3680:                         $user = $item;
                   3681:                     } else {
                   3682:                         $user = join(':',split(/[\@]/,$item));
                   3683:                     }
                   3684:                     if ($user eq $uname.':'.$udom) {
                   3685:                         undef($skipuser);
                   3686:                         last;
                   3687:                     }
                   3688:                 }
                   3689:             }
                   3690:             if ($skipuser) {
                   3691:                 return 0;
                   3692:             }
                   3693:         }
                   3694:     }
1.1194    raeburn  3695:     $type ||= 'any';
                   3696:     if (!defined($cdom) || !defined($cnum)) {
                   3697:         my $cid  = $env{'request.course.id'};
                   3698:         $cdom = $env{'course.'.$cid.'.domain'};
                   3699:         $cnum = $env{'course.'.$cid.'.num'};
                   3700:     }
                   3701:     my $typesref;
1.1195    raeburn  3702:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3703:         $typesref = ['active','previous','future'];
                   3704:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3705:         $typesref = [$type];
                   3706:     }
                   3707:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3708:                               $typesref,undef,[$cdom]);
                   3709:     my ($tmp) = keys(%roles);
                   3710:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3711:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3712:     if (@course_roles > 0) {
                   3713:         return 1;
                   3714:     }
                   3715:     return 0;
                   3716: }
                   3717: 
1.478     albertel 3718: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3719: # input: action, courseID, current domain, intended
1.637     raeburn  3720: #        path to file, source of file, instruction to parse file for objects,
                   3721: #        ref to hash for embedded objects,
                   3722: #        ref to hash for codebase of java objects.
1.1095    raeburn  3723: #        reference to scalar to accommodate mime type determined
                   3724: #          from File::MMagic if $parser = parse.
1.637     raeburn  3725: #
1.485     raeburn  3726: # output: url to file (if action was uploaddoc), 
                   3727: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3728: #
1.478     albertel 3729: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3730: # course.
1.477     raeburn  3731: #
1.478     albertel 3732: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3733: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3734: #          course's home server.
1.477     raeburn  3735: #
1.478     albertel 3736: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3737: #          be copied from $source (current location) to 
                   3738: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3739: #         and will then be copied to
                   3740: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3741: #         course's home server.
1.485     raeburn  3742: #
1.481     raeburn  3743: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3744: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3745: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3746: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3747: #         in course's home server.
1.637     raeburn  3748: #
1.477     raeburn  3749: 
                   3750: sub process_coursefile {
1.1095    raeburn  3751:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3752:         $mimetype)=@_;
1.477     raeburn  3753:     my $fetchresult;
1.638     albertel 3754:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3755:     if ($action eq 'propagate') {
1.638     albertel 3756:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3757: 			     $home);
1.481     raeburn  3758:     } else {
1.477     raeburn  3759:         my $fpath = '';
                   3760:         my $fname = $file;
1.478     albertel 3761:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3762:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3763:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3764:         if ($action eq 'copy') {
                   3765:             if ($source eq '') {
                   3766:                 $fetchresult = 'no source file';
                   3767:                 return $fetchresult;
                   3768:             } else {
                   3769:                 my $destination = $filepath.'/'.$fname;
                   3770:                 rename($source,$destination);
                   3771:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3772:                                  $home);
1.481     raeburn  3773:             }
                   3774:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3775:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3776:             print $fh $env{'form.'.$source};
1.481     raeburn  3777:             close($fh);
1.637     raeburn  3778:             if ($parser eq 'parse') {
1.1024    raeburn  3779:                 my $mm = new File::MMagic;
1.1095    raeburn  3780:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3781:                 if ($type eq 'text/html') {
1.1024    raeburn  3782:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3783:                     unless ($parse_result eq 'ok') {
                   3784:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3785:                     }
1.637     raeburn  3786:                 }
1.1095    raeburn  3787:                 if (ref($mimetype)) {
                   3788:                     $$mimetype = $type;
                   3789:                 } 
1.637     raeburn  3790:             }
1.477     raeburn  3791:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3792:                                  $home);
1.481     raeburn  3793:             if ($fetchresult eq 'ok') {
                   3794:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3795:             } else {
                   3796:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3797:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3798:                 return '/adm/notfound.html';
                   3799:             }
1.477     raeburn  3800:         }
                   3801:     }
1.485     raeburn  3802:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3803:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3804:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3805:     }
                   3806:     return $fetchresult;
                   3807: }
                   3808: 
1.637     raeburn  3809: sub build_filepath {
                   3810:     my ($fpath) = @_;
                   3811:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3812:     unless ($fpath eq '') {
                   3813:         my @parts=split('/',$fpath);
                   3814:         foreach my $part (@parts) {
                   3815:             $filepath.= '/'.$part;
                   3816:             if ((-e $filepath)!=1) {
                   3817:                 mkdir($filepath,0777);
                   3818:             }
                   3819:         }
                   3820:     }
                   3821:     return $filepath;
                   3822: }
                   3823: 
                   3824: sub store_edited_file {
1.638     albertel 3825:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3826:     my $file = $primary_url;
                   3827:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3828:     my $fpath = '';
                   3829:     my $fname = $file;
                   3830:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3831:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3832:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3833:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3834:     print $fh $content;
                   3835:     close($fh);
1.638     albertel 3836:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3837:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3838: 			  $home);
1.637     raeburn  3839:     if ($$fetchresult eq 'ok') {
                   3840:         return '/uploaded/'.$fpath.'/'.$fname;
                   3841:     } else {
1.638     albertel 3842:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3843: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3844:         return '/adm/notfound.html';
                   3845:     }
                   3846: }
                   3847: 
1.531     albertel 3848: sub clean_filename {
1.831     albertel 3849:     my ($fname,$args)=@_;
1.315     www      3850: # Replace Windows backslashes by forward slashes
1.257     www      3851:     $fname=~s/\\/\//g;
1.831     albertel 3852:     if (!$args->{'keep_path'}) {
                   3853:         # Get rid of everything but the actual filename
                   3854: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3855:     }
1.315     www      3856: # Replace spaces by underscores
                   3857:     $fname=~s/\s+/\_/g;
                   3858: # Replace all other weird characters by nothing
1.831     albertel 3859:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3860: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3861: # numbers
                   3862:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3863:     return $fname;
                   3864: }
1.1051    raeburn  3865: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3866: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3867: # image with the same aspect ratio as the original, but with dimensions which do 
                   3868: # not exceed $resizewidth and $resizeheight.
                   3869:  
1.984     neumanie 3870: sub resizeImage {
1.1051    raeburn  3871:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3872:     my $ima = Image::Magick->new;
                   3873:     my $resized;
                   3874:     if (-e $img_path) {
                   3875:         $ima->Read($img_path);
                   3876:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3877:             my $width = $ima->Get('width');
                   3878:             my $height = $ima->Get('height');
                   3879:             if ($width > $resizewidth) {
                   3880: 	        my $factor = $width/$resizewidth;
                   3881:                 my $newheight = $height/$factor;
                   3882:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3883:                 $resized = 1;
                   3884:             }
                   3885:         }
                   3886:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3887:             my $width = $ima->Get('width');
                   3888:             my $height = $ima->Get('height');
                   3889:             if ($height > $resizeheight) {
                   3890:                 my $factor = $height/$resizeheight;
                   3891:                 my $newwidth = $width/$factor;
                   3892:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3893:                 $resized = 1;
                   3894:             }
                   3895:         }
                   3896:         if ($resized) {
                   3897:             $ima->Write($img_path);
                   3898:         }
                   3899:     }
                   3900:     return;
1.977     amueller 3901: }
                   3902: 
1.608     albertel 3903: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3904: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3905: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3906: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3907: #                                    canceloverwrite, or ''. 
                   3908: #                   if 'coursedoc': upload to the current course
                   3909: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3910: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3911: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3912: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3913: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3914: #        $allfiles - reference to hash for embedded objects
                   3915: #        $codebase - reference to hash for codebase of java objects
                   3916: #        $desuname - username for permanent storage of uploaded file
                   3917: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3918: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3919: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3920: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3921: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3922: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3923: #                    from File::MMagic.
1.858     raeburn  3924: # 
1.686     albertel 3925: # output: url of file in userspace, or error: <message> 
                   3926: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3927: 
1.531     albertel 3928: sub userfileupload {
1.1090    raeburn  3929:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3930:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3931:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3932:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3933:     $fname=&clean_filename($fname);
1.1090    raeburn  3934:     # See if there is anything left
1.257     www      3935:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3936:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3937:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3938:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3939:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3940:         my $now = time;
1.1090    raeburn  3941:         my $filepath;
1.1095    raeburn  3942:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3943:              $filepath = 'tmp/helprequests/'.$now;
                   3944:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3945:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3946:                          '_'.$env{'user.domain'}.'/pending';
                   3947:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3948:             my ($docuname,$docudom);
1.1350    raeburn  3949:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3950:                 $docudom = $destudom;
                   3951:             } else {
                   3952:                 $docudom = $env{'user.domain'};
                   3953:             }
1.1350    raeburn  3954:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3955:                 $docuname = $destuname;
                   3956:             } else {
                   3957:                 $docuname = $env{'user.name'};
                   3958:             }
                   3959:             if (exists($env{'form.group'})) {
                   3960:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3961:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3962:             }
                   3963:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3964:             if ($context eq 'canceloverwrite') {
                   3965:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3966:                 if (-e  $tempfile) {
                   3967:                     my @info = stat($tempfile);
                   3968:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3969:                         unlink($tempfile);
                   3970:                     }
                   3971:                 }
                   3972:                 return;
1.523     raeburn  3973:             }
                   3974:         }
1.1090    raeburn  3975:         # Create the directory if not present
1.741     raeburn  3976:         my @parts=split(/\//,$filepath);
                   3977:         my $fullpath = $perlvar{'lonDaemons'};
                   3978:         for (my $i=0;$i<@parts;$i++) {
                   3979:             $fullpath .= '/'.$parts[$i];
                   3980:             if ((-e $fullpath)!=1) {
                   3981:                 mkdir($fullpath,0777);
                   3982:             }
                   3983:         }
1.1359    raeburn  3984:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3985:         print $fh $env{'form.'.$formname};
                   3986:         close($fh);
1.1090    raeburn  3987:         if ($context eq 'existingfile') {
                   3988:             my @info = stat($fullpath.'/'.$fname);
                   3989:             return ($fullpath.'/'.$fname,$info[9]);
                   3990:         } else {
                   3991:             return $fullpath.'/'.$fname;
                   3992:         }
1.523     raeburn  3993:     }
1.995     raeburn  3994:     if ($subdir eq 'scantron') {
                   3995:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3996:     } else {
1.995     raeburn  3997:         $fname="$subdir/$fname";
                   3998:     }
1.1090    raeburn  3999:     if ($context eq 'coursedoc') {
1.638     albertel 4000: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4001: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4002:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4003:             return &finishuserfileupload($docuname,$docudom,
                   4004: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4005: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4006:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4007:         } else {
1.1218    raeburn  4008:             if ($env{'form.folder'}) {
                   4009:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4010:             }
1.638     albertel 4011:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4012: 				       $fname,$formname,$parser,
1.1095    raeburn  4013: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4014:         }
1.719     banghart 4015:     } elsif (defined($destuname)) {
                   4016:         my $docuname=$destuname;
                   4017:         my $docudom=$destudom;
1.860     raeburn  4018: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4019: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4020:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4021:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4022:     } else {
1.638     albertel 4023:         my $docuname=$env{'user.name'};
                   4024:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4025:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4026:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4027:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4028:         }
1.860     raeburn  4029: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4030: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4031:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4032:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4033:     }
1.271     www      4034: }
                   4035: 
                   4036: sub finishuserfileupload {
1.860     raeburn  4037:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4038:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4039:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4040:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4041:   
1.860     raeburn  4042:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4043:     $file=$fname;
                   4044:     if ($fname=~m|/|) {
                   4045:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4046: 	$path.=$fnamepath.'/';
                   4047:     }
1.259     www      4048:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4049:     my $count;
                   4050:     for ($count=4;$count<=$#parts;$count++) {
                   4051:         $filepath.="/$parts[$count]";
                   4052:         if ((-e $filepath)!=1) {
                   4053: 	    mkdir($filepath,0777);
                   4054:         }
                   4055:     }
1.984     neumanie 4056: 
1.258     www      4057: # Save the file
                   4058:     {
1.1359    raeburn  4059: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4060: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4061: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4062: 	    return '/adm/notfound.html';
                   4063: 	}
1.1090    raeburn  4064:         if ($context eq 'overwrite') {
1.1117    foxr     4065:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4066:             my $target = $filepath.'/'.$file;
                   4067:             if (-e $source) {
                   4068:                 my @info = stat($source);
                   4069:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4070:                     unless (&File::Copy::move($source,$target)) {
                   4071:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4072:                         return "Moving from $source failed";
                   4073:                     }
                   4074:                 } else {
                   4075:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4076:                 }
                   4077:             } else {
                   4078:                 return "Temporary file: $source missing";
                   4079:             }
                   4080:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4081: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4082: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4083: 	    return '/adm/notfound.html';
                   4084: 	}
1.570     albertel 4085: 	close(FH);
1.1051    raeburn  4086:         if ($resizewidth && $resizeheight) {
                   4087:             my $mm = new File::MMagic;
                   4088:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4089:             if ($mime_type =~ m{^image/}) {
                   4090: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4091:             }  
1.977     amueller 4092: 	}
1.258     www      4093:     }
1.1152    raeburn  4094:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4095:         if (ref($mimetype)) {
                   4096:             if ($$mimetype eq '') {
                   4097:                 my $mm = new File::MMagic;
                   4098:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4099:                 $$mimetype = $type;
                   4100:             }
                   4101:         }
                   4102:     }
1.637     raeburn  4103:     if ($parser eq 'parse') {
1.1152    raeburn  4104:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4105:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4106:                                                        $allfiles,$codebase);
                   4107:             unless ($parse_result eq 'ok') {
                   4108:                 &logthis('Failed to parse '.$filepath.$file.
                   4109: 	   	         ' for embedded media: '.$parse_result); 
                   4110:             }
1.637     raeburn  4111:         }
                   4112:     }
1.860     raeburn  4113:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4114:         my $input = $filepath.'/'.$file;
                   4115:         my $output = $filepath.'/'.'tn-'.$file;
                   4116:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4117:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4118:         system({$args[0]} @args);
1.860     raeburn  4119:         if (-e $filepath.'/'.'tn-'.$file) {
                   4120:             $fetchthumb  = 1; 
                   4121:         }
                   4122:     }
1.858     raeburn  4123:  
1.259     www      4124: # Notify homeserver to grep it
                   4125: #
1.984     neumanie 4126:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4127:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4128:     if ($fetchresult eq 'ok') {
1.860     raeburn  4129:         if ($fetchthumb) {
                   4130:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4131:             if ($thumbresult ne 'ok') {
                   4132:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4133:                          $docuhome.': '.$thumbresult);
                   4134:             }
                   4135:         }
1.259     www      4136: #
1.258     www      4137: # Return the URL to it
1.494     albertel 4138:         return '/uploaded/'.$path.$file;
1.263     www      4139:     } else {
1.494     albertel 4140:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4141: 		 ': '.$fetchresult);
1.263     www      4142:         return '/adm/notfound.html';
1.858     raeburn  4143:     }
1.493     albertel 4144: }
                   4145: 
1.637     raeburn  4146: sub extract_embedded_items {
1.961     raeburn  4147:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4148:     my @state = ();
1.1164    raeburn  4149:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4150:     my %javafiles = (
                   4151:                       codebase => '',
                   4152:                       code => '',
                   4153:                       archive => ''
                   4154:                     );
                   4155:     my %mediafiles = (
                   4156:                       src => '',
                   4157:                       movie => '',
                   4158:                      );
1.648     raeburn  4159:     my $p;
                   4160:     if ($content) {
                   4161:         $p = HTML::LCParser->new($content);
                   4162:     } else {
1.961     raeburn  4163:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4164:     }
1.641     albertel 4165:     while (my $t=$p->get_token()) {
1.640     albertel 4166: 	if ($t->[0] eq 'S') {
                   4167: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4168: 	    push(@state, $tagname);
1.648     raeburn  4169:             if (lc($tagname) eq 'allow') {
                   4170:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4171:             }
1.640     albertel 4172: 	    if (lc($tagname) eq 'img') {
                   4173: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4174: 	    }
1.886     albertel 4175: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4176:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4177:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4178:                 }
1.886     albertel 4179: 	    }
1.645     raeburn  4180:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4181:                 my $src;
1.645     raeburn  4182:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4183:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4184:                 } else {
1.1164    raeburn  4185:                     if ($attr->{'src'} ne '') {
                   4186:                         $src = $attr->{'src'};
                   4187:                         &add_filetype($allfiles,$src,'src');
                   4188:                     }
                   4189:                 }
                   4190:                 my $text = $p->get_trimmed_text();
                   4191:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4192:                     my @swfargs = split(/,/,$1);
                   4193:                     foreach my $item (@swfargs) {
                   4194:                         $item =~ s/["']//g;
                   4195:                         $item =~ s/^\s+//;
                   4196:                         $item =~ s/\s+$//;
                   4197:                     }
                   4198:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4199:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4200:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4201:                         } else {
                   4202:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4203:                         }
                   4204:                     }
1.645     raeburn  4205:                 }
                   4206:             }
                   4207:             if (lc($tagname) eq 'link') {
                   4208:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4209:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4210:                 }
                   4211:             }
1.640     albertel 4212: 	    if (lc($tagname) eq 'object' ||
                   4213: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4214: 		foreach my $item (keys(%javafiles)) {
                   4215: 		    $javafiles{$item} = '';
                   4216: 		}
1.1164    raeburn  4217:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4218:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4219:                 }
1.640     albertel 4220: 	    }
                   4221: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4222: 		my $name = lc($attr->{'name'});
                   4223: 		foreach my $item (keys(%javafiles)) {
                   4224: 		    if ($name eq $item) {
                   4225: 			$javafiles{$item} = $attr->{'value'};
                   4226: 			last;
                   4227: 		    }
                   4228: 		}
1.1164    raeburn  4229:                 my $pathfrom;
1.640     albertel 4230: 		foreach my $item (keys(%mediafiles)) {
                   4231: 		    if ($name eq $item) {
1.1164    raeburn  4232:                         $pathfrom = $attr->{'value'};
                   4233:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4234: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4235: 			last;
                   4236: 		    }
                   4237: 		}
1.1164    raeburn  4238:                 if ($name eq 'flashvars') {
                   4239:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4240:                 }
                   4241:                 if ($pathfrom ne '') {
                   4242:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4243:                                          $pathfrom);
                   4244:                 }
1.640     albertel 4245: 	    }
                   4246: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4247: 		foreach my $item (keys(%javafiles)) {
                   4248: 		    if ($attr->{$item}) {
                   4249: 			$javafiles{$item} = $attr->{$item};
                   4250: 			last;
                   4251: 		    }
                   4252: 		}
                   4253: 		foreach my $item (keys(%mediafiles)) {
                   4254: 		    if ($attr->{$item}) {
                   4255: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4256: 			last;
                   4257: 		    }
                   4258: 		}
1.1164    raeburn  4259:                 if (lc($tagname) eq 'embed') {
                   4260:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4261:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4262:                                              $attr->{'src'});
                   4263:                     }
                   4264:                 }
1.640     albertel 4265: 	    }
1.1243    raeburn  4266:             if (lc($tagname) eq 'iframe') {
                   4267:                 my $src = $attr->{'src'} ;
                   4268:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4269:                     &add_filetype($allfiles,$src,'src');
                   4270:                 } elsif ($src =~ m{^/}) {
                   4271:                     if ($env{'request.course.id'}) {
                   4272:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4273:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4274:                         my $url = &hreflocation('',$fullpath);
                   4275:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4276:                             my $relpath = $1;
                   4277:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4278:                                 &add_filetype($allfiles,$1,'src');
                   4279:                             }
                   4280:                         }
                   4281:                     }
                   4282:                 }
                   4283:             }
1.1164    raeburn  4284:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4285:                 pop(@state);
1.1164    raeburn  4286:             }
1.640     albertel 4287: 	} elsif ($t->[0] eq 'E') {
                   4288: 	    my ($tagname) = ($t->[1]);
                   4289: 	    if ($javafiles{'codebase'} ne '') {
                   4290: 		$javafiles{'codebase'} .= '/';
                   4291: 	    }  
                   4292: 	    if (lc($tagname) eq 'applet' ||
                   4293: 		lc($tagname) eq 'object' ||
                   4294: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4295: 		) {
                   4296: 		foreach my $item (keys(%javafiles)) {
                   4297: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4298: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4299: 			&add_filetype($allfiles,$file,$item);
                   4300: 		    }
                   4301: 		}
                   4302: 	    } 
                   4303: 	    pop @state;
                   4304: 	}
                   4305:     }
1.1164    raeburn  4306:     foreach my $id (sort(keys(%flashvars))) {
                   4307:         if ($shockwave{$id} ne '') {
                   4308:             my @pairs = split(/\&/,$flashvars{$id});
                   4309:             foreach my $pair (@pairs) {
                   4310:                 my ($key,$value) = split(/\=/,$pair);
                   4311:                 if ($key eq 'thumb') {
                   4312:                     &add_filetype($allfiles,$value,$key);
                   4313:                 } elsif ($key eq 'content') {
                   4314:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4315:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4316:                     if ($ext ne '') {
                   4317:                         &add_filetype($allfiles,$path.$value,$ext);
                   4318:                     }
                   4319:                 }
                   4320:             }
                   4321:         }
                   4322:     }
1.637     raeburn  4323:     return 'ok';
                   4324: }
                   4325: 
1.639     albertel 4326: sub add_filetype {
                   4327:     my ($allfiles,$file,$type)=@_;
                   4328:     if (exists($allfiles->{$file})) {
                   4329: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4330: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4331: 	}
                   4332:     } else {
                   4333: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4334:     }
                   4335: }
                   4336: 
1.1164    raeburn  4337: sub embedded_dependency {
                   4338:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4339:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4340:         if (($identifier ne '') &&
                   4341:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4342:             ($pathfrom ne '')) {
                   4343:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4344:             foreach my $dep (@{$related->{$identifier}}) {
                   4345:                 &add_filetype($allfiles,$path.$dep,'object');
                   4346:             }
                   4347:         }
                   4348:     }
                   4349:     return;
                   4350: }
                   4351: 
1.493     albertel 4352: sub removeuploadedurl {
1.984     neumanie 4353:     my ($url)=@_;	
                   4354:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4355:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4356: }
                   4357: 
                   4358: sub removeuserfile {
                   4359:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4360:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4361:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4362:     if ($result eq 'ok') {	
1.798     raeburn  4363:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4364:             my $metafile = $fname.'.meta';
                   4365:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4366: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4367:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4368:             my $sqlresult = 
1.823     albertel 4369:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4370:                                         'portfolio_metadata',$group,
                   4371:                                         'delete');
1.798     raeburn  4372:         }
                   4373:     }
                   4374:     return $result;
1.257     www      4375: }
1.15      www      4376: 
1.530     albertel 4377: sub mkdiruserfile {
                   4378:     my ($docuname,$docudom,$dir)=@_;
                   4379:     my $home=&homeserver($docuname,$docudom);
                   4380:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4381: }
                   4382: 
1.531     albertel 4383: sub renameuserfile {
                   4384:     my ($docuname,$docudom,$old,$new)=@_;
                   4385:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4386:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4387:                         &escape("$old").':'.&escape("$new"),$home);
                   4388:     if ($result eq 'ok') {
                   4389:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4390:             my $oldmeta = $old.'.meta';
                   4391:             my $newmeta = $new.'.meta';
                   4392:             my $metaresult = 
                   4393:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4394: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4395:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4396:             my $sqlresult = 
1.823     albertel 4397:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4398:                                         'portfolio_metadata',$group,
                   4399:                                         'delete');
1.798     raeburn  4400:         }
                   4401:     }
                   4402:     return $result;
1.531     albertel 4403: }
                   4404: 
1.14      www      4405: # ------------------------------------------------------------------------- Log
                   4406: 
                   4407: sub log {
                   4408:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4409:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4410: }
                   4411: 
                   4412: # ------------------------------------------------------------------ Course Log
1.352     www      4413: #
                   4414: # This routine flushes several buffers of non-mission-critical nature
                   4415: #
1.157     www      4416: 
                   4417: sub flushcourselogs {
1.352     www      4418:     &logthis('Flushing log buffers');
                   4419: #
                   4420: # course logs
                   4421: # This is a log of all transactions in a course, which can be used
                   4422: # for data mining purposes
                   4423: #
                   4424: # It also collects the courseid database, which lists last transaction
                   4425: # times and course titles for all courseids
                   4426: #
                   4427:     my %courseidbuffer=();
1.921     raeburn  4428:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4429:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4430: 		          &escape($courselogs{$crsid}),
                   4431: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4432: 	    delete $courselogs{$crsid};
                   4433:         } else {
                   4434:             &logthis('Failed to flush log buffer for '.$crsid);
                   4435:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4436:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4437:                         " exceeded maximum size, deleting.</font>");
                   4438:                delete $courselogs{$crsid};
                   4439:             }
1.352     www      4440:         }
1.920     raeburn  4441:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4442:             'description' => $coursedescrbuf{$crsid},
                   4443:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4444:             'type'        => $coursetypebuf{$crsid},
                   4445:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4446:         };
1.191     harris41 4447:     }
1.352     www      4448: #
                   4449: # Write course id database (reverse lookup) to homeserver of courses 
                   4450: # Is used in pickcourse
                   4451: #
1.840     albertel 4452:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4453:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4454:                                     $courseidbuffer{$crs_home},
                   4455:                                     $crs_home,'timeonly');
1.352     www      4456:     }
                   4457: #
                   4458: # File accesses
                   4459: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4460: #
1.449     matthew  4461:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4462:         if ($entry =~ /___count$/) {
                   4463:             my ($dom,$name);
1.807     albertel 4464:             ($dom,$name,undef)=
1.811     albertel 4465: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4466:             if (! defined($dom) || $dom eq '' || 
                   4467:                 ! defined($name) || $name eq '') {
1.620     albertel 4468:                 my $cid = $env{'request.course.id'};
                   4469:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4470:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4471:             }
1.450     matthew  4472:             my $value = $accesshash{$entry};
                   4473:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4474:             my %temphash=($url => $value);
1.449     matthew  4475:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4476:             if ($result eq 'ok') {
                   4477:                 delete $accesshash{$entry};
                   4478:             }
                   4479:         } else {
1.811     albertel 4480:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4481:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4482:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4483:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4484:                 delete $accesshash{$entry};
                   4485:             }
1.185     www      4486:         }
1.191     harris41 4487:     }
1.352     www      4488: #
                   4489: # Roles
                   4490: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4491: #
1.800     albertel 4492:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4493:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4494: 	    split(/\:/,$entry);
                   4495:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4496:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4497:                 $rudom,$runame) eq 'ok') {
                   4498: 	    delete $userrolehash{$entry};
                   4499:         }
                   4500:     }
1.662     raeburn  4501: #
1.1334    raeburn  4502: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4503: #
                   4504:     my %domrolebuffer = ();
1.1000    raeburn  4505:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4506:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4507:         if ($domrolebuffer{$rudom}) {
                   4508:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4509:                       '='.&escape($domainrolehash{$entry});
                   4510:         } else {
                   4511:             $domrolebuffer{$rudom}.=&escape($entry).
                   4512:                       '='.&escape($domainrolehash{$entry});
                   4513:         }
                   4514:         delete $domainrolehash{$entry};
                   4515:     }
                   4516:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4517: 	my %servers;
                   4518: 	if (defined(&domain($dom,'primary'))) {
                   4519: 	    my $primary=&domain($dom,'primary');
                   4520: 	    my $hostname=&hostname($primary);
                   4521: 	    $servers{$primary} = $hostname;
                   4522: 	} else { 
                   4523: 	    %servers = &get_servers($dom,'library');
                   4524: 	}
1.841     albertel 4525: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4526: 	    if (&reply('domroleput:'.$dom.':'.
                   4527: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4528: 		last;
                   4529: 	    } else {  
1.841     albertel 4530: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4531: 	    }
1.662     raeburn  4532:         }
                   4533:     }
1.186     www      4534:     $dumpcount++;
1.157     www      4535: }
                   4536: 
                   4537: sub courselog {
                   4538:     my $what=shift;
1.158     www      4539:     $what=time.':'.$what;
1.620     albertel 4540:     unless ($env{'request.course.id'}) { return ''; }
                   4541:     $coursedombuf{$env{'request.course.id'}}=
                   4542:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4543:     $coursenumbuf{$env{'request.course.id'}}=
                   4544:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4545:     $coursehombuf{$env{'request.course.id'}}=
                   4546:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4547:     $coursedescrbuf{$env{'request.course.id'}}=
                   4548:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4549:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4550:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4551:     $courseownerbuf{$env{'request.course.id'}}=
                   4552:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4553:     $coursetypebuf{$env{'request.course.id'}}=
                   4554:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4555:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4556: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4557:     } else {
1.620     albertel 4558: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4559:     }
1.620     albertel 4560:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4561: 	&flushcourselogs();
                   4562:     }
1.158     www      4563: }
                   4564: 
                   4565: sub courseacclog {
                   4566:     my $fnsymb=shift;
1.620     albertel 4567:     unless ($env{'request.course.id'}) { return ''; }
                   4568:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4569:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4570:         $what.=':POST';
1.583     matthew  4571:         # FIXME: Probably ought to escape things....
1.800     albertel 4572: 	foreach my $key (keys(%env)) {
                   4573:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4574:                 my $formitem = $1;
                   4575:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4576:                     $what.=':'.$formitem.'='.$env{$key};
                   4577:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4578:                     $what.=':'.$formitem.'='.$env{$key};
                   4579:                 }
1.158     www      4580:             }
1.191     harris41 4581:         }
1.583     matthew  4582:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4583:         # FIXME: We should not be depending on a form parameter that someone
                   4584:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4585:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4586:             $what.= ':POST';
                   4587:             # FIXME: Probably ought to escape things....
                   4588:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4589:                                  'crsdiscuss') {
1.620     albertel 4590:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4591:             }
                   4592:         }
1.158     www      4593:     }
                   4594:     &courselog($what);
1.149     www      4595: }
                   4596: 
1.185     www      4597: sub countacc {
                   4598:     my $url=&declutter(shift);
1.458     matthew  4599:     return if (! defined($url) || $url eq '');
1.620     albertel 4600:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4601: #
                   4602: # Mark that this url was used in this course
                   4603: #
1.620     albertel 4604:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4605: #
                   4606: # Increase the access count for this resource in this child process
                   4607: #
1.281     www      4608:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4609:     $accesshash{$key}++;
1.185     www      4610: }
1.349     www      4611: 
1.361     www      4612: sub linklog {
                   4613:     my ($from,$to)=@_;
                   4614:     $from=&declutter($from);
                   4615:     $to=&declutter($to);
                   4616:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4617:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4618: }
1.1160    www      4619: 
                   4620: sub statslog {
                   4621:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4622:     if ($users<2) { return; }
                   4623:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4624:             'course'       => $env{'request.course.id'},
                   4625:             'sections'     => '"all"',
                   4626:             'num_students' => $users,
                   4627:             'part'         => $part,
                   4628:             'symb'         => $symb,
                   4629:             'mean_tries'   => $av_attempts,
                   4630:             'deg_of_diff'  => $degdiff});
                   4631:     foreach my $key (keys(%dynstore)) {
                   4632:         $accesshash{$key}=$dynstore{$key};
                   4633:     }
                   4634: }
1.361     www      4635:   
1.349     www      4636: sub userrolelog {
                   4637:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4638:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4639:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4640:        $userrolehash
                   4641:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4642:                     =$tend.':'.$tstart;
1.662     raeburn  4643:     }
1.1169    droeschl 4644:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4645:        $userrolehash
                   4646:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4647:                     =$tend.':'.$tstart;
                   4648:     }
1.1334    raeburn  4649:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4650:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4651:        $domainrolehash
                   4652:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4653:                     = $tend.':'.$tstart;
                   4654:     }
1.351     www      4655: }
                   4656: 
1.957     raeburn  4657: sub courserolelog {
                   4658:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4659:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4660:         my $cdom = $1;
                   4661:         my $cnum = $2;
                   4662:         my $sec = $3;
                   4663:         my $namespace = 'rolelog';
                   4664:         my %storehash = (
                   4665:                            role    => $trole,
                   4666:                            start   => $tstart,
                   4667:                            end     => $tend,
                   4668:                            selfenroll => $selfenroll,
                   4669:                            context    => $context,
                   4670:                         );
                   4671:         if ($trole eq 'gr') {
                   4672:             $namespace = 'groupslog';
                   4673:             $storehash{'group'} = $sec;
                   4674:         } else {
                   4675:             $storehash{'section'} = $sec;
                   4676:         }
1.1188    raeburn  4677:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4678:                    $domain,$cnum,$cdom);
1.1184    raeburn  4679:         if (($trole ne 'st') || ($sec ne '')) {
                   4680:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4681:         }
                   4682:     }
                   4683:     return;
                   4684: }
                   4685: 
1.1184    raeburn  4686: sub domainrolelog {
                   4687:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4688:     if ($area =~ m{^/($match_domain)/$}) {
                   4689:         my $cdom = $1;
                   4690:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4691:         my $namespace = 'rolelog';
                   4692:         my %storehash = (
                   4693:                            role    => $trole,
                   4694:                            start   => $tstart,
                   4695:                            end     => $tend,
                   4696:                            context => $context,
                   4697:                         );
1.1188    raeburn  4698:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4699:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4700:     }
                   4701:     return;
                   4702: 
                   4703: }
                   4704: 
                   4705: sub coauthorrolelog {
                   4706:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4707:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4708:         my $audom = $1;
                   4709:         my $auname = $2;
                   4710:         my $namespace = 'rolelog';
                   4711:         my %storehash = (
                   4712:                            role    => $trole,
                   4713:                            start   => $tstart,
                   4714:                            end     => $tend,
                   4715:                            context => $context,
                   4716:                         );
1.1188    raeburn  4717:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4718:                    $domain,$auname,$audom);
1.1184    raeburn  4719:     }
                   4720:     return;
                   4721: }
                   4722: 
1.351     www      4723: sub get_course_adv_roles {
1.948     raeburn  4724:     my ($cid,$codes) = @_;
1.620     albertel 4725:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4726:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4727:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4728:     my %nothide=();
1.800     albertel 4729:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4730:         if ($user !~ /:/) {
                   4731: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4732:         } else {
                   4733:             $nothide{$user}=1;
                   4734:         }
1.470     www      4735:     }
1.1219    raeburn  4736:     my @possdoms = ($coursehash{'domain'});
                   4737:     if ($coursehash{'checkforpriv'}) {
                   4738:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4739:     }
1.351     www      4740:     my %returnhash=();
                   4741:     my %dumphash=
                   4742:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4743:     my $now=time;
1.997     raeburn  4744:     my %privileged;
1.1000    raeburn  4745:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4746: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4747:         if (($tstart) && ($tstart<0)) { next; }
                   4748:         if (($tend) && ($tend<$now)) { next; }
                   4749:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4750:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4751: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4752:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4753:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4754: 	if ($role eq 'cr') { next; }
1.948     raeburn  4755:         if ($codes) {
                   4756:             if ($section) { $role .= ':'.$section; }
                   4757:             if ($returnhash{$role}) {
                   4758:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4759:             } else {
                   4760:                 $returnhash{$role}=$username.':'.$domain;
                   4761:             }
1.351     www      4762:         } else {
1.988     raeburn  4763:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4764:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4765:             if ($returnhash{$key}) {
                   4766: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4767:             } else {
                   4768:                 $returnhash{$key}=$username.':'.$domain;
                   4769:             }
1.351     www      4770:         }
1.948     raeburn  4771:     }
1.400     www      4772:     return %returnhash;
                   4773: }
                   4774: 
                   4775: sub get_my_roles {
1.937     raeburn  4776:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4777:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4778:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4779:     my (%dumphash,%nothide);
1.1086    raeburn  4780:     if ($context eq 'userroles') {
1.1166    raeburn  4781:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4782:     } else {
1.1219    raeburn  4783:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4784:         if ($hidepriv) {
                   4785:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4786:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4787:                 if ($user !~ /:/) {
                   4788:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4789:                 } else {
                   4790:                     $nothide{$user} = 1;
                   4791:                 }
                   4792:             }
                   4793:         }
1.858     raeburn  4794:     }
1.400     www      4795:     my %returnhash=();
                   4796:     my $now=time;
1.999     raeburn  4797:     my %privileged;
1.800     albertel 4798:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4799:         my ($role,$tend,$tstart);
                   4800:         if ($context eq 'userroles') {
1.1149    raeburn  4801:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4802: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4803:         } else {
                   4804:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4805:         }
1.400     www      4806:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4807:         my $status = 'active';
1.939     raeburn  4808:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4809:             $status = 'previous';
                   4810:         } 
                   4811:         if (($tstart) && ($now<$tstart)) {
                   4812:             $status = 'future';
                   4813:         }
                   4814:         if (ref($types) eq 'ARRAY') {
                   4815:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4816:                 next;
                   4817:             } 
                   4818:         } else {
                   4819:             if ($status ne 'active') {
                   4820:                 next;
                   4821:             }
                   4822:         }
1.867     raeburn  4823:         my ($rolecode,$username,$domain,$section,$area);
                   4824:         if ($context eq 'userroles') {
1.1186    raeburn  4825:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4826:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4827:         } else {
                   4828:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4829:         }
1.832     raeburn  4830:         if (ref($roledoms) eq 'ARRAY') {
                   4831:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4832:                 next;
                   4833:             }
                   4834:         }
                   4835:         if (ref($roles) eq 'ARRAY') {
                   4836:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4837:                 if ($role =~ /^cr\//) {
                   4838:                     if (!grep(/^cr$/,@{$roles})) {
                   4839:                         next;
                   4840:                     }
1.1104    raeburn  4841:                 } elsif ($role =~ /^gr\//) {
                   4842:                     if (!grep(/^gr$/,@{$roles})) {
                   4843:                         next;
                   4844:                     }
1.922     raeburn  4845:                 } else {
                   4846:                     next;
                   4847:                 }
1.832     raeburn  4848:             }
1.867     raeburn  4849:         }
1.937     raeburn  4850:         if ($hidepriv) {
1.1219    raeburn  4851:             my @privroles = ('dc','su');
1.999     raeburn  4852:             if ($context eq 'userroles') {
1.1219    raeburn  4853:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4854:             } else {
1.1219    raeburn  4855:                 my $possdoms = [$domain];
                   4856:                 if (ref($roledoms) eq 'ARRAY') {
                   4857:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4858:                 }
1.1219    raeburn  4859:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4860:                     if (!$nothide{$username.':'.$domain}) {
                   4861:                         next;
                   4862:                     }
                   4863:                 }
1.937     raeburn  4864:             }
                   4865:         }
1.933     raeburn  4866:         if ($withsec) {
                   4867:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4868:                 $tstart.':'.$tend;
                   4869:         } else {
                   4870:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4871:         }
1.832     raeburn  4872:     }
1.373     www      4873:     return %returnhash;
1.399     www      4874: }
                   4875: 
1.1333    raeburn  4876: sub get_all_adhocroles {
                   4877:     my ($dom) = @_;
                   4878:     my @roles_by_num = ();
                   4879:     my %domdefaults = &get_domain_defaults($dom);
                   4880:     my (%description,%access_in_dom,%access_info);
                   4881:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4882:         my $count = 0;
                   4883:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4884:         my %ordered;
                   4885:         foreach my $role (sort(keys(%domcurrent))) {
                   4886:             my ($order,$desc,$access_in_dom);
                   4887:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4888:                 $order = $domcurrent{$role}{'order'};
                   4889:                 $desc = $domcurrent{$role}{'desc'};
                   4890:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4891:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4892:             }
                   4893:             if ($order eq '') {
                   4894:                 $order = $count;
                   4895:             }
                   4896:             $ordered{$order} = $role;
                   4897:             if ($desc ne '') {
                   4898:                 $description{$role} = $desc;
                   4899:             } else {
                   4900:                 $description{$role}= $role;
                   4901:             }
                   4902:             $count++;
                   4903:         }
                   4904:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4905:             push(@roles_by_num,$ordered{$item});
                   4906:         }
                   4907:     }
                   4908:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4909: }
                   4910: 
1.1332    raeburn  4911: sub get_my_adhocroles {
1.1333    raeburn  4912:     my ($cid,$checkreg) = @_;
                   4913:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4914:     if ($env{'request.course.id'} eq $cid) {
                   4915:         $cdom = $env{'course.'.$cid.'.domain'};
                   4916:         $cnum = $env{'course.'.$cid.'.num'};
                   4917:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4918:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4919:         $cdom = $1;
                   4920:         $cnum = $2;
                   4921:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4922:                                      $cdom,$cnum);
                   4923:     }
                   4924:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4925:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4926:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4927:         if ($rosterhash{$user} ne '') {
                   4928:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4929:             return ([],{}) if ($type eq 'auto');
                   4930:         }
                   4931:     }
                   4932:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4933:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4934:             my $then=$env{'user.login.time'};
                   4935:             my $update=$env{'user.update.time'};
1.1335    raeburn  4936:             if (!$update) {
                   4937:                 $update = $then;
                   4938:             }
                   4939:             my @liveroles;
1.1334    raeburn  4940:             foreach my $role ('dh','da') {
                   4941:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4942:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4943:                     my $limit = $update;
                   4944:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4945:                         $limit = $then;
                   4946:                     }
1.1335    raeburn  4947:                     my $activerole = 1;
                   4948:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4949:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4950:                     if ($activerole) {
                   4951:                         push(@liveroles,$role);
                   4952:                     }
1.1334    raeburn  4953:                 }
1.1332    raeburn  4954:             }
1.1335    raeburn  4955:             if (@liveroles) {
1.1332    raeburn  4956:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4957:                     my ($accessref,$accessinfo,%access_in_dom);
                   4958:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4959:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4960:                         if (@{$roles_by_num}) {
1.1332    raeburn  4961:                             my %settings;
                   4962:                             if ($env{'request.course.id'} eq $cid) {
                   4963:                                 foreach my $envkey (keys(%env)) {
                   4964:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4965:                                         $settings{$1} = $env{$envkey};
                   4966:                                     }
                   4967:                                 }
                   4968:                             } else {
                   4969:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4970:                             }
                   4971:                             my %setincrs;
                   4972:                             if ($settings{'internal.adhocaccess'}) {
                   4973:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4974:                             }
                   4975:                             my @statuses;
                   4976:                             if ($env{'environment.inststatus'}) {
                   4977:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4978:                             }
                   4979:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4980:                             if (ref($accessref) eq 'HASH') {
                   4981:                                 %access_in_dom = %{$accessref};
                   4982:                             }
                   4983:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4984:                                 my ($curraccess,@okstatus,@personnel);
                   4985:                                 if ($setincrs{$role}) {
                   4986:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4987:                                     if ($curraccess eq 'status') {
                   4988:                                         @okstatus = split(/\&/,$rest);
                   4989:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4990:                                         @personnel = split(/\&/,$rest);
                   4991:                                     }
                   4992:                                 } else {
                   4993:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4994:                                     if (ref($accessinfo) eq 'HASH') {
                   4995:                                         if ($curraccess eq 'status') {
                   4996:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4997:                                                 @okstatus = @{$accessinfo->{$role}};
                   4998:                                             }
                   4999:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5000:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5001:                                                 @personnel = @{$accessinfo->{$role}};
                   5002:                                             }
1.1332    raeburn  5003:                                         }
                   5004:                                     }
                   5005:                                 }
                   5006:                                 if ($curraccess eq 'none') {
                   5007:                                     next;
                   5008:                                 } elsif ($curraccess eq 'all') {
                   5009:                                     push(@possroles,$role);
1.1336    raeburn  5010:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5011:                                     if (grep(/^dh$/,@liveroles)) {
                   5012:                                         push(@possroles,$role);
                   5013:                                     } else {
                   5014:                                         next;
                   5015:                                     }
1.1336    raeburn  5016:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5017:                                     if (grep(/^da$/,@liveroles)) {
                   5018:                                         push(@possroles,$role);
                   5019:                                     } else {
                   5020:                                         next;
                   5021:                                     }
1.1332    raeburn  5022:                                 } elsif ($curraccess eq 'status') {
                   5023:                                     if (@okstatus) {
                   5024:                                         if (!@statuses) {
                   5025:                                             if (grep(/^default$/,@okstatus)) {
                   5026:                                                 push(@possroles,$role);
                   5027:                                             }
                   5028:                                         } else {
                   5029:                                             foreach my $status (@okstatus) {
                   5030:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5031:                                                     push(@possroles,$role);
                   5032:                                                     last;
                   5033:                                                 }
                   5034:                                             }
                   5035:                                         }
                   5036:                                     }
                   5037:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5038:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5039:                                         if ($curraccess eq 'exc') {
                   5040:                                             push(@possroles,$role);
                   5041:                                         }
                   5042:                                     } elsif ($curraccess eq 'inc') {
                   5043:                                         push(@possroles,$role);
                   5044:                                     }
                   5045:                                 }
                   5046:                             }
                   5047:                         }
                   5048:                     }
                   5049:                 }
                   5050:             }
                   5051:         }
                   5052:     }
1.1333    raeburn  5053:     unless (ref($description) eq 'HASH') {
                   5054:         if (ref($roles_by_num) eq 'ARRAY') {
                   5055:             my %desc;
                   5056:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5057:             $description = \%desc;
                   5058:         } else {
                   5059:             $description = {};
                   5060:         }
                   5061:     }
                   5062:     return (\@possroles,$description);
1.1332    raeburn  5063: }
                   5064: 
1.399     www      5065: # ----------------------------------------------------- Frontpage Announcements
                   5066: #
                   5067: #
                   5068: 
                   5069: sub postannounce {
                   5070:     my ($server,$text)=@_;
1.844     albertel 5071:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5072:     unless ($text=~/\w/) { $text=''; }
                   5073:     return &reply('setannounce:'.&escape($text),$server);
                   5074: }
                   5075: 
                   5076: sub getannounce {
1.448     albertel 5077: 
1.1359    raeburn  5078:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5079: 	my $announcement='';
1.800     albertel 5080: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5081: 	close($fh);
1.399     www      5082: 	if ($announcement=~/\w/) { 
                   5083: 	    return 
                   5084:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5085:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5086: 	} else {
                   5087: 	    return '';
                   5088: 	}
                   5089:     } else {
                   5090: 	return '';
                   5091:     }
1.351     www      5092: }
1.353     www      5093: 
                   5094: # ---------------------------------------------------------- Course ID routines
                   5095: # Deal with domain's nohist_courseid.db files
                   5096: #
                   5097: 
                   5098: sub courseidput {
1.921     raeburn  5099:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5100:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5101:     my $outcome;
                   5102:     if ($caller eq 'timeonly') {
                   5103:         my $cids = '';
                   5104:         foreach my $item (keys(%$storehash)) {
                   5105:             $cids.=&escape($item).'&';
                   5106:         }
                   5107:         $cids=~s/\&$//;
                   5108:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5109:                           $coursehome);       
                   5110:     } else {
                   5111:         my $items = '';
                   5112:         foreach my $item (keys(%$storehash)) {
                   5113:             $items.= &escape($item).'='.
                   5114:                      &freeze_escape($$storehash{$item}).'&';
                   5115:         }
                   5116:         $items=~s/\&$//;
                   5117:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5118:                           $coursehome);
1.918     raeburn  5119:     }
                   5120:     if ($outcome eq 'unknown_cmd') {
                   5121:         my $what;
                   5122:         foreach my $cid (keys(%$storehash)) {
                   5123:             $what .= &escape($cid).'=';
1.921     raeburn  5124:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5125:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5126:             }
                   5127:             $what =~ s/\:$/&/;
                   5128:         }
                   5129:         $what =~ s/\&$//;  
                   5130:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5131:     } else {
                   5132:         return $outcome;
                   5133:     }
1.353     www      5134: }
                   5135: 
                   5136: sub courseiddump {
1.921     raeburn  5137:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5138:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5139:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5140:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5141:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5142:     my $as_hash = 1;
                   5143:     my %returnhash;
                   5144:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5145:     my %libserv = &all_library();
                   5146:     foreach my $tryserver (keys(%libserv)) {
                   5147:         if ( (  $hostidflag == 1 
                   5148: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5149: 	     || (!defined($hostidflag)) ) {
                   5150: 
1.918     raeburn  5151: 	    if (($domfilter eq '') ||
                   5152: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5153:                 my $rep;
                   5154:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5155:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5156:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5157:                                 &escape($descfilter), &escape($instcodefilter), 
                   5158:                                 &escape($ownerfilter), &escape($coursefilter),
                   5159:                                 &escape($typefilter), &escape($regexp_ok), 
                   5160:                                 $as_hash, &escape($selfenrollonly), 
                   5161:                                 &escape($catfilter), $showhidden, $caller, 
                   5162:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5163:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5164:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5165:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5166:                 } else {
                   5167:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5168:                              $sincefilter.':'.&escape($descfilter).':'.
                   5169:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5170:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5171:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5172:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5173:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5174:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5175:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5176:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5177:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5178:                 }
                   5179:                      
1.918     raeburn  5180:                 my @pairs=split(/\&/,$rep);
                   5181:                 foreach my $item (@pairs) {
                   5182:                     my ($key,$value)=split(/\=/,$item,2);
                   5183:                     $key = &unescape($key);
                   5184:                     next if ($key =~ /^error: 2 /);
                   5185:                     my $result = &thaw_unescape($value);
                   5186:                     if (ref($result) eq 'HASH') {
                   5187:                         $returnhash{$key}=$result;
                   5188:                     } else {
1.921     raeburn  5189:                         my @responses = split(/:/,$value);
                   5190:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5191:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5192:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5193:                         }
1.1008    raeburn  5194:                     }
1.353     www      5195:                 }
                   5196:             }
                   5197:         }
                   5198:     }
                   5199:     return %returnhash;
                   5200: }
                   5201: 
1.1055    raeburn  5202: sub courselastaccess {
                   5203:     my ($cdom,$cnum,$hostidref) = @_;
                   5204:     my %returnhash;
                   5205:     if ($cdom && $cnum) {
                   5206:         my $chome = &homeserver($cnum,$cdom);
                   5207:         if ($chome ne 'no_host') {
                   5208:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5209:             &extract_lastaccess(\%returnhash,$rep);
                   5210:         }
                   5211:     } else {
                   5212:         if (!$cdom) { $cdom=''; }
                   5213:         my %libserv = &all_library();
                   5214:         foreach my $tryserver (keys(%libserv)) {
                   5215:             if (ref($hostidref) eq 'ARRAY') {
                   5216:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5217:             } 
                   5218:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5219:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5220:                 &extract_lastaccess(\%returnhash,$rep);
                   5221:             }
                   5222:         }
                   5223:     }
                   5224:     return %returnhash;
                   5225: }
                   5226: 
                   5227: sub extract_lastaccess {
                   5228:     my ($returnhash,$rep) = @_;
                   5229:     if (ref($returnhash) eq 'HASH') {
                   5230:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5231:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5232:                  $rep eq '') {
                   5233:             my @pairs=split(/\&/,$rep);
                   5234:             foreach my $item (@pairs) {
                   5235:                 my ($key,$value)=split(/\=/,$item,2);
                   5236:                 $key = &unescape($key);
                   5237:                 next if ($key =~ /^error: 2 /);
                   5238:                 $returnhash->{$key} = &thaw_unescape($value);
                   5239:             }
                   5240:         }
                   5241:     }
                   5242:     return;
                   5243: }
                   5244: 
1.658     raeburn  5245: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5246: 
                   5247: sub dcmailput {
1.685     raeburn  5248:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5249:     my $status = &Apache::lonnet::critical(
1.740     www      5250:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5251:        &escape($message),$server);
1.662     raeburn  5252:     return $status;
                   5253: }
                   5254: 
1.658     raeburn  5255: sub dcmaildump {
                   5256:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5257:     my %returnhash=();
1.846     albertel 5258: 
                   5259:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5260:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5261:                                                          &escape($enddate).':';
                   5262: 	my @esc_senders=map { &escape($_)} @$senders;
                   5263: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5264: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5265:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5266:             if (($key) && ($value)) {
                   5267:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5268:             }
                   5269:         }
                   5270:     }
                   5271:     return %returnhash;
                   5272: }
1.662     raeburn  5273: # ---------------------------------------------------------- Domain roles
                   5274: 
                   5275: sub get_domain_roles {
                   5276:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5277:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5278:         $startdate = '.';
                   5279:     }
1.1018    raeburn  5280:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5281:         $enddate = '.';
                   5282:     }
1.922     raeburn  5283:     my $rolelist;
                   5284:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5285:         $rolelist = join('&',@{$roles});
1.922     raeburn  5286:     }
1.662     raeburn  5287:     my %personnel = ();
1.841     albertel 5288: 
                   5289:     my %servers = &get_servers($dom,'library');
                   5290:     foreach my $tryserver (keys(%servers)) {
                   5291: 	%{$personnel{$tryserver}}=();
                   5292: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5293: 					    &escape($startdate).':'.
                   5294: 					    &escape($enddate).':'.
                   5295: 					    &escape($rolelist), $tryserver))) {
                   5296: 	    my ($key,$value) = split(/\=/,$line,2);
                   5297: 	    if (($key) && ($value)) {
                   5298: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5299: 	    }
                   5300: 	}
1.662     raeburn  5301:     }
                   5302:     return %personnel;
                   5303: }
1.658     raeburn  5304: 
1.1332    raeburn  5305: sub get_active_domroles {
                   5306:     my ($dom,$roles) = @_;
                   5307:     return () unless (ref($roles) eq 'ARRAY');
                   5308:     my $now = time;
                   5309:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5310:     my %domroles;
                   5311:     foreach my $server (keys(%dompersonnel)) {
                   5312:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5313:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5314:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5315:         }
                   5316:     }
                   5317:     return %domroles;
                   5318: }
                   5319: 
1.1057    www      5320: # ----------------------------------------------------------- Interval timing 
1.149     www      5321: 
1.1153    www      5322: {
                   5323: # Caches needed for speedup of navmaps
                   5324: # We don't want to cache this for very long at all (5 seconds at most)
                   5325: # 
                   5326: # The user for whom we cache
                   5327: my $cachedkey='';
                   5328: # The cached times for this user
                   5329: my %cachedtimes=();
                   5330: # When this was last done
1.1282    raeburn  5331: my $cachedtime='';
1.1153    www      5332: 
                   5333: sub load_all_first_access {
1.1308    raeburn  5334:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5335:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5336:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5337:         (!$ignorecache)) {
1.1154    raeburn  5338:         return;
                   5339:     }
                   5340:     $cachedtime=time;
                   5341:     $cachedkey=$uname.':'.$udom;
                   5342:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5343: }
                   5344: 
1.504     albertel 5345: sub get_first_access {
1.1308    raeburn  5346:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5347:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5348:     if ($argsymb) { $symb=$argsymb; }
                   5349:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5350:     if ($argmap) { $map = $argmap; }
1.926     albertel 5351:     if ($type eq 'course') {
                   5352: 	$res='course';
                   5353:     } elsif ($type eq 'map') {
1.588     albertel 5354: 	$res=&symbread($map);
                   5355:     } else {
                   5356: 	$res=$symb;
                   5357:     }
1.1308    raeburn  5358:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5359:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5360: }
                   5361: 
                   5362: sub set_first_access {
1.1162    raeburn  5363:     my ($type,$interval)=@_;
1.790     albertel 5364:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5365:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5366:     if ($type eq 'course') {
                   5367: 	$res='course';
                   5368:     } elsif ($type eq 'map') {
1.588     albertel 5369: 	$res=&symbread($map);
                   5370:     } else {
                   5371: 	$res=$symb;
                   5372:     }
1.1153    www      5373:     $cachedkey='';
1.1162    raeburn  5374:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5375:     if ($firstaccess) {
                   5376:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5377:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5378:                  "in $courseid");
1.1386    raeburn  5379:         return 'already_set';
                   5380:     } else {
1.1162    raeburn  5381:         my $start = time;
                   5382: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5383:                           $udom,$uname);
                   5384:         if ($putres eq 'ok') {
                   5385:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5386:                  $udom,$uname); 
                   5387:             &appenv(
                   5388:                      {
                   5389:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5390:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5391:                      }
                   5392:                   );
1.1365    raeburn  5393:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5394:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5395:             }
1.1386    raeburn  5396:         } elsif ($putres ne 'refused') {
                   5397:             &logthis("Result: $putres when attempting to set first access time ".
                   5398:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5399:         }
                   5400:         return $putres;
1.505     albertel 5401:     }
                   5402:     return 'already_set';
1.504     albertel 5403: }
1.1153    www      5404: }
1.1282    raeburn  5405: 
1.110     www      5406: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5407: 
                   5408: sub expirespread {
                   5409:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5410:     my $cid=$env{'request.course.id'}; 
1.110     www      5411:     if ($cid) {
                   5412:        my $now=time;
                   5413:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5414:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5415:                             $env{'course.'.$cid.'.num'}.
1.110     www      5416: 	        	    ':nohist_expirationdates:'.
                   5417:                             &escape($key).'='.$now,
1.620     albertel 5418:                             $env{'course.'.$cid.'.home'})
1.110     www      5419:     }
                   5420:     return 'ok';
1.14      www      5421: }
                   5422: 
1.109     www      5423: # ----------------------------------------------------- Devalidate Spreadsheets
                   5424: 
                   5425: sub devalidate {
1.325     www      5426:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5427:     my $cid=$env{'request.course.id'}; 
1.109     www      5428:     if ($cid) {
1.391     matthew  5429:         # delete the stored spreadsheets for
                   5430:         # - the student level sheet of this user in course's homespace
                   5431:         # - the assessment level sheet for this resource 
                   5432:         #   for this user in user's homespace
1.553     albertel 5433: 	# - current conditional state info
1.325     www      5434: 	my $key=$uname.':'.$udom.':';
1.109     www      5435:         my $status=
1.299     matthew  5436: 	    &del('nohist_calculatedsheets',
1.391     matthew  5437: 		 [$key.'studentcalc:'],
1.620     albertel 5438: 		 $env{'course.'.$cid.'.domain'},
                   5439: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5440: 		.' '.
                   5441: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5442: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5443:         unless ($status eq 'ok ok') {
                   5444:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5445:                     $uname.' at '.$udom.' for '.
1.109     www      5446: 		    $symb.': '.$status);
1.133     albertel 5447:         }
1.553     albertel 5448: 	&delenv('user.state.'.$cid);
1.109     www      5449:     }
                   5450: }
                   5451: 
1.265     albertel 5452: sub get_scalar {
                   5453:     my ($string,$end) = @_;
                   5454:     my $value;
                   5455:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5456: 	$value = $1;
                   5457:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5458: 	$value = $1;
                   5459:     }
                   5460:     return &unescape($value);
                   5461: }
                   5462: 
                   5463: sub array2str {
                   5464:   my (@array) = @_;
                   5465:   my $result=&arrayref2str(\@array);
                   5466:   $result=~s/^__ARRAY_REF__//;
                   5467:   $result=~s/__END_ARRAY_REF__$//;
                   5468:   return $result;
                   5469: }
                   5470: 
1.204     albertel 5471: sub arrayref2str {
                   5472:   my ($arrayref) = @_;
1.265     albertel 5473:   my $result='__ARRAY_REF__';
1.204     albertel 5474:   foreach my $elem (@$arrayref) {
1.265     albertel 5475:     if(ref($elem) eq 'ARRAY') {
                   5476:       $result.=&arrayref2str($elem).'&';
                   5477:     } elsif(ref($elem) eq 'HASH') {
                   5478:       $result.=&hashref2str($elem).'&';
                   5479:     } elsif(ref($elem)) {
                   5480:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5481:     } else {
                   5482:       $result.=&escape($elem).'&';
                   5483:     }
                   5484:   }
                   5485:   $result=~s/\&$//;
1.265     albertel 5486:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5487:   return $result;
                   5488: }
                   5489: 
1.168     albertel 5490: sub hash2str {
1.204     albertel 5491:   my (%hash) = @_;
                   5492:   my $result=&hashref2str(\%hash);
1.265     albertel 5493:   $result=~s/^__HASH_REF__//;
                   5494:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5495:   return $result;
                   5496: }
                   5497: 
                   5498: sub hashref2str {
                   5499:   my ($hashref)=@_;
1.265     albertel 5500:   my $result='__HASH_REF__';
1.800     albertel 5501:   foreach my $key (sort(keys(%$hashref))) {
                   5502:     if (ref($key) eq 'ARRAY') {
                   5503:       $result.=&arrayref2str($key).'=';
                   5504:     } elsif (ref($key) eq 'HASH') {
                   5505:       $result.=&hashref2str($key).'=';
                   5506:     } elsif (ref($key)) {
1.265     albertel 5507:       $result.='=';
1.800     albertel 5508:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5509:     } else {
1.1132    raeburn  5510: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5511:     }
                   5512: 
1.800     albertel 5513:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5514:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5515:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5516:       $result.=&hashref2str($hashref->{$key}).'&';
                   5517:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5518:        $result.='&';
1.800     albertel 5519:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5520:     } else {
1.800     albertel 5521:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5522:     }
                   5523:   }
1.168     albertel 5524:   $result=~s/\&$//;
1.265     albertel 5525:   $result .= '__END_HASH_REF__';
1.168     albertel 5526:   return $result;
                   5527: }
                   5528: 
                   5529: sub str2hash {
1.265     albertel 5530:     my ($string)=@_;
                   5531:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5532:     return %$hash;
                   5533: }
                   5534: 
                   5535: sub str2hashref {
1.168     albertel 5536:   my ($string) = @_;
1.265     albertel 5537: 
                   5538:   my %hash;
                   5539: 
                   5540:   if($string !~ /^__HASH_REF__/) {
                   5541:       if (! ($string eq '' || !defined($string))) {
                   5542: 	  $hash{'error'}='Not hash reference';
                   5543:       }
                   5544:       return (\%hash, $string);
                   5545:   }
                   5546: 
                   5547:   $string =~ s/^__HASH_REF__//;
                   5548: 
                   5549:   while($string !~ /^__END_HASH_REF__/) {
                   5550:       #key
                   5551:       my $key='';
                   5552:       if($string =~ /^__HASH_REF__/) {
                   5553:           ($key, $string)=&str2hashref($string);
                   5554:           if(defined($key->{'error'})) {
                   5555:               $hash{'error'}='Bad data';
                   5556:               return (\%hash, $string);
                   5557:           }
                   5558:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5559:           ($key, $string)=&str2arrayref($string);
                   5560:           if($key->[0] eq 'Array reference error') {
                   5561:               $hash{'error'}='Bad data';
                   5562:               return (\%hash, $string);
                   5563:           }
                   5564:       } else {
                   5565:           $string =~ s/^(.*?)=//;
1.267     albertel 5566: 	  $key=&unescape($1);
1.265     albertel 5567:       }
                   5568:       $string =~ s/^=//;
                   5569: 
                   5570:       #value
                   5571:       my $value='';
                   5572:       if($string =~ /^__HASH_REF__/) {
                   5573:           ($value, $string)=&str2hashref($string);
                   5574:           if(defined($value->{'error'})) {
                   5575:               $hash{'error'}='Bad data';
                   5576:               return (\%hash, $string);
                   5577:           }
                   5578:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5579:           ($value, $string)=&str2arrayref($string);
                   5580:           if($value->[0] eq 'Array reference error') {
                   5581:               $hash{'error'}='Bad data';
                   5582:               return (\%hash, $string);
                   5583:           }
                   5584:       } else {
                   5585: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5586:       }
                   5587:       $string =~ s/^&//;
                   5588: 
                   5589:       $hash{$key}=$value;
1.204     albertel 5590:   }
1.265     albertel 5591: 
                   5592:   $string =~ s/^__END_HASH_REF__//;
                   5593: 
                   5594:   return (\%hash, $string);
1.204     albertel 5595: }
                   5596: 
                   5597: sub str2array {
1.265     albertel 5598:     my ($string)=@_;
                   5599:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5600:     return @$array;
                   5601: }
                   5602: 
                   5603: sub str2arrayref {
1.204     albertel 5604:   my ($string) = @_;
1.265     albertel 5605:   my @array;
                   5606: 
                   5607:   if($string !~ /^__ARRAY_REF__/) {
                   5608:       if (! ($string eq '' || !defined($string))) {
                   5609: 	  $array[0]='Array reference error';
                   5610:       }
                   5611:       return (\@array, $string);
                   5612:   }
                   5613: 
                   5614:   $string =~ s/^__ARRAY_REF__//;
                   5615: 
                   5616:   while($string !~ /^__END_ARRAY_REF__/) {
                   5617:       my $value='';
                   5618:       if($string =~ /^__HASH_REF__/) {
                   5619:           ($value, $string)=&str2hashref($string);
                   5620:           if(defined($value->{'error'})) {
                   5621:               $array[0] ='Array reference error';
                   5622:               return (\@array, $string);
                   5623:           }
                   5624:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5625:           ($value, $string)=&str2arrayref($string);
                   5626:           if($value->[0] eq 'Array reference error') {
                   5627:               $array[0] ='Array reference error';
                   5628:               return (\@array, $string);
                   5629:           }
                   5630:       } else {
                   5631: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5632:       }
                   5633:       $string =~ s/^&//;
                   5634: 
                   5635:       push(@array, $value);
1.191     harris41 5636:   }
1.265     albertel 5637: 
                   5638:   $string =~ s/^__END_ARRAY_REF__//;
                   5639: 
                   5640:   return (\@array, $string);
1.168     albertel 5641: }
                   5642: 
1.167     albertel 5643: # -------------------------------------------------------------------Temp Store
                   5644: 
1.168     albertel 5645: sub tmpreset {
                   5646:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5647:   if (!$symb) {
                   5648:     $symb=&symbread();
1.620     albertel 5649:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5650:   }
                   5651:   $symb=escape($symb);
                   5652: 
1.620     albertel 5653:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5654:   $namespace=~s/\//\_/g;
                   5655:   $namespace=~s/\W//g;
                   5656: 
1.620     albertel 5657:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5658:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5659:   if ($domain eq 'public' && $stuname eq 'public') {
                   5660:       $stuname=$ENV{'REMOTE_ADDR'};
                   5661:   }
1.1117    foxr     5662:   my $path=LONCAPA::tempdir();
1.168     albertel 5663:   my %hash;
                   5664:   if (tie(%hash,'GDBM_File',
                   5665: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5666: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5667:     foreach my $key (keys(%hash)) {
1.180     albertel 5668:       if ($key=~ /:$symb/) {
1.168     albertel 5669: 	delete($hash{$key});
                   5670:       }
                   5671:     }
                   5672:   }
                   5673: }
                   5674: 
1.167     albertel 5675: sub tmpstore {
1.168     albertel 5676:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5677: 
                   5678:   if (!$symb) {
                   5679:     $symb=&symbread();
1.620     albertel 5680:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5681:   }
                   5682:   $symb=escape($symb);
                   5683: 
                   5684:   if (!$namespace) {
                   5685:     # I don't think we would ever want to store this for a course.
                   5686:     # it seems this will only be used if we don't have a course.
1.620     albertel 5687:     #$namespace=$env{'request.course.id'};
1.168     albertel 5688:     #if (!$namespace) {
1.620     albertel 5689:       $namespace=$env{'request.state'};
1.168     albertel 5690:     #}
                   5691:   }
                   5692:   $namespace=~s/\//\_/g;
                   5693:   $namespace=~s/\W//g;
1.620     albertel 5694:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5695:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5696:   if ($domain eq 'public' && $stuname eq 'public') {
                   5697:       $stuname=$ENV{'REMOTE_ADDR'};
                   5698:   }
1.168     albertel 5699:   my $now=time;
                   5700:   my %hash;
1.1117    foxr     5701:   my $path=LONCAPA::tempdir();
1.168     albertel 5702:   if (tie(%hash,'GDBM_File',
                   5703: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5704: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5705:     $hash{"version:$symb"}++;
                   5706:     my $version=$hash{"version:$symb"};
                   5707:     my $allkeys=''; 
                   5708:     foreach my $key (keys(%$storehash)) {
                   5709:       $allkeys.=$key.':';
1.591     albertel 5710:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5711:     }
                   5712:     $hash{"$version:$symb:timestamp"}=$now;
                   5713:     $allkeys.='timestamp';
                   5714:     $hash{"$version:keys:$symb"}=$allkeys;
                   5715:     if (untie(%hash)) {
                   5716:       return 'ok';
                   5717:     } else {
                   5718:       return "error:$!";
                   5719:     }
                   5720:   } else {
                   5721:     return "error:$!";
                   5722:   }
                   5723: }
1.167     albertel 5724: 
1.168     albertel 5725: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5726: 
1.168     albertel 5727: sub tmprestore {
                   5728:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5729: 
1.168     albertel 5730:   if (!$symb) {
                   5731:     $symb=&symbread();
1.620     albertel 5732:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5733:   }
                   5734:   $symb=escape($symb);
                   5735: 
1.620     albertel 5736:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5737: 
1.620     albertel 5738:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5739:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5740:   if ($domain eq 'public' && $stuname eq 'public') {
                   5741:       $stuname=$ENV{'REMOTE_ADDR'};
                   5742:   }
1.168     albertel 5743:   my %returnhash;
                   5744:   $namespace=~s/\//\_/g;
                   5745:   $namespace=~s/\W//g;
                   5746:   my %hash;
1.1117    foxr     5747:   my $path=LONCAPA::tempdir();
1.168     albertel 5748:   if (tie(%hash,'GDBM_File',
                   5749: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5750: 	  &GDBM_READER(),0640)) {
1.168     albertel 5751:     my $version=$hash{"version:$symb"};
                   5752:     $returnhash{'version'}=$version;
                   5753:     my $scope;
                   5754:     for ($scope=1;$scope<=$version;$scope++) {
                   5755:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5756:       my @keys=split(/:/,$vkeys);
                   5757:       my $key;
                   5758:       $returnhash{"$scope:keys"}=$vkeys;
                   5759:       foreach $key (@keys) {
1.591     albertel 5760: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5761: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5762:       }
                   5763:     }
1.168     albertel 5764:     if (!(untie(%hash))) {
                   5765:       return "error:$!";
                   5766:     }
                   5767:   } else {
                   5768:     return "error:$!";
                   5769:   }
                   5770:   return %returnhash;
1.167     albertel 5771: }
                   5772: 
1.9       www      5773: # ----------------------------------------------------------------------- Store
                   5774: 
                   5775: sub store {
1.1269    raeburn  5776:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5777:     my $home='';
                   5778: 
1.168     albertel 5779:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5780: 
1.213     www      5781:     $symb=&symbclean($symb);
1.122     albertel 5782:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5783: 
1.620     albertel 5784:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5785:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5786: 
                   5787:     &devalidate($symb,$stuname,$domain);
1.109     www      5788: 
                   5789:     $symb=escape($symb);
1.187     www      5790:     if (!$namespace) { 
1.620     albertel 5791:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5792:           return ''; 
                   5793:        } 
                   5794:     }
1.620     albertel 5795:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5796: 
                   5797:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5798:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5799: 
1.12      www      5800:     my $namevalue='';
1.800     albertel 5801:     foreach my $key (keys(%$storehash)) {
                   5802:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5803:     }
1.12      www      5804:     $namevalue=~s/\&$//;
1.187     www      5805:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5806:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5807: }
                   5808: 
1.47      www      5809: # -------------------------------------------------------------- Critical Store
                   5810: 
                   5811: sub cstore {
1.1269    raeburn  5812:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5813:     my $home='';
                   5814: 
1.168     albertel 5815:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5816: 
1.213     www      5817:     $symb=&symbclean($symb);
1.122     albertel 5818:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5819: 
1.620     albertel 5820:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5821:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5822: 
                   5823:     &devalidate($symb,$stuname,$domain);
1.109     www      5824: 
                   5825:     $symb=escape($symb);
1.187     www      5826:     if (!$namespace) { 
1.620     albertel 5827:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5828:           return ''; 
                   5829:        } 
                   5830:     }
1.620     albertel 5831:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5832: 
                   5833:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5834:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5835: 
1.47      www      5836:     my $namevalue='';
1.800     albertel 5837:     foreach my $key (keys(%$storehash)) {
                   5838:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5839:     }
1.47      www      5840:     $namevalue=~s/\&$//;
1.187     www      5841:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5842:     return critical
1.1269    raeburn  5843:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5844: }
                   5845: 
1.9       www      5846: # --------------------------------------------------------------------- Restore
                   5847: 
                   5848: sub restore {
1.124     www      5849:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5850:     my $home='';
                   5851: 
1.168     albertel 5852:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5853: 
1.122     albertel 5854:     if (!$symb) {
1.1224    raeburn  5855:         return if ($namespace eq 'courserequests');
                   5856:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5857:     } else {
1.1224    raeburn  5858:         unless ($namespace eq 'courserequests') {
                   5859:             $symb=&escape(&symbclean($symb));
                   5860:         }
1.122     albertel 5861:     }
1.188     www      5862:     if (!$namespace) { 
1.620     albertel 5863:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5864:           return ''; 
                   5865:        } 
                   5866:     }
1.620     albertel 5867:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5868:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5869:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5870:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5871: 
1.12      www      5872:     my %returnhash=();
1.800     albertel 5873:     foreach my $line (split(/\&/,$answer)) {
                   5874: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5875:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5876:     }
1.75      www      5877:     my $version;
                   5878:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5879:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5880:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5881:        }
1.75      www      5882:     }
1.13      www      5883:     return %returnhash;
1.34      www      5884: }
                   5885: 
                   5886: # ---------------------------------------------------------- Course Description
1.1118    foxr     5887: #
                   5888: #  
1.34      www      5889: 
                   5890: sub coursedescription {
1.731     albertel 5891:     my ($courseid,$args)=@_;
1.34      www      5892:     $courseid=~s/^\///;
1.49      www      5893:     $courseid=~s/\_/\//g;
1.34      www      5894:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5895:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5896:     my $normalid=$cdomain.'_'.$cnum;
                   5897:     # need to always cache even if we get errors otherwise we keep 
                   5898:     # trying and trying and trying to get the course description.
                   5899:     my %envhash=();
                   5900:     my %returnhash=();
1.731     albertel 5901:     
                   5902:     my $expiretime=600;
                   5903:     if ($env{'request.course.id'} eq $normalid) {
                   5904: 	$expiretime=120;
                   5905:     }
                   5906: 
                   5907:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5908:     if (!$args->{'freshen_cache'}
                   5909: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5910: 	foreach my $key (keys(%env)) {
                   5911: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5912: 	    my ($setting) = $1;
                   5913: 	    $returnhash{$setting} = $env{$key};
                   5914: 	}
                   5915: 	return %returnhash;
                   5916:     }
                   5917: 
1.1118    foxr     5918:     # get the data again
                   5919: 
1.731     albertel 5920:     if (!$args->{'one_time'}) {
                   5921: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5922:     }
1.811     albertel 5923: 
1.34      www      5924:     if ($chome ne 'no_host') {
1.302     albertel 5925:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5926:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5927: 	   my $username = $env{'user.name'}; # Defult username
                   5928: 	   if(defined $args->{'user'}) {
                   5929: 	       $username = $args->{'user'};
                   5930: 	   }
1.129     albertel 5931:            $returnhash{'home'}= $chome;
                   5932: 	   $returnhash{'domain'} = $cdomain;
                   5933: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5934:            if (!defined($returnhash{'type'})) {
                   5935:                $returnhash{'type'} = 'Course';
                   5936:            }
1.130     albertel 5937:            while (my ($name,$value) = each %returnhash) {
1.53      www      5938:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5939:            }
1.270     www      5940:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5941:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5942: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5943:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5944:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5945:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5946:        }
                   5947:     }
1.731     albertel 5948:     if (!$args->{'one_time'}) {
1.949     raeburn  5949: 	&appenv(\%envhash);
1.731     albertel 5950:     }
1.302     albertel 5951:     return %returnhash;
1.461     www      5952: }
                   5953: 
1.1080    raeburn  5954: sub update_released_required {
                   5955:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5956:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5957:         $cid = $env{'request.course.id'};
                   5958:         $cdom = $env{'course.'.$cid.'.domain'};
                   5959:         $cnum = $env{'course.'.$cid.'.num'};
                   5960:         $chome = $env{'course.'.$cid.'.home'};
                   5961:     }
                   5962:     if ($needsrelease) {
                   5963:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5964:         my $needsupdate;
                   5965:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5966:             $needsupdate = 1;
                   5967:         } else {
                   5968:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5969:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5970:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5971:                 $needsupdate = 1;
                   5972:             }
                   5973:         }
                   5974:         if ($needsupdate) {
                   5975:             my %needshash = (
                   5976:                              'internal.releaserequired' => $needsrelease,
                   5977:                             );
                   5978:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5979:             if ($putresult eq 'ok') {
                   5980:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5981:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5982:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5983:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5984:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5985:                 }
                   5986:             }
                   5987:         }
                   5988:     }
                   5989:     return;
                   5990: }
                   5991: 
1.461     www      5992: # -------------------------------------------------See if a user is privileged
                   5993: 
                   5994: sub privileged {
1.1219    raeburn  5995:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5996:     my $now = time;
1.1219    raeburn  5997:     my $roles;
                   5998:     if (ref($possroles) eq 'ARRAY') {
                   5999:         $roles = $possroles; 
                   6000:     } else {
                   6001:         $roles = ['dc','su'];
                   6002:     }
                   6003:     if (ref($possdomains) eq 'ARRAY') {
                   6004:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6005:         foreach my $dom (@{$possdomains}) {
                   6006:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6007:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6008:                 foreach my $role (@{$roles}) {
                   6009:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6010:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6011:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6012:                             return 1 unless (($end && $end < $now) ||
                   6013:                                              ($start && $start > $now));
                   6014:                         }
                   6015:                     }
                   6016:                 }
                   6017:             }
                   6018:         }
                   6019:     } else {
                   6020:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6021:         my $now = time;
1.1170    droeschl 6022: 
1.1275    musolffc 6023:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6024:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6025:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6026:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6027:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6028:             }
1.1219    raeburn  6029:         }
                   6030:     }
                   6031:     return 0;
                   6032: }
1.1170    droeschl 6033: 
1.1219    raeburn  6034: sub privileged_by_domain {
                   6035:     my ($domains,$roles) = @_;
                   6036:     my %privileged = ();
                   6037:     my $cachetime = 60*60*24;
                   6038:     my $now = time;
                   6039:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6040:         return %privileged;
                   6041:     }
                   6042:     foreach my $dom (@{$domains}) {
                   6043:         next if (ref($privileged{$dom}) eq 'HASH');
                   6044:         my $needroles;
                   6045:         foreach my $role (@{$roles}) {
                   6046:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6047:             if (defined($cached)) {
                   6048:                 if (ref($result) eq 'HASH') {
                   6049:                     $privileged{$dom}{$role} = $result;
                   6050:                 }
                   6051:             } else {
                   6052:                 $needroles = 1;
                   6053:             }
                   6054:         }
                   6055:         if ($needroles) {
                   6056:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6057:             $privileged{$dom} = {};
                   6058:             foreach my $server (keys(%dompersonnel)) {
                   6059:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6060:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6061:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6062:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6063:                         next if ($end && $end < $now);
                   6064:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6065:                             $dompersonnel{$server}{$item};
                   6066:                     }
                   6067:                 }
                   6068:             }
                   6069:             if (ref($privileged{$dom}) eq 'HASH') {
                   6070:                 foreach my $role (@{$roles}) {
                   6071:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6072:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6073:                     } else {
                   6074:                         my %hash = ();
                   6075:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6076:                     }
                   6077:                 }
                   6078:             }
                   6079:         }
                   6080:     }
                   6081:     return %privileged;
1.9       www      6082: }
1.1       albertel 6083: 
1.103     harris41 6084: # -------------------------------------------------------- Get user privileges
1.11      www      6085: 
                   6086: sub rolesinit {
1.1169    droeschl 6087:     my ($domain, $username) = @_;
                   6088:     my %userroles = ('user.login.time' => time);
                   6089:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6090: 
                   6091:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6092:     # also, blocking can be triggered by an activating timer
                   6093:     # it's saved in the user's %env.
                   6094:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6095:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6096:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6097:         %timerintchk, %timerintenv);
                   6098: 
1.1162    raeburn  6099:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6100:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6101:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6102:     }
1.1169    droeschl 6103: 
1.1162    raeburn  6104:     foreach my $key (keys(%timerinterval)) {
                   6105:         my ($cid,$rest) = split(/\0/,$key);
                   6106:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6107:     }
1.1169    droeschl 6108: 
1.11      www      6109:     my %allroles=();
1.1162    raeburn  6110:     my %allgroups=();
1.11      www      6111: 
1.1274    raeburn  6112:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6113:         my $role = $rolesdump{$area};
                   6114:         $area =~ s/\_\w\w$//;
                   6115: 
                   6116:         my ($trole, $tend, $tstart, $group_privs);
                   6117: 
                   6118:         if ($role =~ /^cr/) {
                   6119:         # Custom role, defined by a user 
                   6120:         # e.g., user.role.cr/msu/smith/mynewrole
                   6121:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6122:                 $trole = $1;
                   6123:                 ($tend, $tstart) = split('_', $2);
                   6124:             } else {
                   6125:                 $trole = $role;
                   6126:             }
                   6127:         } elsif ($role =~ m|^gr/|) {
                   6128:         # Role of member in a group, defined within a course/community
                   6129:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6130:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6131:             next if $tstart eq '-1';
                   6132:             ($trole, $group_privs) = split(/\//, $trole);
                   6133:             $group_privs = &unescape($group_privs);
                   6134:         } else {
                   6135:         # Just a normal role, defined in roles.tab
                   6136:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6137:         }
                   6138: 
                   6139:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6140:                  $username);
                   6141:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6142: 
                   6143:         # role expired or not available yet?
                   6144:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6145:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6146: 
                   6147:         next if $area eq '' or $trole eq '';
                   6148: 
                   6149:         my $spec = "$trole.$area";
                   6150:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6151: 
                   6152:         if ($trole =~ /^cr\//) {
                   6153:         # Custom role, defined by a user
                   6154:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6155:         } elsif ($trole eq 'gr') {
                   6156:         # Role of a member in a group, defined within a course/community
                   6157:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6158:             next;
                   6159:         } else {
                   6160:         # Normal role, defined in roles.tab
                   6161:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6162:         }
                   6163: 
                   6164:         my $cid = $tdomain.'_'.$trest;
                   6165:         unless ($firstaccchk{$cid}) {
                   6166:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6167:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6168:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6169:                         $coursetimerstarts{$cid}{$item}; 
                   6170:                 }
                   6171:             }
                   6172:             $firstaccchk{$cid} = 1;
                   6173:         }
                   6174:         unless ($timerintchk{$cid}) {
                   6175:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6176:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6177:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6178:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6179:                 }
1.12      www      6180:             }
1.1169    droeschl 6181:             $timerintchk{$cid} = 1;
1.191     harris41 6182:         }
1.11      www      6183:     }
1.1169    droeschl 6184: 
1.1341    raeburn  6185:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6186:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6187:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6188:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6189: 
1.1162    raeburn  6190:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6191: }
                   6192: 
1.567     raeburn  6193: sub set_arearole {
1.1215    raeburn  6194:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6195:     unless ($nolog) {
1.567     raeburn  6196: # log the associated role with the area
1.1215    raeburn  6197:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6198:     }
1.743     albertel 6199:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6200: }
                   6201: 
                   6202: sub custom_roleprivs {
                   6203:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6204:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6205:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6206:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6207:         my ($rdummy,$roledef)=
                   6208:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6209:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6210:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6211:             if (defined($syspriv)) {
1.1043    raeburn  6212:                 if ($trest =~ /^$match_community$/) {
                   6213:                     $syspriv =~ s/bre\&S//; 
                   6214:                 }
1.567     raeburn  6215:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6216:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6217:             }
                   6218:             if ($tdomain ne '') {
                   6219:                 if (defined($dompriv)) {
                   6220:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6221:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6222:                 }
                   6223:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6224:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6225:                         my $rolename = $1;
                   6226:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6227:                     }
1.567     raeburn  6228:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6229:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6230:                 }
                   6231:             }
                   6232:         }
                   6233:     }
                   6234: }
                   6235: 
1.1332    raeburn  6236: sub course_adhocrole_privs {
                   6237:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6238:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6239:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6240:         my (%currprivs,%storeprivs);
                   6241:         foreach my $item (split(/:/,$coursepriv)) {
                   6242:             my ($priv,$restrict) = split(/\&/,$item);
                   6243:             $currprivs{$priv} = $restrict;
                   6244:         }
                   6245:         my (%possadd,%possremove,%full);
                   6246:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6247:             my ($priv,$restrict)=split(/\&/,$item);
                   6248:             $full{$priv} = $restrict;
                   6249:         }
                   6250:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6251:              next if ($item eq '');
                   6252:              my ($rule,$rest) = split(/=/,$item);
                   6253:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6254:              foreach my $priv (split(/:/,$rest)) {
                   6255:                  if ($priv ne '') {
                   6256:                      if ($rule eq 'off') {
                   6257:                          $possremove{$priv} = 1;
                   6258:                      } else {
                   6259:                          $possadd{$priv} = 1;
                   6260:                      }
                   6261:                  }
                   6262:              }
                   6263:          }
                   6264:          foreach my $priv (sort(keys(%full))) {
                   6265:              if (exists($currprivs{$priv})) {
                   6266:                  unless (exists($possremove{$priv})) {
                   6267:                      $storeprivs{$priv} = $currprivs{$priv};
                   6268:                  }
                   6269:              } elsif (exists($possadd{$priv})) {
                   6270:                  $storeprivs{$priv} = $full{$priv};
                   6271:              }
                   6272:          }
                   6273:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6274:      }
                   6275:      return $coursepriv;
                   6276: }
                   6277: 
1.678     raeburn  6278: sub group_roleprivs {
                   6279:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6280:     my $access = 1;
                   6281:     my $now = time;
                   6282:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6283:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6284:     if ($access) {
1.811     albertel 6285:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6286:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6287:     }
                   6288: }
1.567     raeburn  6289: 
                   6290: sub standard_roleprivs {
                   6291:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6292:     if (defined($pr{$trole.':s'})) {
                   6293:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6294:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6295:     }
                   6296:     if ($tdomain ne '') {
                   6297:         if (defined($pr{$trole.':d'})) {
                   6298:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6299:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6300:         }
                   6301:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6302:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6303:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6304:         }
                   6305:     }
                   6306: }
                   6307: 
                   6308: sub set_userprivs {
1.1064    raeburn  6309:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6310:     my $author=0;
                   6311:     my $adv=0;
1.1341    raeburn  6312:     my $rar=0;
1.678     raeburn  6313:     my %grouproles = ();
                   6314:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6315:         my @groupkeys; 
1.1000    raeburn  6316:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6317:             push(@groupkeys,$role);
                   6318:         }
                   6319:         if (ref($groups_roles) eq 'HASH') {
                   6320:             foreach my $key (keys(%{$groups_roles})) {
                   6321:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6322:                     push(@groupkeys,$key);
                   6323:                 }
                   6324:             }
                   6325:         }
                   6326:         if (@groupkeys > 0) {
                   6327:             foreach my $role (@groupkeys) {
                   6328:                 my ($trole,$area,$sec,$extendedarea);
                   6329:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6330:                     $trole = $1;
                   6331:                     $area = $2;
                   6332:                     $sec = $3;
                   6333:                     $extendedarea = $area.$sec;
                   6334:                     if (exists($$allgroups{$area})) {
                   6335:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6336:                             my $spec = $trole.'.'.$extendedarea;
                   6337:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6338:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6339:                         }
1.678     raeburn  6340:                     }
                   6341:                 }
                   6342:             }
                   6343:         }
                   6344:     }
1.800     albertel 6345:     foreach my $group (keys(%grouproles)) {
                   6346:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6347:     }
1.800     albertel 6348:     foreach my $role (keys(%{$allroles})) {
                   6349:         my %thesepriv;
1.941     raeburn  6350:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6351:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6352:             if ($item ne '') {
                   6353:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6354:                 if ($restrictions eq '') {
                   6355:                     $thesepriv{$privilege}='F';
                   6356:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6357:                     $thesepriv{$privilege}.=$restrictions;
                   6358:                 }
                   6359:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6360:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6361:             }
                   6362:         }
                   6363:         my $thesestr='';
1.1104    raeburn  6364:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6365: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6366: 	}
                   6367:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6368:     }
1.1341    raeburn  6369:     return ($author,$adv,$rar);
1.567     raeburn  6370: }
                   6371: 
1.994     raeburn  6372: sub role_status {
1.1104    raeburn  6373:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6374:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6375:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6376:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6377:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6378:             $$where = '/'.$two;
1.994     raeburn  6379:             $$trolecode=$$role.'.'.$$where;
                   6380:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6381:             $$tstatus='is';
1.1104    raeburn  6382:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6383:                 $$tstatus='future';
1.1034    raeburn  6384:                 if ($$tstart<$now) {
                   6385:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6386:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6387:                             my (%allroles,%allgroups,$group_privs,
                   6388:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6389:                             my %userroles = (
                   6390:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6391:                             );
1.1064    raeburn  6392:                             @rolecodes = ('cm'); 
1.1002    raeburn  6393:                             my $spec=$$role.'.'.$$where;
                   6394:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6395:                             if ($$role =~ /^cr\//) {
                   6396:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6397:                                 push(@rolecodes,'cr');
1.1002    raeburn  6398:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6399:                                 push(@rolecodes,$$role);
1.1002    raeburn  6400:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6401:                                                     $env{'user.name'});
1.1064    raeburn  6402:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6403:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6404:                                 $group_privs = &unescape($group_privs);
                   6405:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6406:                                 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  6407:                                 &get_groups_roles($tdomain,$trest,
                   6408:                                                   \%course_roles,\@rolecodes,
                   6409:                                                   \%groups_roles);
1.1002    raeburn  6410:                             } else {
1.1064    raeburn  6411:                                 push(@rolecodes,$$role);
1.1002    raeburn  6412:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6413:                             }
1.1341    raeburn  6414:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6415:                                                                    \%groups_roles);
1.1064    raeburn  6416:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6417:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6418:                         }
                   6419:                     }
1.1034    raeburn  6420:                     $$tstatus = 'is';
1.1002    raeburn  6421:                 }
1.994     raeburn  6422:             }
                   6423:             if ($$tend) {
1.1104    raeburn  6424:                 if ($$tend<$update) {
1.994     raeburn  6425:                     $$tstatus='expired';
                   6426:                 } elsif ($$tend<$now) {
                   6427:                     $$tstatus='will_not';
                   6428:                 }
                   6429:             }
                   6430:         }
                   6431:     }
                   6432: }
                   6433: 
1.1104    raeburn  6434: sub get_groups_roles {
                   6435:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6436:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6437:                   (ref($rolecodes) eq 'ARRAY') && 
                   6438:                   (ref($groups_roles) eq 'HASH')); 
                   6439:     if (keys(%{$cdom_courseroles}) > 0) {
                   6440:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6441:         if ($cdom ne '' && $cnum ne '') {
                   6442:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6443:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6444:                     my $crsrole = $1;
                   6445:                     my $crssec = $2;
                   6446:                     if ($crsrole =~ /^cr/) {
                   6447:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6448:                             push(@{$rolecodes},'cr');
                   6449:                         }
                   6450:                     } else {
                   6451:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6452:                             push(@{$rolecodes},$crsrole);
                   6453:                         }
                   6454:                     }
                   6455:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6456:                     if ($crssec ne '') {
                   6457:                         $rolekey .= "/$crssec";
                   6458:                     }
                   6459:                     $rolekey .= './';
                   6460:                     $groups_roles->{$rolekey} = $rolecodes;
                   6461:                 }
                   6462:             }
                   6463:         }
                   6464:     }
                   6465:     return;
                   6466: }
                   6467: 
                   6468: sub delete_env_groupprivs {
                   6469:     my ($where,$courseroles,$possroles) = @_;
                   6470:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6471:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6472:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6473:         %{$courseroles->{$udom}} =
                   6474:             &get_my_roles('','','userroles',['active'],
                   6475:                           $possroles,[$udom],1);
                   6476:     }
                   6477:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6478:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6479:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6480:             my $area = '/'.$cdom.'/'.$cnum;
                   6481:             my $privkey = "user.priv.$crsrole.$area";
                   6482:             if ($crssec ne '') {
                   6483:                 $privkey .= '/'.$crssec;
                   6484:             }
                   6485:             $privkey .= ".$area/$group";
                   6486:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6487:         }
                   6488:     }
                   6489:     return;
                   6490: }
                   6491: 
1.994     raeburn  6492: sub check_adhoc_privs {
1.1329    raeburn  6493:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6494:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6495:     if ($sec) {
                   6496:         $cckey .= '/'.$sec;
                   6497:     } 
1.1185    raeburn  6498:     my $setprivs;
1.994     raeburn  6499:     if ($env{$cckey}) {
                   6500:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6501:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6502:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6503:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6504:             $setprivs = 1;
1.994     raeburn  6505:         }
                   6506:     } else {
1.1330    raeburn  6507:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6508:         $setprivs = 1;
1.994     raeburn  6509:     }
1.1185    raeburn  6510:     return $setprivs;
1.994     raeburn  6511: }
                   6512: 
                   6513: sub set_adhoc_privileges {
1.1326    raeburn  6514: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6515:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6516:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6517:     if ($sec ne '') {
                   6518:         $area .= '/'.$sec;
                   6519:     }
1.994     raeburn  6520:     my $spec = $role.'.'.$area;
                   6521:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6522:                                   $env{'user.name'},1);
1.1326    raeburn  6523:     my %rolehash = ();
1.1332    raeburn  6524:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6525:         my $rolename = $1;
1.1326    raeburn  6526:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6527:         my %domdef = &get_domain_defaults($dcdom);
                   6528:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6529:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6530:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6531:             }
                   6532:         }
1.1326    raeburn  6533:     } else {
                   6534:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6535:     }
1.1341    raeburn  6536:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6537:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6538:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6539:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6540:         &appenv( {'request.role'        => $spec,
                   6541:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6542:                   'request.course.sec'  => $sec,
1.1088    raeburn  6543:                  }
                   6544:                );
                   6545:         my $tadv=0;
                   6546:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6547:         &appenv({'request.role.adv'    => $tadv});
                   6548:     }
1.994     raeburn  6549: }
                   6550: 
1.12      www      6551: # --------------------------------------------------------------- get interface
                   6552: 
                   6553: sub get {
1.131     albertel 6554:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6555:    my $items='';
1.800     albertel 6556:    foreach my $item (@$storearr) {
                   6557:        $items.=&escape($item).'&';
1.191     harris41 6558:    }
1.12      www      6559:    $items=~s/\&$//;
1.620     albertel 6560:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6561:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6562:    my $uhome=&homeserver($uname,$udomain);
                   6563: 
1.133     albertel 6564:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6565:    my @pairs=split(/\&/,$rep);
1.273     albertel 6566:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6567:      return @pairs;
                   6568:    }
1.15      www      6569:    my %returnhash=();
1.42      www      6570:    my $i=0;
1.800     albertel 6571:    foreach my $item (@$storearr) {
                   6572:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6573:       $i++;
1.191     harris41 6574:    }
1.15      www      6575:    return %returnhash;
1.27      www      6576: }
                   6577: 
                   6578: # --------------------------------------------------------------- del interface
                   6579: 
                   6580: sub del {
1.133     albertel 6581:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6582:    my $items='';
1.800     albertel 6583:    foreach my $item (@$storearr) {
                   6584:        $items.=&escape($item).'&';
1.191     harris41 6585:    }
1.984     neumanie 6586: 
1.27      www      6587:    $items=~s/\&$//;
1.620     albertel 6588:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6589:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6590:    my $uhome=&homeserver($uname,$udomain);
                   6591:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6592: }
                   6593: 
                   6594: # -------------------------------------------------------------- dump interface
                   6595: 
1.1180    droeschl 6596: sub unserialize {
                   6597:     my ($rep, $escapedkeys) = @_;
                   6598: 
                   6599:     return {} if $rep =~ /^error/;
                   6600: 
                   6601:     my %returnhash=();
1.1252    raeburn  6602: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6603: 	    my ($key, $value) = split(/=/, $item, 2);
                   6604: 	    $key = unescape($key) unless $escapedkeys;
                   6605: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6606: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6607: 	}
                   6608:     #return %returnhash;
                   6609:     return \%returnhash;
                   6610: }        
                   6611: 
                   6612: # see Lond::dump_with_regexp
                   6613: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6614: sub dump {
1.1180    droeschl 6615:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6616:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6617:     if (!$uname) { $uname=$env{'user.name'}; }
                   6618:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6619: 
1.1266    raeburn  6620:     if ($regexp) {
                   6621:         $regexp=&escape($regexp);
                   6622:     } else {
                   6623:         $regexp='.';
                   6624:     }
1.1180    droeschl 6625:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6626:         # user is hosted on this machine
1.1266    raeburn  6627:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6628:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6629:         return %{unserialize($reply, $escapedkeys)};
                   6630:     }
1.1166    raeburn  6631:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6632:     my @pairs=split(/\&/,$rep);
                   6633:     my %returnhash=();
1.1098    foxr     6634:     if (!($rep =~ /^error/ )) {
                   6635: 	foreach my $item (@pairs) {
                   6636: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6637:         $key = unescape($key) unless $escapedkeys;
                   6638:         #$key = &unescape($key);
1.1098    foxr     6639: 	    next if ($key =~ /^error: 2 /);
                   6640: 	    $returnhash{$key}=&thaw_unescape($value);
                   6641: 	}
1.755     albertel 6642:     }
                   6643:     return %returnhash;
1.407     www      6644: }
                   6645: 
1.1098    foxr     6646: 
1.717     albertel 6647: # --------------------------------------------------------- dumpstore interface
                   6648: 
                   6649: sub dumpstore {
                   6650:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6651:    # same as dump but keys must be escaped. They may contain colon separated
                   6652:    # lists of values that may themself contain colons (e.g. symbs).
                   6653:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6654: }
                   6655: 
1.407     www      6656: # -------------------------------------------------------------- keys interface
                   6657: 
                   6658: sub getkeys {
                   6659:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6660:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6661:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6662:    my $uhome=&homeserver($uname,$udomain);
                   6663:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6664:    my @keyarray=();
1.800     albertel 6665:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6666:       next if ($key =~ /^error: 2 /);
1.800     albertel 6667:       push(@keyarray,&unescape($key));
1.407     www      6668:    }
                   6669:    return @keyarray;
1.318     matthew  6670: }
                   6671: 
1.319     matthew  6672: # --------------------------------------------------------------- currentdump
                   6673: sub currentdump {
1.328     matthew  6674:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6675:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6676:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6677:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6678:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6679:    my $rep;
                   6680: 
                   6681:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6682:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6683:                    $courseid)));
                   6684:    } else {
                   6685:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6686:    }
                   6687: 
1.318     matthew  6688:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6689:    #
1.318     matthew  6690:    my %returnhash=();
1.319     matthew  6691:    #
1.1343    raeburn  6692:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6693:        # an old lond will not know currentdump
                   6694:        # Do a dump and make it look like a currentdump
1.822     albertel 6695:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6696:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6697:        my %hash = @tmp;
                   6698:        @tmp=();
1.424     matthew  6699:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6700:    } else {
                   6701:        my @pairs=split(/\&/,$rep);
1.800     albertel 6702:        foreach my $pair (@pairs) {
                   6703:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6704:            my ($symb,$param) = split(/:/,$key);
                   6705:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6706:                                                         &thaw_unescape($value);
1.319     matthew  6707:        }
1.191     harris41 6708:    }
1.12      www      6709:    return %returnhash;
1.424     matthew  6710: }
                   6711: 
                   6712: sub convert_dump_to_currentdump{
                   6713:     my %hash = %{shift()};
                   6714:     my %returnhash;
                   6715:     # Code ripped from lond, essentially.  The only difference
                   6716:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6717:     # we might run in to problems with parameter names =~ /^v\./
                   6718:     while (my ($key,$value) = each(%hash)) {
                   6719:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6720: 	$symb  = &unescape($symb);
                   6721: 	$param = &unescape($param);
1.424     matthew  6722:         next if ($v eq 'version' || $symb eq 'keys');
                   6723:         next if (exists($returnhash{$symb}) &&
                   6724:                  exists($returnhash{$symb}->{$param}) &&
                   6725:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6726:         $returnhash{$symb}->{$param}=$value;
                   6727:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6728:     }
                   6729:     #
                   6730:     # Remove all of the keys in the hashes which keep track of
                   6731:     # the version of the parameter.
                   6732:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6733:         # use a foreach because we are going to delete from the hash.
                   6734:         foreach my $key (keys(%$param_hash)) {
                   6735:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6736:         }
                   6737:     }
                   6738:     return \%returnhash;
1.12      www      6739: }
                   6740: 
1.627     albertel 6741: # ------------------------------------------------------ critical inc interface
                   6742: 
                   6743: sub cinc {
                   6744:     return &inc(@_,'critical');
                   6745: }
                   6746: 
1.449     matthew  6747: # --------------------------------------------------------------- inc interface
                   6748: 
                   6749: sub inc {
1.627     albertel 6750:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6751:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6752:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6753:     my $uhome=&homeserver($uname,$udomain);
                   6754:     my $items='';
                   6755:     if (! ref($store)) {
                   6756:         # got a single value, so use that instead
                   6757:         $items = &escape($store).'=&';
                   6758:     } elsif (ref($store) eq 'SCALAR') {
                   6759:         $items = &escape($$store).'=&';        
                   6760:     } elsif (ref($store) eq 'ARRAY') {
                   6761:         $items = join('=&',map {&escape($_);} @{$store});
                   6762:     } elsif (ref($store) eq 'HASH') {
                   6763:         while (my($key,$value) = each(%{$store})) {
                   6764:             $items.= &escape($key).'='.&escape($value).'&';
                   6765:         }
                   6766:     }
                   6767:     $items=~s/\&$//;
1.627     albertel 6768:     if ($critical) {
                   6769: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6770:     } else {
                   6771: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6772:     }
1.449     matthew  6773: }
                   6774: 
1.12      www      6775: # --------------------------------------------------------------- put interface
                   6776: 
                   6777: sub put {
1.134     albertel 6778:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6779:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6780:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6781:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6782:    my $items='';
1.800     albertel 6783:    foreach my $item (keys(%$storehash)) {
                   6784:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6785:    }
1.12      www      6786:    $items=~s/\&$//;
1.134     albertel 6787:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6788: }
                   6789: 
1.631     albertel 6790: # ------------------------------------------------------------ newput interface
                   6791: 
                   6792: sub newput {
                   6793:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6794:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6795:    if (!$uname) { $uname=$env{'user.name'}; }
                   6796:    my $uhome=&homeserver($uname,$udomain);
                   6797:    my $items='';
                   6798:    foreach my $key (keys(%$storehash)) {
                   6799:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6800:    }
                   6801:    $items=~s/\&$//;
                   6802:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6803: }
                   6804: 
                   6805: # ---------------------------------------------------------  putstore interface
                   6806: 
1.524     raeburn  6807: sub putstore {
1.1269    raeburn  6808:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6809:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6810:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6811:    my $uhome=&homeserver($uname,$udomain);
                   6812:    my $items='';
1.715     albertel 6813:    foreach my $key (keys(%$storehash)) {
                   6814:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6815:    }
1.715     albertel 6816:    $items=~s/\&$//;
1.716     albertel 6817:    my $esc_symb=&escape($symb);
                   6818:    my $esc_v=&escape($version);
1.715     albertel 6819:    my $reply =
1.716     albertel 6820:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6821: 	      $uhome);
1.1269    raeburn  6822:    if (($tolog) && ($reply eq 'ok')) {
                   6823:        my $namevalue='';
                   6824:        foreach my $key (keys(%{$storehash})) {
                   6825:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6826:        }
                   6827:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6828:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6829:                      '&version='.$esc_v.
                   6830:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6831:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6832:    }
1.715     albertel 6833:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6834:        # gfall back to way things use to be done
1.715     albertel 6835:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6836: 			    $uname);
1.524     raeburn  6837:    }
1.715     albertel 6838:    return $reply;
                   6839: }
                   6840: 
                   6841: sub old_putstore {
1.716     albertel 6842:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6843:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6844:     if (!$uname) { $uname=$env{'user.name'}; }
                   6845:     my $uhome=&homeserver($uname,$udomain);
                   6846:     my %newstorehash;
1.800     albertel 6847:     foreach my $item (keys(%$storehash)) {
                   6848: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6849: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6850:     }
                   6851:     my $items='';
                   6852:     my %allitems = ();
1.800     albertel 6853:     foreach my $item (keys(%newstorehash)) {
                   6854: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6855: 	    my $key = $1.':keys:'.$2;
                   6856: 	    $allitems{$key} .= $3.':';
                   6857: 	}
1.800     albertel 6858: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6859:     }
1.800     albertel 6860:     foreach my $item (keys(%allitems)) {
                   6861: 	$allitems{$item} =~ s/\:$//;
                   6862: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6863:     }
                   6864:     $items=~s/\&$//;
                   6865:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6866: }
                   6867: 
1.47      www      6868: # ------------------------------------------------------ critical put interface
                   6869: 
                   6870: sub cput {
1.134     albertel 6871:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6873:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6874:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6875:    my $items='';
1.800     albertel 6876:    foreach my $item (keys(%$storehash)) {
                   6877:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6878:    }
1.47      www      6879:    $items=~s/\&$//;
1.134     albertel 6880:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6881: }
                   6882: 
                   6883: # -------------------------------------------------------------- eget interface
                   6884: 
                   6885: sub eget {
1.133     albertel 6886:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6887:    my $items='';
1.800     albertel 6888:    foreach my $item (@$storearr) {
                   6889:        $items.=&escape($item).'&';
1.191     harris41 6890:    }
1.12      www      6891:    $items=~s/\&$//;
1.620     albertel 6892:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6893:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6894:    my $uhome=&homeserver($uname,$udomain);
                   6895:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6896:    my @pairs=split(/\&/,$rep);
                   6897:    my %returnhash=();
1.42      www      6898:    my $i=0;
1.800     albertel 6899:    foreach my $item (@$storearr) {
                   6900:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6901:       $i++;
1.191     harris41 6902:    }
1.12      www      6903:    return %returnhash;
                   6904: }
                   6905: 
1.667     albertel 6906: # ------------------------------------------------------------ tmpput interface
                   6907: sub tmpput {
1.802     raeburn  6908:     my ($storehash,$server,$context)=@_;
1.667     albertel 6909:     my $items='';
1.800     albertel 6910:     foreach my $item (keys(%$storehash)) {
                   6911: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6912:     }
                   6913:     $items=~s/\&$//;
1.802     raeburn  6914:     if (defined($context)) {
                   6915:         $items .= ':'.&escape($context);
                   6916:     }
1.667     albertel 6917:     return &reply("tmpput:$items",$server);
                   6918: }
                   6919: 
                   6920: # ------------------------------------------------------------ tmpget interface
                   6921: sub tmpget {
1.688     albertel 6922:     my ($token,$server)=@_;
                   6923:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6924:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6925:     my %returnhash;
1.1328    raeburn  6926:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6927:         return %returnhash;
                   6928:     }
1.667     albertel 6929:     foreach my $item (split(/\&/,$rep)) {
                   6930: 	my ($key,$value)=split(/=/,$item);
                   6931: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6932:     }
                   6933:     return %returnhash;
                   6934: }
                   6935: 
1.1113    raeburn  6936: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6937: sub tmpdel {
                   6938:     my ($token,$server)=@_;
                   6939:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6940:     return &reply("tmpdel:$token",$server);
                   6941: }
                   6942: 
1.1198    raeburn  6943: # ------------------------------------------------------------ get_timebased_id 
                   6944: 
                   6945: sub get_timebased_id {
                   6946:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6947:         $maxtries) = @_;
                   6948:     my ($newid,$error,$dellock);
                   6949:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6950:         return ('','ok','invalid call to get suffix');
                   6951:     }
                   6952: 
                   6953: # set defaults for any optional args for which values were not supplied
                   6954:     if ($who eq '') {
                   6955:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6956:     }
                   6957:     if (!$locktries) {
                   6958:         $locktries = 3;
                   6959:     }
                   6960:     if (!$maxtries) {
                   6961:         $maxtries = 10;
                   6962:     }
                   6963:     
                   6964:     if (($cdom eq '') || ($cnum eq '')) {
                   6965:         if ($env{'request.course.id'}) {
                   6966:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6967:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6968:         }
                   6969:         if (($cdom eq '') || ($cnum eq '')) {
                   6970:             return ('','ok','call to get suffix not in course context');
                   6971:         }
                   6972:     }
                   6973: 
                   6974: # construct locking item
                   6975:     my $lockhash = {
                   6976:                       $prefix."\0".'locked_'.$keyid => $who,
                   6977:                    };
                   6978:     my $tries = 0;
                   6979: 
                   6980: # attempt to get lock on nohist_$namespace file
                   6981:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6982:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6983:         $tries ++;
                   6984:         sleep 1;
                   6985:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6986:     }
                   6987: 
                   6988: # attempt to get unique identifier, based on current timestamp
                   6989:     if ($gotlock eq 'ok') {
                   6990:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6991:         my $id = time;
                   6992:         $newid = $id;
1.1268    raeburn  6993:         if ($idtype eq 'addcode') {
                   6994:             $newid .= &sixnum_code();
                   6995:         }
1.1198    raeburn  6996:         my $idtries = 0;
                   6997:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6998:             if ($idtype eq 'concat') {
                   6999:                 $newid = $id.$idtries;
1.1268    raeburn  7000:             } elsif ($idtype eq 'addcode') {
                   7001:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7002:             } else {
                   7003:                 $newid ++;
                   7004:             }
                   7005:             $idtries ++;
                   7006:         }
                   7007:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7008:             my %new_item =  (
                   7009:                               $prefix."\0".$newid => $who,
                   7010:                             );
                   7011:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7012:                                                  $cdom,$cnum);
                   7013:             if ($putresult ne 'ok') {
                   7014:                 undef($newid);
                   7015:                 $error = 'error saving new item: '.$putresult;
                   7016:             }
                   7017:         } else {
1.1268    raeburn  7018:              undef($newid);
1.1198    raeburn  7019:              $error = ('error: no unique suffix available for the new item ');
                   7020:         }
                   7021: #  remove lock
                   7022:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7023:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7024:     } else {
                   7025:         $error = "error: could not obtain lockfile\n";
                   7026:         $dellock = 'ok';
1.1276    raeburn  7027:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7028:             $dellock = 'nolock';
                   7029:         }
1.1198    raeburn  7030:     }
                   7031:     return ($newid,$dellock,$error);
                   7032: }
                   7033: 
1.1268    raeburn  7034: sub sixnum_code {
                   7035:     my $code;
                   7036:     for (0..6) {
                   7037:         $code .= int( rand(9) );
                   7038:     }
                   7039:     return $code;
                   7040: }
                   7041: 
1.765     albertel 7042: # -------------------------------------------------- portfolio access checking
                   7043: 
                   7044: sub portfolio_access {
1.1270    raeburn  7045:     my ($requrl,$clientip) = @_;
1.765     albertel 7046:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7047:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7048:     if ($result) {
                   7049:         my %setters;
                   7050:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7051:             my ($startblock,$endblock) =
                   7052:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7053:             if ($startblock && $endblock) {
                   7054:                 return 'B';
                   7055:             }
                   7056:         } else {
                   7057:             my ($startblock,$endblock) =
                   7058:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7059:             if ($startblock && $endblock) {
                   7060:                 return 'B';
                   7061:             }
                   7062:         }
                   7063:     }
1.765     albertel 7064:     if ($result eq 'ok') {
1.766     albertel 7065:        return 'F';
1.765     albertel 7066:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7067:        return 'A';
1.765     albertel 7068:     }
1.766     albertel 7069:     return '';
1.765     albertel 7070: }
                   7071: 
                   7072: sub get_portfolio_access {
1.1270    raeburn  7073:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7074: 
                   7075:     if (!ref($access_hash)) {
                   7076: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7077: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7078: 						   $file_name);
                   7079: 	$access_hash = $access_controls{$file_name};
                   7080:     }
                   7081: 
1.1270    raeburn  7082:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7083:     my $now = time;
                   7084:     if (ref($access_hash) eq 'HASH') {
                   7085:         foreach my $key (keys(%{$access_hash})) {
                   7086:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7087:             if ($start > $now) {
                   7088:                 next;
                   7089:             }
                   7090:             if ($end && $end<$now) {
                   7091:                 next;
                   7092:             }
                   7093:             if ($scope eq 'public') {
                   7094:                 $public = $key;
                   7095:                 last;
                   7096:             } elsif ($scope eq 'guest') {
                   7097:                 $guest = $key;
                   7098:             } elsif ($scope eq 'domains') {
                   7099:                 push(@domains,$key);
                   7100:             } elsif ($scope eq 'users') {
                   7101:                 push(@users,$key);
                   7102:             } elsif ($scope eq 'course') {
                   7103:                 push(@courses,$key);
                   7104:             } elsif ($scope eq 'group') {
                   7105:                 push(@groups,$key);
1.1270    raeburn  7106:             } elsif ($scope eq 'ip') {
                   7107:                 push(@ips,$key);
1.765     albertel 7108:             }
                   7109:         }
                   7110:         if ($public) {
                   7111:             return 'ok';
1.1270    raeburn  7112:         } elsif (@ips > 0) {
                   7113:             my $allowed;
                   7114:             foreach my $ipkey (@ips) {
                   7115:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7116:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7117:                         $allowed = 1;
                   7118:                         last; 
                   7119:                     }
                   7120:                 }
                   7121:             }
                   7122:             if ($allowed) {
                   7123:                 return 'ok';
                   7124:             }
1.765     albertel 7125:         }
                   7126:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7127:             if ($guest) {
                   7128:                 return $guest;
                   7129:             }
                   7130:         } else {
                   7131:             if (@domains > 0) {
                   7132:                 foreach my $domkey (@domains) {
                   7133:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7134:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7135:                             return 'ok';
                   7136:                         }
                   7137:                     }
                   7138:                 }
                   7139:             }
                   7140:             if (@users > 0) {
                   7141:                 foreach my $userkey (@users) {
1.865     raeburn  7142:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7143:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7144:                             if (ref($item) eq 'HASH') {
                   7145:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7146:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7147:                                     return 'ok';
                   7148:                                 }
                   7149:                             }
                   7150:                         }
                   7151:                     } 
1.765     albertel 7152:                 }
                   7153:             }
                   7154:             my %roleshash;
                   7155:             my @courses_and_groups = @courses;
                   7156:             push(@courses_and_groups,@groups); 
                   7157:             if (@courses_and_groups > 0) {
                   7158:                 my (%allgroups,%allroles); 
                   7159:                 my ($start,$end,$role,$sec,$group);
                   7160:                 foreach my $envkey (%env) {
1.1060    raeburn  7161:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7162:                         my $cid = $2.'_'.$3; 
                   7163:                         if ($1 eq 'gr') {
                   7164:                             $group = $4;
                   7165:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7166:                         } else {
                   7167:                             if ($4 eq '') {
                   7168:                                 $sec = 'none';
                   7169:                             } else {
                   7170:                                 $sec = $4;
                   7171:                             }
                   7172:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7173:                         }
1.811     albertel 7174:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7175:                         my $cid = $2.'_'.$3;
                   7176:                         if ($4 eq '') {
                   7177:                             $sec = 'none';
                   7178:                         } else {
                   7179:                             $sec = $4;
                   7180:                         }
                   7181:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7182:                     }
                   7183:                 }
                   7184:                 if (keys(%allroles) == 0) {
                   7185:                     return;
                   7186:                 }
                   7187:                 foreach my $key (@courses_and_groups) {
                   7188:                     my %content = %{$$access_hash{$key}};
                   7189:                     my $cnum = $content{'number'};
                   7190:                     my $cdom = $content{'domain'};
                   7191:                     my $cid = $cdom.'_'.$cnum;
                   7192:                     if (!exists($allroles{$cid})) {
                   7193:                         next;
                   7194:                     }    
                   7195:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7196:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7197:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7198:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7199:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7200:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7201:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7202:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7203:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7204:                                         if (grep/^all$/,@sections) {
                   7205:                                             return 'ok';
                   7206:                                         } else {
                   7207:                                             if (grep/^$sec$/,@sections) {
                   7208:                                                 return 'ok';
                   7209:                                             }
                   7210:                                         }
                   7211:                                     }
                   7212:                                 }
                   7213:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7214:                                     if (grep/^none$/,@groups) {
                   7215:                                         return 'ok';
                   7216:                                     }
                   7217:                                 } else {
                   7218:                                     if (grep/^all$/,@groups) {
                   7219:                                         return 'ok';
                   7220:                                     } 
                   7221:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7222:                                         if (grep/^$group$/,@groups) {
                   7223:                                             return 'ok';
                   7224:                                         }
                   7225:                                     }
                   7226:                                 } 
                   7227:                             }
                   7228:                         }
                   7229:                     }
                   7230:                 }
                   7231:             }
                   7232:             if ($guest) {
                   7233:                 return $guest;
                   7234:             }
                   7235:         }
                   7236:     }
                   7237:     return;
                   7238: }
                   7239: 
                   7240: sub course_group_datechecker {
                   7241:     my ($dates,$now,$status) = @_;
                   7242:     my ($start,$end) = split(/\./,$dates);
                   7243:     if (!$start && !$end) {
                   7244:         return 'ok';
                   7245:     }
                   7246:     if (grep/^active$/,@{$status}) {
                   7247:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7248:             return 'ok';
                   7249:         }
                   7250:     }
                   7251:     if (grep/^previous$/,@{$status}) {
                   7252:         if ($end > $now ) {
                   7253:             return 'ok';
                   7254:         }
                   7255:     }
                   7256:     if (grep/^future$/,@{$status}) {
                   7257:         if ($start > $now) {
                   7258:             return 'ok';
                   7259:         }
                   7260:     }
                   7261:     return; 
                   7262: }
                   7263: 
                   7264: sub parse_portfolio_url {
                   7265:     my ($url) = @_;
                   7266: 
                   7267:     my ($type,$udom,$unum,$group,$file_name);
                   7268:     
1.823     albertel 7269:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7270: 	$type = 1;
                   7271:         $udom = $1;
                   7272:         $unum = $2;
                   7273:         $file_name = $3;
1.823     albertel 7274:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7275: 	$type = 2;
                   7276:         $udom = $1;
                   7277:         $unum = $2;
                   7278:         $group = $3;
                   7279:         $file_name = $3.'/'.$4;
                   7280:     }
                   7281:     if (wantarray) {
                   7282: 	return ($type,$udom,$unum,$file_name,$group);
                   7283:     }
                   7284:     return $type;
                   7285: }
                   7286: 
                   7287: sub is_portfolio_url {
                   7288:     my ($url) = @_;
                   7289:     return scalar(&parse_portfolio_url($url));
                   7290: }
                   7291: 
1.798     raeburn  7292: sub is_portfolio_file {
                   7293:     my ($file) = @_;
1.820     raeburn  7294:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7295:         return 1;
                   7296:     }
                   7297:     return;
                   7298: }
                   7299: 
1.976     raeburn  7300: sub usertools_access {
1.1084    raeburn  7301:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7302:     my ($access,%tools);
                   7303:     if ($context eq '') {
                   7304:         $context = 'tools';
                   7305:     }
                   7306:     if ($context eq 'requestcourses') {
                   7307:         %tools = (
                   7308:                       official   => 1,
                   7309:                       unofficial => 1,
1.1006    raeburn  7310:                       community  => 1,
1.1246    raeburn  7311:                       textbook   => 1,
1.1305    raeburn  7312:                       placement  => 1,
1.1368    raeburn  7313:                       lti        => 1,
1.985     raeburn  7314:                  );
1.1183    raeburn  7315:     } elsif ($context eq 'requestauthor') {
                   7316:         %tools = (
                   7317:                       requestauthor => 1,
                   7318:                  );
1.985     raeburn  7319:     } else {
                   7320:         %tools = (
                   7321:                       aboutme   => 1,
                   7322:                       blog      => 1,
1.1177    raeburn  7323:                       webdav    => 1,
1.985     raeburn  7324:                       portfolio => 1,
                   7325:                  );
                   7326:     }
1.976     raeburn  7327:     return if (!defined($tools{$tool}));
                   7328: 
1.1242    raeburn  7329:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7330:         $udom = $env{'user.domain'};
                   7331:         $uname = $env{'user.name'};
                   7332:     }
                   7333: 
1.978     raeburn  7334:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7335:         if ($action ne 'reload') {
1.985     raeburn  7336:             if ($context eq 'requestcourses') {
                   7337:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7338:             } elsif ($context eq 'requestauthor') {
                   7339:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7340:             } else {
                   7341:                 return $env{'environment.availabletools.'.$tool};
                   7342:             }
                   7343:         }
1.976     raeburn  7344:     }
                   7345: 
1.1183    raeburn  7346:     my ($toolstatus,$inststatus,$envkey);
                   7347:     if ($context eq 'requestauthor') {
                   7348:         $envkey = $context; 
                   7349:     } else {
                   7350:         $envkey = $context.'.'.$tool;
                   7351:     }
1.976     raeburn  7352: 
1.985     raeburn  7353:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7354:          ($action ne 'reload')) {
1.1183    raeburn  7355:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7356:         $inststatus = $env{'environment.inststatus'};
                   7357:     } else {
1.1084    raeburn  7358:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7359:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7360:             $inststatus = $userenvref->{'inststatus'};
                   7361:         } else {
1.1183    raeburn  7362:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7363:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7364:             $inststatus = $userenv{'inststatus'};
                   7365:         }
1.976     raeburn  7366:     }
                   7367: 
                   7368:     if ($toolstatus ne '') {
                   7369:         if ($toolstatus) {
                   7370:             $access = 1;
                   7371:         } else {
                   7372:             $access = 0;
                   7373:         }
                   7374:         return $access;
                   7375:     }
                   7376: 
1.1084    raeburn  7377:     my ($is_adv,%domdef);
                   7378:     if (ref($is_advref) eq 'HASH') {
                   7379:         $is_adv = $is_advref->{'is_adv'};
                   7380:     } else {
                   7381:         $is_adv = &is_advanced_user($udom,$uname);
                   7382:     }
                   7383:     if (ref($domdefref) eq 'HASH') {
                   7384:         %domdef = %{$domdefref};
                   7385:     } else {
                   7386:         %domdef = &get_domain_defaults($udom);
                   7387:     }
1.976     raeburn  7388:     if (ref($domdef{$tool}) eq 'HASH') {
                   7389:         if ($is_adv) {
                   7390:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7391:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7392:                     $access = 1;
                   7393:                 } else {
                   7394:                     $access = 0;
                   7395:                 }
                   7396:                 return $access;
                   7397:             }
                   7398:         }
                   7399:         if ($inststatus ne '') {
                   7400:             my ($hasaccess,$hasnoaccess);
                   7401:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7402:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7403:                     if ($domdef{$tool}{$affiliation}) {
                   7404:                         $hasaccess = 1;
                   7405:                     } else {
                   7406:                         $hasnoaccess = 1;
                   7407:                     }
                   7408:                 }
                   7409:             }
                   7410:             if ($hasaccess || $hasnoaccess) {
                   7411:                 if ($hasaccess) {
                   7412:                     $access = 1;
                   7413:                 } elsif ($hasnoaccess) {
                   7414:                     $access = 0; 
                   7415:                 }
                   7416:                 return $access;
                   7417:             }
                   7418:         } else {
                   7419:             if ($domdef{$tool}{'default'} ne '') {
                   7420:                 if ($domdef{$tool}{'default'}) {
                   7421:                     $access = 1;
                   7422:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7423:                     $access = 0;
                   7424:                 }
                   7425:                 return $access;
                   7426:             }
                   7427:         }
                   7428:     } else {
1.1177    raeburn  7429:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7430:             $access = 1;
                   7431:         } else {
                   7432:             $access = 0;
                   7433:         }
1.976     raeburn  7434:         return $access;
                   7435:     }
                   7436: }
                   7437: 
1.1050    raeburn  7438: sub is_course_owner {
                   7439:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7440:     if (($udom eq '') || ($uname eq '')) {
                   7441:         $udom = $env{'user.domain'};
                   7442:         $uname = $env{'user.name'};
                   7443:     }
                   7444:     unless (($udom eq '') || ($uname eq '')) {
                   7445:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7446:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7447:                 return 1;
                   7448:             } else {
                   7449:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7450:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7451:                     return 1;
                   7452:                 }
                   7453:             }
                   7454:         }
                   7455:     }
                   7456:     return;
                   7457: }
                   7458: 
1.976     raeburn  7459: sub is_advanced_user {
                   7460:     my ($udom,$uname) = @_;
1.1085    raeburn  7461:     if ($udom ne '' && $uname ne '') {
                   7462:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7463:             if (wantarray) {
                   7464:                 return ($env{'user.adv'},$env{'user.author'});
                   7465:             } else {
                   7466:                 return $env{'user.adv'};
                   7467:             }
1.1085    raeburn  7468:         }
                   7469:     }
1.976     raeburn  7470:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7471:     my %allroles;
1.1128    raeburn  7472:     my ($is_adv,$is_author);
1.976     raeburn  7473:     foreach my $role (keys(%roleshash)) {
                   7474:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7475:         my $area = '/'.$tdomain.'/'.$trest;
                   7476:         if ($sec ne '') {
                   7477:             $area .= '/'.$sec;
                   7478:         }
                   7479:         if (($area ne '') && ($trole ne '')) {
                   7480:             my $spec=$trole.'.'.$area;
                   7481:             if ($trole =~ /^cr\//) {
                   7482:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7483:             } elsif ($trole ne 'gr') {
                   7484:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7485:             }
1.1128    raeburn  7486:             if ($trole eq 'au') {
                   7487:                 $is_author = 1;
                   7488:             }
1.976     raeburn  7489:         }
                   7490:     }
                   7491:     foreach my $role (keys(%allroles)) {
                   7492:         last if ($is_adv);
                   7493:         foreach my $item (split(/:/,$allroles{$role})) {
                   7494:             if ($item ne '') {
                   7495:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7496:                 if ($privilege eq 'adv') {
                   7497:                     $is_adv = 1;
                   7498:                     last;
                   7499:                 }
                   7500:             }
                   7501:         }
                   7502:     }
1.1128    raeburn  7503:     if (wantarray) {
                   7504:         return ($is_adv,$is_author);
                   7505:     }
1.976     raeburn  7506:     return $is_adv;
                   7507: }
1.798     raeburn  7508: 
1.1035    raeburn  7509: sub check_can_request {
1.1368    raeburn  7510:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7511:     my $canreq = 0;
1.1368    raeburn  7512:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7513:         $uname = $env{'user.name'};
                   7514:         $udom = $env{'user.domain'};
                   7515:     }
1.1035    raeburn  7516:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7517:     my @options = ('approval','validate','autolimit');
                   7518:     my $optregex = join('|',@options);
                   7519:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7520:         foreach my $type (@{$types}) {
1.1368    raeburn  7521:             if (&usertools_access($uname,$udom,$type,undef,
                   7522:                                   'requestcourses')) {
1.1035    raeburn  7523:                 $canreq ++;
1.1036    raeburn  7524:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7525:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7526:                 }
1.1368    raeburn  7527:                 if ($dom eq $udom) {
1.1035    raeburn  7528:                     $can_request->{$type} = 1;
                   7529:                 }
                   7530:             }
1.1368    raeburn  7531:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7532:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7533:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7534:                 if (@curr > 0) {
1.1036    raeburn  7535:                     foreach my $item (@curr) {
                   7536:                         if (ref($request_domains) eq 'HASH') {
                   7537:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7538:                             if ($otherdom ne '') {
                   7539:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7540:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7541:                                         push(@{$request_domains->{$type}},$otherdom);
                   7542:                                     }
                   7543:                                 } else {
                   7544:                                     push(@{$request_domains->{$type}},$otherdom);
                   7545:                                 }
                   7546:                             }
                   7547:                         }
                   7548:                     }
1.1368    raeburn  7549:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7550:                         $canreq ++;
1.1035    raeburn  7551:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7552:                             $can_request->{$type} = 1;
                   7553:                         }
                   7554:                     }
                   7555:                 }
                   7556:             }
                   7557:         }
                   7558:     }
                   7559:     return $canreq;
                   7560: }
                   7561: 
1.341     www      7562: # ---------------------------------------------- Custom access rule evaluation
                   7563: 
                   7564: sub customaccess {
                   7565:     my ($priv,$uri)=@_;
1.807     albertel 7566:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7567:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7568:     $udom = &LONCAPA::clean_domain($udom);
                   7569:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7570:     my $access=0;
1.800     albertel 7571:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7572: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7573: 	if ($type eq 'user') {
                   7574: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7575: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7576: 		if ($tdom) {
                   7577: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7578: 		}
1.896     albertel 7579: 		if ($tuname) {
                   7580: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7581: 		}
                   7582: 		$access=($effect eq 'allow');
                   7583: 		last;
                   7584: 	    }
                   7585: 	} else {
                   7586: 	    if ($role) {
                   7587: 		if ($role ne $urole) { next; }
                   7588: 	    }
                   7589: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7590: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7591: 		if ($tdom) {
                   7592: 		    if ($tdom ne $udom) { next; }
                   7593: 		}
                   7594: 		if ($tcrs) {
                   7595: 		    if ($tcrs ne $ucrs) { next; }
                   7596: 		}
                   7597: 		if ($tsec) {
                   7598: 		    if ($tsec ne $usec) { next; }
                   7599: 		}
                   7600: 		$access=($effect eq 'allow');
                   7601: 		last;
                   7602: 	    }
                   7603: 	    if ($realm eq '' && $role eq '') {
                   7604: 		$access=($effect eq 'allow');
                   7605: 	    }
1.402     bowersj2 7606: 	}
1.341     www      7607:     }
                   7608:     return $access;
                   7609: }
                   7610: 
1.103     harris41 7611: # ------------------------------------------------- Check for a user privilege
1.12      www      7612: 
                   7613: sub allowed {
1.1281    raeburn  7614:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7615:     my $ver_orguri=$uri;
1.439     www      7616:     $uri=&deversion($uri);
1.152     www      7617:     my $orguri=$uri;
1.52      www      7618:     $uri=&declutter($uri);
1.809     raeburn  7619: 
1.810     raeburn  7620:     if ($priv eq 'evb') {
                   7621: # Evade communication block restrictions for specified role in a course
                   7622:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7623:             return $1;
                   7624:         } else {
                   7625:             return;
                   7626:         }
                   7627:     }
                   7628: 
1.620     albertel 7629:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7630: # Free bre access to adm and meta resources
1.1343    raeburn  7631:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7632: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7633: 	&& ($priv eq 'bre')) {
1.14      www      7634: 	return 'F';
1.159     www      7635:     }
                   7636: 
1.545     banghart 7637: # Free bre access to user's own portfolio contents
1.714     raeburn  7638:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7639:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7640: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7641:         my %setters;
                   7642:         my ($startblock,$endblock) = 
                   7643:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7644:         if ($startblock && $endblock) {
                   7645:             return 'B';
                   7646:         } else {
                   7647:             return 'F';
                   7648:         }
1.545     banghart 7649:     }
                   7650: 
1.762     raeburn  7651: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7652:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7653:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7654:         if (exists($env{'request.course.id'})) {
                   7655:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7656:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7657:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7658:                 my $courseprivid=$env{'request.course.id'};
                   7659:                 $courseprivid=~s/\_/\//;
                   7660:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7661:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7662:                     return $1; 
1.762     raeburn  7663:                 } else {
                   7664:                     if ($env{'request.course.sec'}) {
                   7665:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7666:                     }
                   7667:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7668:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7669:                         return $2;
                   7670:                     }
1.714     raeburn  7671:                 }
                   7672:             }
                   7673:         }
                   7674:     }
                   7675: 
1.159     www      7676: # Free bre to public access
                   7677: 
                   7678:     if ($priv eq 'bre') {
1.1362    raeburn  7679:         my $copyright;
                   7680:         unless ($uri =~ /ext\.tool/) {
                   7681:             $copyright=&metadata($uri,'copyright');
                   7682:         }
1.620     albertel 7683: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7684:            return 'F'; 
                   7685:         }
1.238     www      7686:         if ($copyright eq 'priv') {
                   7687:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7688: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7689: 		return '';
                   7690:             }
                   7691:         }
                   7692:         if ($copyright eq 'domain') {
                   7693:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7694: 	    unless (($env{'user.domain'} eq $1) ||
                   7695:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7696: 		return '';
                   7697:             }
1.262     matthew  7698:         }
1.620     albertel 7699:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7700:             # Library role, so allow browsing of resources in this domain.
                   7701:             return 'F';
1.238     www      7702:         }
1.341     www      7703:         if ($copyright eq 'custom') {
                   7704: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7705:         }
1.14      www      7706:     }
1.264     matthew  7707:     # Domain coordinator is trying to create a course
1.620     albertel 7708:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7709:         # uri is the requested domain in this case.
                   7710:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7711:         # a role of dc for the domain in question.
1.620     albertel 7712:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7713:     }
1.29      www      7714: 
1.52      www      7715:     my $thisallowed='';
                   7716:     my $statecond=0;
                   7717:     my $courseprivid='';
                   7718: 
1.1039    raeburn  7719:     my $ownaccess;
1.1043    raeburn  7720:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7721:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7722:         if ($uri eq '') {
                   7723:             $ownaccess = 1;
                   7724:         } else {
                   7725:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7726:                 my $udom = $env{'user.domain'};
                   7727:                 my $uname = $env{'user.name'};
                   7728:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7729:                     $ownaccess = 1;
1.1040    raeburn  7730:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7731:                     unless ($uri =~ m{\.\./}) {
                   7732:                         $ownaccess = 1;
                   7733:                     }
                   7734:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7735:                     my $now = time;
                   7736:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7737:                         my $adom = $1;
                   7738:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7739:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7740:                                 my ($start,$end) = split('.',$env{$key});
                   7741:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7742:                                     $ownaccess = 1;
                   7743:                                     last;
                   7744:                                 }
                   7745:                             }
                   7746:                         }
                   7747:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7748:                         my $adom = $1;
                   7749:                         my $aname = $2;
1.1042    raeburn  7750:                         foreach my $role ('ca','aa') { 
                   7751:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7752:                                 my ($start,$end) =
                   7753:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7754:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7755:                                     $ownaccess = 1;
                   7756:                                     last;
                   7757:                                 }
1.1039    raeburn  7758:                             }
                   7759:                         }
                   7760:                     }
                   7761:                 }
                   7762:             }
                   7763:         }
                   7764:     }
                   7765: 
1.52      www      7766: # Course
                   7767: 
1.620     albertel 7768:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7769:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7770:             $thisallowed.=$1;
                   7771:         }
1.52      www      7772:     }
1.29      www      7773: 
1.52      www      7774: # Domain
                   7775: 
1.620     albertel 7776:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7777:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7778:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7779:             $thisallowed.=$1;
                   7780:         }
1.12      www      7781:     }
1.52      www      7782: 
1.1141    raeburn  7783: # User who is not author or co-author might still be able to edit
                   7784: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7785:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7786:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7787:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7788:             $thisallowed.=$1;
                   7789:         }
                   7790:     }
                   7791: 
1.52      www      7792: # Course: uri itself is a course
1.66      www      7793:     my $courseuri=$uri;
                   7794:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7795:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7796: 
1.620     albertel 7797:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7798:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7799:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7800:             $thisallowed.=$1;
                   7801:         }
1.12      www      7802:     }
1.29      www      7803: 
1.665     albertel 7804: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7805: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7806:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7807: 	$thisallowed='';
1.671     raeburn  7808:         my ($match)=&is_on_map($uri);
                   7809:         if ($match) {
                   7810:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7811:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7812:                 my $value = $1;
                   7813:                 if ($noblockcheck) {
                   7814:                     $thisallowed.=$value;
1.1162    raeburn  7815:                 } else {
1.1281    raeburn  7816:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7817:                     if (@blockers > 0) {
                   7818:                         $thisallowed = 'B';
                   7819:                     } else {
                   7820:                         $thisallowed.=$value;
                   7821:                     }
1.1162    raeburn  7822:                 }
1.671     raeburn  7823:             }
                   7824:         } else {
1.705     albertel 7825:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7826:             if ($refuri) {
                   7827:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7828:                     $thisallowed='F';
1.671     raeburn  7829:                 } else {
                   7830:                     $refuri=&declutter($refuri);
                   7831:                     my ($match) = &is_on_map($refuri);
                   7832:                     if ($match) {
1.1281    raeburn  7833:                         if ($noblockcheck) {
                   7834:                             $thisallowed='F';
1.1162    raeburn  7835:                         } else {
1.1281    raeburn  7836:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7837:                             if (@blockers > 0) {
                   7838:                                 $thisallowed = 'B';
                   7839:                             } else {
                   7840:                                 $thisallowed='F';
                   7841:                             }
1.1162    raeburn  7842:                         }
1.671     raeburn  7843:                     }
1.669     raeburn  7844:                 }
1.671     raeburn  7845:             }
                   7846:         }
1.314     www      7847:     }
1.492     albertel 7848: 
1.766     albertel 7849:     if ($priv eq 'bre'
                   7850: 	&& $thisallowed ne 'F' 
                   7851: 	&& $thisallowed ne '2'
                   7852: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7853: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7854:     }
1.1250    raeburn  7855: 
1.52      www      7856: # Full access at system, domain or course-wide level? Exit.
1.29      www      7857:     if ($thisallowed=~/F/) {
                   7858: 	return 'F';
                   7859:     }
                   7860: 
1.52      www      7861: # If this is generating or modifying users, exit with special codes
1.29      www      7862: 
1.643     www      7863:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7864: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7865: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7866: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7867: 	    unless ($auname) { return $thisallowed; }
                   7868: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7869: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7870: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7871: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7872: 	}
1.52      www      7873: 	return $thisallowed;
                   7874:     }
                   7875: #
1.103     harris41 7876: # Gathered so far: system, domain and course wide privileges
1.52      www      7877: #
                   7878: # Course: See if uri or referer is an individual resource that is part of 
                   7879: # the course
                   7880: 
1.620     albertel 7881:     if ($env{'request.course.id'}) {
1.232     www      7882: 
1.620     albertel 7883:        $courseprivid=$env{'request.course.id'};
                   7884:        if ($env{'request.course.sec'}) {
                   7885:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7886:        }
                   7887:        $courseprivid=~s/\_/\//;
                   7888:        my $checkreferer=1;
1.232     www      7889:        my ($match,$cond)=&is_on_map($uri);
                   7890:        if ($match) {
                   7891:            $statecond=$cond;
1.620     albertel 7892:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7893:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7894:                my $value = $1;
                   7895:                if ($priv eq 'bre') {
1.1281    raeburn  7896:                    if ($noblockcheck) {
                   7897:                        $thisallowed.=$value;
1.1162    raeburn  7898:                    } else {
1.1281    raeburn  7899:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7900:                        if (@blockers > 0) {
                   7901:                            $thisallowed = 'B';
                   7902:                        } else {
                   7903:                            $thisallowed.=$value;
                   7904:                        }
1.1162    raeburn  7905:                    }
                   7906:                } else {
                   7907:                    $thisallowed.=$value;
                   7908:                }
1.52      www      7909:                $checkreferer=0;
                   7910:            }
1.29      www      7911:        }
1.83      www      7912:        
1.148     www      7913:        if ($checkreferer) {
1.620     albertel 7914: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7915:             unless ($refuri) {
1.800     albertel 7916:                 foreach my $key (keys(%env)) {
                   7917: 		    if ($key=~/^httpref\..*\*/) {
                   7918: 			my $pattern=$key;
1.156     www      7919:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7920:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7921:                         $pattern=~s/\//\\\//g;
1.152     www      7922:                         if ($orguri=~/$pattern/) {
1.800     albertel 7923: 			    $refuri=$env{$key};
1.148     www      7924:                         }
                   7925:                     }
1.191     harris41 7926:                 }
1.148     www      7927:             }
1.232     www      7928: 
1.148     www      7929:          if ($refuri) { 
1.152     www      7930: 	  $refuri=&declutter($refuri);
1.232     www      7931:           my ($match,$cond)=&is_on_map($refuri);
                   7932:             if ($match) {
                   7933:               my $refstatecond=$cond;
1.620     albertel 7934:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7935:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7936:                   my $value = $1;
                   7937:                   if ($priv eq 'bre') {
1.1281    raeburn  7938:                       if ($noblockcheck) {
                   7939:                           $thisallowed.=$value;
1.1162    raeburn  7940:                       } else {
1.1281    raeburn  7941:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7942:                           if (@blockers > 0) {
                   7943:                               $thisallowed = 'B';
                   7944:                           } else {
                   7945:                               $thisallowed.=$value;
                   7946:                           }
1.1162    raeburn  7947:                       }
                   7948:                   } else {
                   7949:                       $thisallowed.=$value;
                   7950:                   }
1.53      www      7951:                   $uri=$refuri;
                   7952:                   $statecond=$refstatecond;
1.52      www      7953:               }
                   7954:           }
1.148     www      7955:         }
1.29      www      7956:        }
1.52      www      7957:    }
1.29      www      7958: 
1.52      www      7959: #
1.103     harris41 7960: # Gathered now: all privileges that could apply, and condition number
1.52      www      7961: # 
                   7962: #
                   7963: # Full or no access?
                   7964: #
1.29      www      7965: 
1.52      www      7966:     if ($thisallowed=~/F/) {
                   7967: 	return 'F';
                   7968:     }
1.29      www      7969: 
1.52      www      7970:     unless ($thisallowed) {
                   7971:         return '';
                   7972:     }
1.29      www      7973: 
1.52      www      7974: # Restrictions exist, deal with them
                   7975: #
                   7976: #   C:according to course preferences
                   7977: #   R:according to resource settings
                   7978: #   L:unless locked
                   7979: #   X:according to user session state
                   7980: #
                   7981: 
                   7982: # Possibly locked functionality, check all courses
1.54      www      7983: # Locks might take effect only after 10 minutes cache expiration for other
                   7984: # courses, and 2 minutes for current course
1.52      www      7985: 
                   7986:     my $envkey;
                   7987:     if ($thisallowed=~/L/) {
1.1000    raeburn  7988:         foreach $envkey (keys(%env)) {
1.54      www      7989:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7990:                my $courseid=$2;
                   7991:                my $roleid=$1.'.'.$2;
1.92      www      7992:                $courseid=~s/^\///;
1.54      www      7993:                my $expiretime=600;
1.620     albertel 7994:                if ($env{'request.role'} eq $roleid) {
1.54      www      7995: 		  $expiretime=120;
                   7996:                }
                   7997: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7998:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7999:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8000: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8001:                }
1.620     albertel 8002:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8003:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8004: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8005:                        &log($env{'user.domain'},$env{'user.name'},
                   8006:                             $env{'user.home'},
1.57      www      8007:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8008:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8009:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8010: 		       return '';
                   8011:                    }
                   8012:                }
1.620     albertel 8013:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8014:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8015: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8016:                        &log($env{'user.domain'},$env{'user.name'},
                   8017:                             $env{'user.home'},
1.57      www      8018:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8019:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8020:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8021: 		       return '';
                   8022:                    }
                   8023:                }
                   8024: 	   }
1.29      www      8025:        }
1.52      www      8026:     }
                   8027:    
                   8028: #
                   8029: # Rest of the restrictions depend on selected course
                   8030: #
                   8031: 
1.620     albertel 8032:     unless ($env{'request.course.id'}) {
1.766     albertel 8033: 	if ($thisallowed eq 'A') {
                   8034: 	    return 'A';
1.814     raeburn  8035:         } elsif ($thisallowed eq 'B') {
                   8036:             return 'B';
1.766     albertel 8037: 	} else {
                   8038: 	    return '1';
                   8039: 	}
1.52      www      8040:     }
1.29      www      8041: 
1.52      www      8042: #
                   8043: # Now user is definitely in a course
                   8044: #
1.53      www      8045: 
                   8046: 
                   8047: # Course preferences
                   8048: 
                   8049:    if ($thisallowed=~/C/) {
1.620     albertel 8050:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8051:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8052:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8053: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8054: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8055: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8056: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8057: 			$env{'request.course.id'});
                   8058: 	   }
1.237     www      8059:            return '';
                   8060:        }
                   8061: 
1.620     albertel 8062:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8063: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8064: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8065: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8066: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8067: 			$env{'request.course.id'});
                   8068: 	   }
1.54      www      8069:            return '';
                   8070:        }
1.53      www      8071:    }
                   8072: 
                   8073: # Resource preferences
                   8074: 
                   8075:    if ($thisallowed=~/R/) {
1.620     albertel 8076:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8077:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8078: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8079: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8080: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8081: 	   }
                   8082: 	   return '';
1.54      www      8083:        }
1.53      www      8084:    }
1.30      www      8085: 
1.246     www      8086: # Restricted by state or randomout?
1.30      www      8087: 
1.52      www      8088:    if ($thisallowed=~/X/) {
1.620     albertel 8089:       if ($env{'acc.randomout'}) {
1.579     albertel 8090: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8091:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8092:             return ''; 
                   8093:          }
1.247     www      8094:       }
                   8095:       if (&condval($statecond)) {
1.52      www      8096: 	 return '2';
                   8097:       } else {
                   8098:          return '';
                   8099:       }
                   8100:    }
1.30      www      8101: 
1.766     albertel 8102:     if ($thisallowed eq 'A') {
                   8103: 	return 'A';
1.814     raeburn  8104:     } elsif ($thisallowed eq 'B') {
                   8105:         return 'B';
1.766     albertel 8106:     }
1.52      www      8107:    return 'F';
1.232     www      8108: }
1.1162    raeburn  8109: 
1.1192    raeburn  8110: # ------------------------------------------- Check construction space access
                   8111: 
                   8112: sub constructaccess {
                   8113:     my ($url,$setpriv)=@_;
                   8114: 
                   8115: # We do not allow editing of previous versions of files
                   8116:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8117: 
                   8118: # Get username and domain from URL
                   8119:     my ($ownername,$ownerdomain,$ownerhome);
                   8120: 
                   8121:     ($ownerdomain,$ownername) =
1.1325    raeburn  8122:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8123: 
                   8124: # The URL does not really point to any authorspace, forget it
                   8125:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8126: 
                   8127: # Now we need to see if the user has access to the authorspace of
                   8128: # $ownername at $ownerdomain
                   8129: 
                   8130:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8131: # Real author for this?
                   8132:        $ownerhome = $env{'user.home'};
                   8133:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8134:           return ($ownername,$ownerdomain,$ownerhome);
                   8135:        }
                   8136:     } else {
                   8137: # Co-author for this?
                   8138:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8139:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8140:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8141:             return ($ownername,$ownerdomain,$ownerhome);
                   8142:         }
1.1312    raeburn  8143:         if ($env{'request.course.id'}) {
                   8144:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8145:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8146:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8147:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8148:                     return ($ownername,$ownerdomain,$ownerhome);
                   8149:                 }
                   8150:             }
                   8151:         }
1.1192    raeburn  8152:     }
                   8153: 
                   8154: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8155: # we might as well leave
                   8156:    unless ($setpriv) { return ''; }
                   8157: 
                   8158: # Backdoor access?
                   8159:     my $allowed=&allowed('eco',$ownerdomain);
                   8160: # Nope
                   8161:     unless ($allowed) { return ''; }
                   8162: # Looks like we may have access, but could be locked by the owner of the construction space
                   8163:     if ($allowed eq 'U') {
                   8164:         my %blocked=&get('environment',['domcoord.author'],
                   8165:                          $ownerdomain,$ownername);
                   8166: # Is blocked by owner
                   8167:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8168:     }
                   8169:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8170: # Grant temporary access
                   8171:         my $then=$env{'user.login.time'};
1.1209    raeburn  8172:         my $update=$env{'user.update.time'};
1.1192    raeburn  8173:         if (!$update) { $update = $then; }
                   8174:         my $refresh=$env{'user.refresh.time'};
                   8175:         if (!$refresh) { $refresh = $update; }
                   8176:         my $now = time;
                   8177:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8178:                            $now,'ca','constructaccess');
                   8179:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8180:         return($ownername,$ownerdomain,$ownerhome);
                   8181:     }
                   8182: # No business here
                   8183:     return '';
                   8184: }
                   8185: 
1.1282    raeburn  8186: # ----------------------------------------------------------- Content Blocking
                   8187: 
                   8188: {
                   8189: # Caches for faster Course Contents display where content blocking
                   8190: # is in operation (i.e., interval param set) for timed quiz.
                   8191: #
                   8192: # User for whom data are being temporarily cached.
                   8193: my $cacheduser='';
                   8194: # Cached blockers for this user (a hash of blocking items). 
                   8195: my %cachedblockers=();
                   8196: # When the data were last cached.
                   8197: my $cachedlast='';
                   8198: 
                   8199: sub load_all_blockers {
                   8200:     my ($uname,$udom,$blocks)=@_;
                   8201:     if (($uname ne '') && ($udom ne '')) { 
                   8202:         if (($cacheduser eq $uname.':'.$udom) &&
                   8203:             (abs($cachedlast-time)<5)) {
                   8204:             return;
                   8205:         }
                   8206:     }
                   8207:     $cachedlast=time;
                   8208:     $cacheduser=$uname.':'.$udom;
                   8209:     %cachedblockers = &get_commblock_resources($blocks);
                   8210: }
                   8211: 
1.1162    raeburn  8212: sub get_comm_blocks {
                   8213:     my ($cdom,$cnum) = @_;
                   8214:     if ($cdom eq '' || $cnum eq '') {
                   8215:         return unless ($env{'request.course.id'});
                   8216:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8217:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8218:     }
                   8219:     my %commblocks;
                   8220:     my $hashid=$cdom.'_'.$cnum;
                   8221:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8222:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8223:         %commblocks = %{$blocksref};
                   8224:     } else {
                   8225:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8226:         my $cachetime = 600;
                   8227:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8228:     }
                   8229:     return %commblocks;
                   8230: }
                   8231: 
1.1282    raeburn  8232: sub get_commblock_resources {
                   8233:     my ($blocks) = @_;
                   8234:     my %blockers = ();
                   8235:     return %blockers unless ($env{'request.course.id'});
                   8236:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8237:     my %commblocks;
                   8238:     if (ref($blocks) eq 'HASH') {
                   8239:         %commblocks = %{$blocks};
                   8240:     } else {
                   8241:         %commblocks = &get_comm_blocks();
                   8242:     }
1.1282    raeburn  8243:     return %blockers unless (keys(%commblocks) > 0); 
                   8244:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8245:     return %blockers unless (ref($navmap));
1.1162    raeburn  8246:     my $now = time;
                   8247:     foreach my $block (keys(%commblocks)) {
                   8248:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8249:             my ($start,$end) = ($1,$2);
                   8250:             if ($start <= $now && $end >= $now) {
                   8251:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8252:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8253:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8254:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8255:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8256:                             }
                   8257:                         }
                   8258:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8259:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8260:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8261:                             }
                   8262:                         }
                   8263:                     }
                   8264:                 }
                   8265:             }
                   8266:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8267:             my $item = $1;
1.1163    raeburn  8268:             my @to_test;
1.1162    raeburn  8269:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8270:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8271:                     my @interval;
                   8272:                     my $type = 'map';
                   8273:                     if ($item eq 'course') {
                   8274:                         $type = 'course';
                   8275:                         @interval=&EXT("resource.0.interval");
                   8276:                     } else {
                   8277:                         if ($item =~ /___\d+___/) {
                   8278:                             $type = 'resource';
                   8279:                             @interval=&EXT("resource.0.interval",$item);
                   8280:                             if (ref($navmap)) {                        
                   8281:                                 my $res = $navmap->getBySymb($item); 
                   8282:                                 push(@to_test,$res);
                   8283:                             }
1.1162    raeburn  8284:                         } else {
1.1282    raeburn  8285:                             my $mapsymb = &symbread($item,1);
                   8286:                             if ($mapsymb) {
                   8287:                                 if (ref($navmap)) {
                   8288:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8289:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8290:                                     foreach my $res (@to_test) {
                   8291:                                         my $symb = $res->symb();
                   8292:                                         next if ($symb eq $mapsymb);
                   8293:                                         if ($symb ne '') {
                   8294:                                             @interval=&EXT("resource.0.interval",$symb);
                   8295:                                             if ($interval[1] eq 'map') {
                   8296:                                                 last;
1.1162    raeburn  8297:                                             }
                   8298:                                         }
                   8299:                                     }
                   8300:                                 }
                   8301:                             }
                   8302:                         }
1.1282    raeburn  8303:                     }
1.1310    raeburn  8304:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8305:                         my $timelimit = $1; 
1.1282    raeburn  8306:                         my $first_access;
                   8307:                         if ($type eq 'resource') {
                   8308:                             $first_access=&get_first_access($interval[1],$item);
                   8309:                         } elsif ($type eq 'map') {
                   8310:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8311:                         } else {
                   8312:                             $first_access=&get_first_access($interval[1]);
                   8313:                         }
                   8314:                         if ($first_access) {
1.1292    raeburn  8315:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8316:                             if ($timesup > $now) {
                   8317:                                 my $activeblock;
                   8318:                                 foreach my $res (@to_test) {
1.1283    raeburn  8319:                                     if ($res->answerable()) {
1.1282    raeburn  8320:                                         $activeblock = 1;
                   8321:                                         last;
                   8322:                                     }
                   8323:                                 }
                   8324:                                 if ($activeblock) {
                   8325:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8326:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8327:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8328:                                          }
                   8329:                                     }
                   8330:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8331:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8332:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8333:                                         }
1.1162    raeburn  8334:                                     }
                   8335:                                 }
                   8336:                             }
                   8337:                         }
                   8338:                     }
                   8339:                 }
                   8340:             }
                   8341:         }
                   8342:     }
1.1282    raeburn  8343:     return %blockers;
1.1162    raeburn  8344: }
                   8345: 
1.1282    raeburn  8346: sub has_comm_blocking {
                   8347:     my ($priv,$symb,$uri,$blocks) = @_;
                   8348:     my @blockers;
                   8349:     return unless ($env{'request.course.id'});
                   8350:     return unless ($priv eq 'bre');
                   8351:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8352:     return if ($env{'request.state'} eq 'construct');
                   8353:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8354:     return unless (keys(%cachedblockers) > 0);
                   8355:     my (%possibles,@symbs);
                   8356:     if (!$symb) {
                   8357:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8358:     }
1.1282    raeburn  8359:     if ($symb) {
                   8360:         @symbs = ($symb);
                   8361:     } elsif (keys(%possibles)) { 
                   8362:         @symbs = keys(%possibles);
                   8363:     }
                   8364:     my $noblock;
                   8365:     foreach my $symb (@symbs) {
                   8366:         last if ($noblock);
                   8367:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8368:         foreach my $block (keys(%cachedblockers)) {
                   8369:             if ($block =~ /^firstaccess____(.+)$/) {
                   8370:                 my $item = $1;
                   8371:                 if (($item eq $map) || ($item eq $symb)) {
                   8372:                     $noblock = 1;
                   8373:                     last;
                   8374:                 }
                   8375:             }
                   8376:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8377:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8378:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8379:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8380:                             push(@blockers,$block);
                   8381:                         }
                   8382:                     }
                   8383:                 }
1.1162    raeburn  8384:             }
1.1282    raeburn  8385:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8386:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8387:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8388:                         push(@blockers,$block);
                   8389:                     }
                   8390:                 }
1.1162    raeburn  8391:             }
                   8392:         }
                   8393:     }
1.1282    raeburn  8394:     return if ($noblock);
                   8395:     return @blockers;
                   8396: }
1.1162    raeburn  8397: }
                   8398: 
1.1282    raeburn  8399: # -------------------------------- Deversion and split uri into path an filename   
                   8400: 
1.1133    foxr     8401: #
1.1282    raeburn  8402: #   Removes the version from a URI and
1.1133    foxr     8403: #   splits it in to its filename and path to the filename.
                   8404: #   Seems like File::Basename could have done this more clearly.
                   8405: #   Parameters:
                   8406: #      $uri   - input URI
                   8407: #   Returns:
                   8408: #     Two element list consisting of 
                   8409: #     $pathname  - the URI up to and excluding the trailing /
                   8410: #     $filename  - The part of the URI following the last /
                   8411: #  NOTE:
                   8412: #    Another realization of this is simply:
                   8413: #    use File::Basename;
                   8414: #    ...
                   8415: #    $uri = shift;
                   8416: #    $filename = basename($uri);
                   8417: #    $path     = dirname($uri);
                   8418: #    return ($filename, $path);
                   8419: #
                   8420: #     The implementation below is probably faster however.
                   8421: #
1.710     albertel 8422: sub split_uri_for_cond {
                   8423:     my $uri=&deversion(&declutter(shift));
                   8424:     my @uriparts=split(/\//,$uri);
                   8425:     my $filename=pop(@uriparts);
                   8426:     my $pathname=join('/',@uriparts);
                   8427:     return ($pathname,$filename);
                   8428: }
1.232     www      8429: # --------------------------------------------------- Is a resource on the map?
                   8430: 
                   8431: sub is_on_map {
1.710     albertel 8432:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8433:     #Trying to find the conditional for the file
1.620     albertel 8434:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8435: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8436:     if ($match) {
1.289     bowersj2 8437: 	return (1,$1);
                   8438:     } else {
1.434     www      8439: 	return (0,0);
1.289     bowersj2 8440:     }
1.12      www      8441: }
                   8442: 
1.427     www      8443: # --------------------------------------------------------- Get symb from alias
                   8444: 
                   8445: sub get_symb_from_alias {
                   8446:     my $symb=shift;
                   8447:     my ($map,$resid,$url)=&decode_symb($symb);
                   8448: # Already is a symb
                   8449:     if ($url) { return $symb; }
                   8450: # Must be an alias
                   8451:     my $aliassymb='';
                   8452:     my %bighash;
1.620     albertel 8453:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8454:                             &GDBM_READER(),0640)) {
                   8455:         my $rid=$bighash{'mapalias_'.$symb};
                   8456: 	if ($rid) {
                   8457: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8458: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8459: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8460: 	}
                   8461:         untie %bighash;
                   8462:     }
                   8463:     return $aliassymb;
                   8464: }
                   8465: 
1.12      www      8466: # ----------------------------------------------------------------- Define Role
                   8467: 
                   8468: sub definerole {
                   8469:   if (allowed('mcr','/')) {
1.1326    raeburn  8470:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8471:     foreach my $role (split(':',$sysrole)) {
                   8472: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8473:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8474:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8475: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8476:                return "refused:s:$crole&$cqual"; 
                   8477:             }
                   8478:         }
1.191     harris41 8479:     }
1.800     albertel 8480:     foreach my $role (split(':',$domrole)) {
                   8481: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8482:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8483:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8484: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8485:                return "refused:d:$crole&$cqual"; 
                   8486:             }
                   8487:         }
1.191     harris41 8488:     }
1.800     albertel 8489:     foreach my $role (split(':',$courole)) {
                   8490: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8491:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8492:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8493: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8494:                return "refused:c:$crole&$cqual"; 
                   8495:             }
                   8496:         }
1.191     harris41 8497:     }
1.1326    raeburn  8498:     my $uhome;
                   8499:     if (($uname ne '') && ($udom ne '')) {
                   8500:         $uhome = &homeserver($uname,$udom);
                   8501:         return $uhome if ($uhome eq 'no_host');
                   8502:     } else {
                   8503:         $uname = $env{'user.name'};
                   8504:         $udom = $env{'user.domain'};
                   8505:         $uhome = $env{'user.home'};
                   8506:     }
1.620     albertel 8507:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8508:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8509:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8510:     return reply($command,$uhome);
1.12      www      8511:   } else {
                   8512:     return 'refused';
                   8513:   }
1.105     harris41 8514: }
                   8515: 
                   8516: # ---------------- Make a metadata query against the network of library servers
                   8517: 
                   8518: sub metadata_query {
1.1237    raeburn  8519:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8520:     my %rhash;
1.845     albertel 8521:     my %libserv = &all_library();
1.244     matthew  8522:     my @server_list = (defined($server_array) ? @$server_array
                   8523:                                               : keys(%libserv) );
                   8524:     for my $server (@server_list) {
1.1237    raeburn  8525:         my $domains = ''; 
                   8526:         if (ref($domains_hash) eq 'HASH') {
                   8527:             $domains = $domains_hash->{$server}; 
                   8528:         }
1.118     harris41 8529: 	unless ($custom or $customshow) {
1.1237    raeburn  8530: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8531: 	    $rhash{$server}=$reply;
                   8532: 	}
                   8533: 	else {
                   8534: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8535: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8536: 			     $server);
                   8537: 	    $rhash{$server}=$reply;
                   8538: 	}
1.112     harris41 8539:     }
1.118     harris41 8540:     return \%rhash;
1.240     www      8541: }
                   8542: 
                   8543: # ----------------------------------------- Send log queries and wait for reply
                   8544: 
                   8545: sub log_query {
                   8546:     my ($uname,$udom,$query,%filters)=@_;
                   8547:     my $uhome=&homeserver($uname,$udom);
                   8548:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8549:     my $uhost=&hostname($uhome);
1.800     albertel 8550:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8551:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8552:                        $uhome);
1.479     albertel 8553:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8554:     return get_query_reply($queryid);
                   8555: }
                   8556: 
1.818     raeburn  8557: # -------------------------- Update MySQL table for portfolio file
                   8558: 
                   8559: sub update_portfolio_table {
1.821     raeburn  8560:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8561:     if ($group ne '') {
                   8562:         $file_name =~s /^\Q$group\E//;
                   8563:     }
1.818     raeburn  8564:     my $homeserver = &homeserver($uname,$udom);
                   8565:     my $queryid=
1.821     raeburn  8566:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8567:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8568:     my $reply = &get_query_reply($queryid);
                   8569:     return $reply;
                   8570: }
                   8571: 
1.899     raeburn  8572: # -------------------------- Update MySQL allusers table
                   8573: 
                   8574: sub update_allusers_table {
                   8575:     my ($uname,$udom,$names) = @_;
                   8576:     my $homeserver = &homeserver($uname,$udom);
                   8577:     my $queryid=
                   8578:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8579:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8580:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8581:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8582:                'generation='.&escape($names->{'generation'}).'%%'.
                   8583:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8584:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8585:     return;
1.899     raeburn  8586: }
                   8587: 
1.508     raeburn  8588: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8589: 
                   8590: sub fetch_enrollment_query {
1.511     raeburn  8591:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8592:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8593:     my $maxtries = 1;
1.508     raeburn  8594:     if ($context eq 'automated') {
                   8595:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8596:         $sleep = 2;
                   8597:         $loopmax = 100;
1.547     raeburn  8598:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8599:     } else {
                   8600:         $homeserver = &homeserver($cnum,$dom);
                   8601:     }
1.838     albertel 8602:     my $host=&hostname($homeserver);
1.506     raeburn  8603:     my $cmd = '';
1.1000    raeburn  8604:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8605:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8606:     }
                   8607:     $cmd =~ s/%%$//;
                   8608:     $cmd = &escape($cmd);
                   8609:     my $query = 'fetchenrollment';
1.620     albertel 8610:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8611:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8612:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8613:         return 'error: '.$queryid;
                   8614:     }
1.1317    raeburn  8615:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8616:     my $tries = 1;
                   8617:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8618:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8619:         $tries ++;
                   8620:     }
1.526     raeburn  8621:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8622:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8623:     } else {
1.901     albertel 8624:         my @responses = split(/:/,$reply);
1.1322    raeburn  8625:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8626:             foreach my $line (@responses) {
                   8627:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8628:                 $$replyref{$key} = $value;
                   8629:             }
                   8630:         } else {
1.1117    foxr     8631:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8632:             foreach my $line (@responses) {
                   8633:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8634:                 $$replyref{$key} = $value;
                   8635:                 if ($value > 0) {
1.800     albertel 8636:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8637:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8638:                         my $destname = $pathname.'/'.$filename;
                   8639:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8640:                         if ($xml_classlist =~ /^error/) {
                   8641:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8642:                         } else {
1.1359    raeburn  8643:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8644:                                 print FILE &unescape($xml_classlist);
                   8645:                                 close(FILE);
1.526     raeburn  8646:                             } else {
                   8647:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8648:                             }
                   8649:                         }
                   8650:                     }
                   8651:                 }
                   8652:             }
                   8653:         }
                   8654:         return 'ok';
                   8655:     }
                   8656:     return 'error';
                   8657: }
                   8658: 
1.242     www      8659: sub get_query_reply {
1.1317    raeburn  8660:     my ($queryid,$sleep,$loopmax) = @_;;
                   8661:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8662:         $sleep = 0.2;
                   8663:     }
                   8664:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8665:         $loopmax = 100;
                   8666:     }
1.1117    foxr     8667:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8668:     my $reply='';
1.1317    raeburn  8669:     for (1..$loopmax) {
                   8670: 	sleep($sleep);
1.240     www      8671:         if (-e $replyfile.'.end') {
1.1359    raeburn  8672: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8673: 		$reply = join('',<$fh>);
                   8674: 		close($fh);
1.240     www      8675: 	   } else { return 'error: reply_file_error'; }
1.242     www      8676:            return &unescape($reply);
                   8677: 	}
1.240     www      8678:     }
1.242     www      8679:     return 'timeout:'.$queryid;
1.240     www      8680: }
                   8681: 
                   8682: sub courselog_query {
1.241     www      8683: #
                   8684: # possible filters:
                   8685: # url: url or symb
                   8686: # username
                   8687: # domain
                   8688: # action: view, submit, grade
                   8689: # start: timestamp
                   8690: # end: timestamp
                   8691: #
1.240     www      8692:     my (%filters)=@_;
1.620     albertel 8693:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8694:     if ($filters{'url'}) {
                   8695: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8696:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8697:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8698:     }
1.620     albertel 8699:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8700:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8701:     return &log_query($cname,$cdom,'courselog',%filters);
                   8702: }
                   8703: 
                   8704: sub userlog_query {
1.858     raeburn  8705: #
                   8706: # possible filters:
                   8707: # action: log check role
                   8708: # start: timestamp
                   8709: # end: timestamp
                   8710: #
1.240     www      8711:     my ($uname,$udom,%filters)=@_;
                   8712:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8713: }
                   8714: 
1.506     raeburn  8715: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8716: 
                   8717: sub auto_run {
1.508     raeburn  8718:     my ($cnum,$cdom) = @_;
1.876     raeburn  8719:     my $response = 0;
                   8720:     my $settings;
                   8721:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8722:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8723:         $settings = $domconfig{'autoenroll'};
                   8724:         if ($settings->{'run'} eq '1') {
                   8725:             $response = 1;
                   8726:         }
                   8727:     } else {
1.934     raeburn  8728:         my $homeserver;
                   8729:         if (&is_course($cdom,$cnum)) {
                   8730:             $homeserver = &homeserver($cnum,$cdom);
                   8731:         } else {
                   8732:             $homeserver = &domain($cdom,'primary');
                   8733:         }
                   8734:         if ($homeserver ne 'no_host') {
                   8735:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8736:         }
1.876     raeburn  8737:     }
1.506     raeburn  8738:     return $response;
                   8739: }
1.776     albertel 8740: 
1.506     raeburn  8741: sub auto_get_sections {
1.508     raeburn  8742:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8743:     my $homeserver;
                   8744:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8745:         $homeserver = &homeserver($cnum,$cdom);
                   8746:     }
                   8747:     if (!defined($homeserver)) { 
                   8748:         if ($cdom =~ /^$match_domain$/) {
                   8749:             $homeserver = &domain($cdom,'primary');
                   8750:         }
                   8751:     }
                   8752:     my @secs;
                   8753:     if (defined($homeserver)) {
                   8754:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8755:         unless ($response eq 'refused') {
                   8756:             @secs = split(/:/,$response);
                   8757:         }
1.506     raeburn  8758:     }
                   8759:     return @secs;
                   8760: }
1.776     albertel 8761: 
1.506     raeburn  8762: sub auto_new_course {
1.1099    raeburn  8763:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8764:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8765:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8766:     return $response;
                   8767: }
1.776     albertel 8768: 
1.506     raeburn  8769: sub auto_validate_courseID {
1.508     raeburn  8770:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8771:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8772:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8773:     return $response;
                   8774: }
1.776     albertel 8775: 
1.1007    raeburn  8776: sub auto_validate_instcode {
1.1020    raeburn  8777:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8778:     my ($homeserver,$response);
                   8779:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8780:         $homeserver = &homeserver($cnum,$cdom);
                   8781:     }
                   8782:     if (!defined($homeserver)) {
                   8783:         if ($cdom =~ /^$match_domain$/) {
                   8784:             $homeserver = &domain($cdom,'primary');
                   8785:         }
                   8786:     }
1.1065    raeburn  8787:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8788:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8789:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8790:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8791: }
                   8792: 
1.506     raeburn  8793: sub auto_create_password {
1.873     raeburn  8794:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8795:     my ($homeserver,$response);
1.506     raeburn  8796:     my $create_passwd = 0;
                   8797:     my $authchk = '';
1.873     raeburn  8798:     if ($udom =~ /^$match_domain$/) {
                   8799:         $homeserver = &domain($udom,'primary');
                   8800:     }
                   8801:     if ($homeserver eq '') {
                   8802:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8803:             $homeserver = &homeserver($cnum,$cdom);
                   8804:         }
                   8805:     }
                   8806:     if ($homeserver eq '') {
                   8807:         $authchk = 'nodomain';
1.506     raeburn  8808:     } else {
1.873     raeburn  8809:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8810:         if ($response eq 'refused') {
                   8811:             $authchk = 'refused';
                   8812:         } else {
1.901     albertel 8813:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8814:         }
1.506     raeburn  8815:     }
                   8816:     return ($authparam,$create_passwd,$authchk);
                   8817: }
                   8818: 
1.706     raeburn  8819: sub auto_photo_permission {
                   8820:     my ($cnum,$cdom,$students) = @_;
                   8821:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8822:     my ($outcome,$perm_reqd,$conditions) = 
                   8823: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8824:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8825: 	return (undef,undef);
                   8826:     }
1.706     raeburn  8827:     return ($outcome,$perm_reqd,$conditions);
                   8828: }
                   8829: 
                   8830: sub auto_checkphotos {
                   8831:     my ($uname,$udom,$pid) = @_;
                   8832:     my $homeserver = &homeserver($uname,$udom);
                   8833:     my ($result,$resulttype);
                   8834:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8835: 				   &escape($uname).':'.&escape($pid),
                   8836: 				   $homeserver));
1.709     albertel 8837:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8838: 	return (undef,undef);
                   8839:     }
1.706     raeburn  8840:     if ($outcome) {
                   8841:         ($result,$resulttype) = split(/:/,$outcome);
                   8842:     } 
                   8843:     return ($result,$resulttype);
                   8844: }
                   8845: 
                   8846: sub auto_photochoice {
                   8847:     my ($cnum,$cdom) = @_;
                   8848:     my $homeserver = &homeserver($cnum,$cdom);
                   8849:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8850: 						       &escape($cdom),
                   8851: 						       $homeserver)));
1.709     albertel 8852:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8853: 	return (undef,undef);
                   8854:     }
1.706     raeburn  8855:     return ($update,$comment);
                   8856: }
                   8857: 
                   8858: sub auto_photoupdate {
                   8859:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8860:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8861:     my $host=&hostname($homeserver);
1.706     raeburn  8862:     my $cmd = '';
                   8863:     my $maxtries = 1;
1.800     albertel 8864:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8865:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8866:     }
                   8867:     $cmd =~ s/%%$//;
                   8868:     $cmd = &escape($cmd);
                   8869:     my $query = 'institutionalphotos';
                   8870:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8871:     unless ($queryid=~/^\Q$host\E\_/) {
                   8872:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8873:         return 'error: '.$queryid;
                   8874:     }
                   8875:     my $reply = &get_query_reply($queryid);
                   8876:     my $tries = 1;
                   8877:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8878:         $reply = &get_query_reply($queryid);
                   8879:         $tries ++;
                   8880:     }
                   8881:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8882:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8883:     } else {
                   8884:         my @responses = split(/:/,$reply);
                   8885:         my $outcome = shift(@responses); 
                   8886:         foreach my $item (@responses) {
                   8887:             my ($key,$value) = split(/=/,$item);
                   8888:             $$photo{$key} = $value;
                   8889:         }
                   8890:         return $outcome;
                   8891:     }
                   8892:     return 'error';
                   8893: }
                   8894: 
1.521     raeburn  8895: sub auto_instcode_format {
1.793     albertel 8896:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8897: 	$cat_order) = @_;
1.521     raeburn  8898:     my $courses = '';
1.772     raeburn  8899:     my @homeservers;
1.521     raeburn  8900:     if ($caller eq 'global') {
1.841     albertel 8901: 	my %servers = &get_servers($codedom,'library');
                   8902: 	foreach my $tryserver (keys(%servers)) {
                   8903: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8904: 		push(@homeservers,$tryserver);
                   8905: 	    }
1.584     raeburn  8906:         }
1.1022    raeburn  8907:     } elsif ($caller eq 'requests') {
                   8908:         if ($codedom =~ /^$match_domain$/) {
                   8909:             my $chome = &domain($codedom,'primary');
                   8910:             unless ($chome eq 'no_host') {
                   8911:                 push(@homeservers,$chome);
                   8912:             }
                   8913:         }
1.521     raeburn  8914:     } else {
1.772     raeburn  8915:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8916:     }
1.793     albertel 8917:     foreach my $code (keys(%{$instcodes})) {
                   8918:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8919:     }
                   8920:     chop($courses);
1.772     raeburn  8921:     my $ok_response = 0;
                   8922:     my $response;
                   8923:     while (@homeservers > 0 && $ok_response == 0) {
                   8924:         my $server = shift(@homeservers); 
                   8925:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8926:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8927:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8928: 		split(/:/,$response);
1.772     raeburn  8929:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8930:             push(@{$codetitles},&str2array($codetitles_str));
                   8931:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8932:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8933:             $ok_response = 1;
                   8934:         }
                   8935:     }
                   8936:     if ($ok_response) {
1.521     raeburn  8937:         return 'ok';
1.772     raeburn  8938:     } else {
                   8939:         return $response;
1.521     raeburn  8940:     }
                   8941: }
                   8942: 
1.792     raeburn  8943: sub auto_instcode_defaults {
                   8944:     my ($domain,$returnhash,$code_order) = @_;
                   8945:     my @homeservers;
1.841     albertel 8946: 
                   8947:     my %servers = &get_servers($domain,'library');
                   8948:     foreach my $tryserver (keys(%servers)) {
                   8949: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8950: 	    push(@homeservers,$tryserver);
                   8951: 	}
1.792     raeburn  8952:     }
1.841     albertel 8953: 
1.792     raeburn  8954:     my $response;
1.841     albertel 8955:     foreach my $server (@homeservers) {
1.792     raeburn  8956:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8957:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8958: 	
                   8959: 	foreach my $pair (split(/\&/,$response)) {
                   8960: 	    my ($name,$value)=split(/\=/,$pair);
                   8961: 	    if ($name eq 'code_order') {
                   8962: 		@{$code_order} = split(/\&/,&unescape($value));
                   8963: 	    } else {
                   8964: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8965: 	    }
                   8966: 	}
                   8967: 	return 'ok';
1.792     raeburn  8968:     }
1.841     albertel 8969: 
                   8970:     return $response;
1.1003    raeburn  8971: }
                   8972: 
                   8973: sub auto_possible_instcodes {
1.1007    raeburn  8974:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8975:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8976:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8977:         return;
                   8978:     }
1.1003    raeburn  8979:     my (@homeservers,$uhome);
                   8980:     if (defined(&domain($domain,'primary'))) {
                   8981:         $uhome=&domain($domain,'primary');
                   8982:         push(@homeservers,&domain($domain,'primary'));
                   8983:     } else {
                   8984:         my %servers = &get_servers($domain,'library');
                   8985:         foreach my $tryserver (keys(%servers)) {
                   8986:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8987:                 push(@homeservers,$tryserver);
                   8988:             }
                   8989:         }
                   8990:     }
                   8991:     my $response;
                   8992:     foreach my $server (@homeservers) {
                   8993:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8994:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8995:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8996:             split(':',$response);
                   8997:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8998:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8999:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9000:             my ($name,$value)=split('=',$item);
                   9001:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9002:         }
                   9003:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9004:             my ($name,$value)=split('=',$item);
                   9005:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9006:         }
                   9007:         return 'ok';
                   9008:     }
                   9009:     return $response;
                   9010: }
1.792     raeburn  9011: 
1.1010    raeburn  9012: sub auto_courserequest_checks {
                   9013:     my ($dom) = @_;
1.1020    raeburn  9014:     my ($homeserver,%validations);
                   9015:     if ($dom =~ /^$match_domain$/) {
                   9016:         $homeserver = &domain($dom,'primary');
                   9017:     }
                   9018:     unless ($homeserver eq 'no_host') {
                   9019:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9020:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9021:             my @items = split(/&/,$response);
                   9022:             foreach my $item (@items) {
                   9023:                 my ($key,$value) = split('=',$item);
                   9024:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9025:             }
                   9026:         }
                   9027:     }
1.1010    raeburn  9028:     return %validations; 
                   9029: }
                   9030: 
1.1020    raeburn  9031: sub auto_courserequest_validation {
1.1255    raeburn  9032:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9033:     my ($homeserver,$response);
                   9034:     if ($dom =~ /^$match_domain$/) {
                   9035:         $homeserver = &domain($dom,'primary');
                   9036:     }
1.1255    raeburn  9037:     unless ($homeserver eq 'no_host') {
                   9038:         my $customdata;
                   9039:         if (ref($custominfo) eq 'HASH') {
                   9040:             $customdata = &freeze_escape($custominfo);
                   9041:         }
1.1020    raeburn  9042:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9043:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9044:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9045:                                     $customdata,$homeserver));
1.1020    raeburn  9046:     }
                   9047:     return $response;
                   9048: }
                   9049: 
1.777     albertel 9050: sub auto_validate_class_sec {
1.918     raeburn  9051:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9052:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9053:     my $ownerlist;
                   9054:     if (ref($owners) eq 'ARRAY') {
                   9055:         $ownerlist = join(',',@{$owners});
                   9056:     } else {
                   9057:         $ownerlist = $owners;
                   9058:     }
1.773     raeburn  9059:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9060:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9061:     return $response;
                   9062: }
                   9063: 
1.1367    raeburn  9064: sub auto_validate_instclasses {
                   9065:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9066:     my ($homeserver,%validations);
                   9067:     $homeserver = &homeserver($cnum,$cdom);
                   9068:     unless ($homeserver eq 'no_host') {
                   9069:         my $ownerlist;
                   9070:         if (ref($owners) eq 'ARRAY') {
                   9071:             $ownerlist = join(',',@{$owners});
                   9072:         } else {
                   9073:             $ownerlist = $owners;
                   9074:         }
                   9075:         if (ref($classesref) eq 'HASH') {
                   9076:             my $classes = &freeze_escape($classesref);
                   9077:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9078:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9079:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9080:                 my @items = split(/&/,$response);
                   9081:                 foreach my $item (@items) {
                   9082:                     my ($key,$value) = split('=',$item);
                   9083:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9084:                 }
                   9085:             }
                   9086:         }
                   9087:     }
                   9088:     return %validations;
                   9089: }
                   9090: 
1.1248    raeburn  9091: sub auto_crsreq_update {
                   9092:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9093:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9094:     my ($homeserver,%crsreqresponse);
                   9095:     if ($cdom =~ /^$match_domain$/) {
                   9096:         $homeserver = &domain($cdom,'primary');
                   9097:     }
                   9098:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9099:         my $info;
                   9100:         if (ref($inbound) eq 'HASH') {
                   9101:             $info = &freeze_escape($inbound);
                   9102:         }
                   9103:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9104:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9105:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9106:                             &escape($title).':'.&escape($code).':'.
                   9107:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9108:                             $homeserver);
1.1248    raeburn  9109:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9110:             my @items = split(/&/,$response);
                   9111:             foreach my $item (@items) {
                   9112:                 my ($key,$value) = split('=',$item);
                   9113:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9114:             }
                   9115:         }
                   9116:     }
                   9117:     return \%crsreqresponse;
                   9118: }
                   9119: 
1.1305    raeburn  9120: sub auto_export_grades {
1.1309    raeburn  9121:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9122:     my ($homeserver,%exportresponse);
                   9123:     if ($cdom =~ /^$match_domain$/) {
                   9124:         $homeserver = &domain($cdom,'primary');
                   9125:     }
                   9126:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9127:         my $info;
                   9128:         if (ref($inforef) eq 'HASH') {
                   9129:             $info = &freeze_escape($inforef);
                   9130:         }
                   9131:         if (ref($gradesref) eq 'HASH') {
                   9132:             my $grades = &freeze_escape($gradesref);
                   9133:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9134:                                 $info.':'.$grades,$homeserver);
                   9135:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9136:                 my @items = split(/&/,$response);
                   9137:                 foreach my $item (@items) {
                   9138:                     my ($key,$value) = split('=',$item);
                   9139:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9140:                 }
                   9141:             }
                   9142:         }
                   9143:     }
                   9144:     return \%exportresponse;
1.1305    raeburn  9145: }
                   9146: 
1.1287    raeburn  9147: sub check_instcode_cloning {
                   9148:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9149:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9150:         return;
                   9151:     }
                   9152:     my $canclone;
                   9153:     if (@{$code_order} > 0) {
                   9154:         my $instcoderegexp ='^';
                   9155:         my @clonecodes = split(/\&/,$cloner);
                   9156:         foreach my $item (@{$code_order}) {
                   9157:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9158:                 foreach my $pair (@clonecodes) {
                   9159:                     my ($key,$val) = split(/\=/,$pair,2);
                   9160:                     $val = &unescape($val);
                   9161:                     if ($key eq $item) {
                   9162:                         $instcoderegexp .= '('.$val.')';
                   9163:                         last;
                   9164:                     }
                   9165:                 }
                   9166:             } else {
                   9167:                 $instcoderegexp .= $codedefaults->{$item};
                   9168:             }
                   9169:         }
                   9170:         $instcoderegexp .= '$';
                   9171:         my (@from,@to);
                   9172:         eval {
                   9173:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9174:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9175:         };
                   9176:         if ((@from > 0) && (@to > 0)) {
                   9177:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9178:             if (!@diffs) {
                   9179:                 $canclone = 1;
                   9180:             }
                   9181:         }
                   9182:     }
                   9183:     return $canclone;
                   9184: }
                   9185: 
                   9186: sub default_instcode_cloning {
                   9187:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9188:     my (%codedefaults,@code_order,$canclone);
                   9189:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9190:         %codedefaults = %{$codedefaultsref};
                   9191:         @code_order = @{$codeorderref};
                   9192:     } elsif ($clonedom) {
                   9193:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9194:     }
                   9195:     if (($domdefclone) && (@code_order)) {
                   9196:         my @clonecodes = split(/\+/,$domdefclone);
                   9197:         my $instcoderegexp ='^';
                   9198:         foreach my $item (@code_order) {
                   9199:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9200:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9201:             } else {
                   9202:                 $instcoderegexp .= $codedefaults{$item};
                   9203:             }
                   9204:         }
                   9205:         $instcoderegexp .= '$';
                   9206:         my (@from,@to);
                   9207:         eval {
                   9208:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9209:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9210:         };
                   9211:         if ((@from > 0) && (@to > 0)) {
                   9212:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9213:             if (!@diffs) {
                   9214:                 $canclone = 1;
                   9215:             }
                   9216:         }
                   9217:     }
                   9218:     return $canclone;
                   9219: }
                   9220: 
1.679     raeburn  9221: # ------------------------------------------------------- Course Group routines
                   9222: 
                   9223: sub get_coursegroups {
1.809     raeburn  9224:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9225:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9226: }
                   9227: 
1.679     raeburn  9228: sub modify_coursegroup {
                   9229:     my ($cdom,$cnum,$groupsettings) = @_;
                   9230:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9231: }
                   9232: 
1.809     raeburn  9233: sub toggle_coursegroup_status {
                   9234:     my ($cdom,$cnum,$group,$action) = @_;
                   9235:     my ($from_namespace,$to_namespace);
                   9236:     if ($action eq 'delete') {
                   9237:         $from_namespace = 'coursegroups';
                   9238:         $to_namespace = 'deleted_groups';
                   9239:     } else {
                   9240:         $from_namespace = 'deleted_groups';
                   9241:         $to_namespace = 'coursegroups';
                   9242:     }
                   9243:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9244:     if (my $tmp = &error(%curr_group)) {
                   9245:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9246:         return ('read error',$tmp);
                   9247:     } else {
                   9248:         my %savedsettings = %curr_group; 
1.809     raeburn  9249:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9250:         my $deloutcome;
                   9251:         if ($result eq 'ok') {
1.809     raeburn  9252:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9253:         } else {
                   9254:             return ('write error',$result);
                   9255:         }
                   9256:         if ($deloutcome eq 'ok') {
                   9257:             return 'ok';
                   9258:         } else {
                   9259:             return ('delete error',$deloutcome);
                   9260:         }
                   9261:     }
                   9262: }
                   9263: 
1.679     raeburn  9264: sub modify_group_roles {
1.957     raeburn  9265:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9266:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9267:     my $role = 'gr/'.&escape($userprivs);
                   9268:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9269:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9270:     if ($result eq 'ok') {
                   9271:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9272:     }
1.679     raeburn  9273:     return $result;
                   9274: }
                   9275: 
                   9276: sub modify_coursegroup_membership {
                   9277:     my ($cdom,$cnum,$membership) = @_;
                   9278:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9279:     return $result;
                   9280: }
                   9281: 
1.682     raeburn  9282: sub get_active_groups {
                   9283:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9284:     my $now = time;
                   9285:     my %groups = ();
                   9286:     foreach my $key (keys(%env)) {
1.811     albertel 9287:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9288:             my ($start,$end) = split(/\./,$env{$key});
                   9289:             if (($end!=0) && ($end<$now)) { next; }
                   9290:             if (($start!=0) && ($start>$now)) { next; }
                   9291:             if ($1 eq $cdom && $2 eq $cnum) {
                   9292:                 $groups{$3} = $env{$key} ;
                   9293:             }
                   9294:         }
                   9295:     }
                   9296:     return %groups;
                   9297: }
                   9298: 
1.683     raeburn  9299: sub get_group_membership {
                   9300:     my ($cdom,$cnum,$group) = @_;
                   9301:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9302: }
                   9303: 
                   9304: sub get_users_groups {
                   9305:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9306:     my @usersgroups;
1.683     raeburn  9307:     my $cachetime=1800;
                   9308: 
                   9309:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9310:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9311:     if (defined($cached)) {
1.734     albertel 9312:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9313:     } else {  
                   9314:         $grouplist = '';
1.816     raeburn  9315:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9316:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9317:         my $access_end = $env{'course.'.$courseid.
                   9318:                               '.default_enrollment_end_date'};
                   9319:         my $now = time;
                   9320:         foreach my $key (keys(%roleshash)) {
                   9321:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9322:                 my $group = $1;
                   9323:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9324:                     my $start = $2;
                   9325:                     my $end = $1;
                   9326:                     if ($start == -1) { next; } # deleted from group
                   9327:                     if (($start!=0) && ($start>$now)) { next; }
                   9328:                     if (($end!=0) && ($end<$now)) {
                   9329:                         if ($access_end && $access_end < $now) {
                   9330:                             if ($access_end - $end < 86400) {
                   9331:                                 push(@usersgroups,$group);
1.733     raeburn  9332:                             }
                   9333:                         }
1.817     raeburn  9334:                         next;
1.733     raeburn  9335:                     }
1.817     raeburn  9336:                     push(@usersgroups,$group);
1.683     raeburn  9337:                 }
                   9338:             }
                   9339:         }
1.817     raeburn  9340:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9341:         $grouplist = join(':',@usersgroups);
                   9342:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9343:     }
1.733     raeburn  9344:     return @usersgroups;
1.683     raeburn  9345: }
                   9346: 
                   9347: sub devalidate_getgroups_cache {
                   9348:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9349:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9350: 
1.683     raeburn  9351:     my $hashid="$udom:$uname:$courseid";
                   9352:     &devalidate_cache_new('getgroups',$hashid);
                   9353: }
                   9354: 
1.12      www      9355: # ------------------------------------------------------------------ Plain Text
                   9356: 
                   9357: sub plaintext {
1.988     raeburn  9358:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9359:     if ($short =~ m{^cr/}) {
1.758     albertel 9360: 	return (split('/',$short))[-1];
                   9361:     }
1.742     raeburn  9362:     if (!defined($cid)) {
                   9363:         $cid = $env{'request.course.id'};
                   9364:     }
                   9365:     my %rolenames = (
1.1008    raeburn  9366:                       Course    => 'std',
                   9367:                       Community => 'alt1',
1.1305    raeburn  9368:                       Placement => 'std',
1.742     raeburn  9369:                     );
1.1037    raeburn  9370:     if ($cid ne '') {
                   9371:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9372:             unless ($forcedefault) {
                   9373:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9374:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9375:                 return &Apache::lonlocal::mt($roletext);
                   9376:             }
                   9377:         }
                   9378:     }
                   9379:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9380:         (defined($rolenames{$type})) && 
                   9381:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9382:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9383:     } elsif ($cid ne '') {
                   9384:         my $crstype = $env{'course.'.$cid.'.type'};
                   9385:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9386:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9387:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9388:         }
1.742     raeburn  9389:     }
1.1037    raeburn  9390:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9391: }
                   9392: 
                   9393: # ----------------------------------------------------------------- Assign Role
                   9394: 
                   9395: sub assignrole {
1.957     raeburn  9396:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9397:         $context)=@_;
1.21      www      9398:     my $mrole;
                   9399:     if ($role =~ /^cr\//) {
1.393     www      9400:         my $cwosec=$url;
1.811     albertel 9401:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9402: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9403:            my $refused = 1;
                   9404:            if ($context eq 'requestcourses') {
                   9405:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9406:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9407:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9408:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9409:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9410:                            if ($crsenv{'internal.courseowner'} eq
                   9411:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9412:                                $refused = '';
                   9413:                            }
                   9414:                        }
                   9415:                    }
                   9416:                }
                   9417:            }
                   9418:            if ($refused) {
                   9419:                &logthis('Refused custom assignrole: '.
                   9420:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9421:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9422:                return 'refused';
                   9423:            }
1.104     www      9424:         }
1.21      www      9425:         $mrole='cr';
1.678     raeburn  9426:     } elsif ($role =~ /^gr\//) {
                   9427:         my $cwogrp=$url;
1.811     albertel 9428:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9429:         unless (&allowed('mdg',$cwogrp)) {
                   9430:             &logthis('Refused group assignrole: '.
                   9431:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9432:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9433:             return 'refused';
                   9434:         }
                   9435:         $mrole='gr';
1.21      www      9436:     } else {
1.82      www      9437:         my $cwosec=$url;
1.811     albertel 9438:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9439:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9440:             my $refused;
                   9441:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9442:                 if (!(&allowed('c'.$role,$url))) {
                   9443:                     $refused = 1;
                   9444:                 }
                   9445:             } else {
                   9446:                 $refused = 1;
                   9447:             }
1.947     raeburn  9448:             if ($refused) {
1.1045    raeburn  9449:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9450:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9451:                     my %crsenv;
                   9452:                     if ($role eq 'cc' || $role eq 'co') {
                   9453:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9454:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9455:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9456:                                 if ($crsenv{'internal.courseowner'} eq 
                   9457:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9458:                                     $refused = '';
                   9459:                                 }
                   9460:                             }
                   9461:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9462:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9463:                                 if ($crsenv{'internal.courseowner'} eq 
                   9464:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9465:                                     $refused = '';
                   9466:                                 }
                   9467:                             }
                   9468:                         }
                   9469:                     }
1.1368    raeburn  9470:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9471:                     if ($role eq 'st') {
                   9472:                         $refused = '';
1.1377    raeburn  9473:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9474:                         $refused = '';
                   9475:                     }
1.1017    raeburn  9476:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9477:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9478:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9479:                         my $wrongcc;
                   9480:                         if ($cnum =~ /^$match_community$/) {
                   9481:                             $wrongcc = 1 if ($role eq 'cc');
                   9482:                         } else {
                   9483:                             $wrongcc = 1 if ($role eq 'co');
                   9484:                         }
                   9485:                         unless ($wrongcc) {
                   9486:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9487:                             if ($crsenv{'internal.courseowner'} eq 
                   9488:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9489:                                 $refused = '';
                   9490:                             }
1.1017    raeburn  9491:                         }
                   9492:                     }
1.1183    raeburn  9493:                 } elsif ($context eq 'requestauthor') {
                   9494:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9495:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9496:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9497:                             $refused = '';
                   9498:                         } else {
                   9499:                             my %domdefaults = &get_domain_defaults($udom);
                   9500:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9501:                                 my $checkbystatus;
                   9502:                                 if ($env{'user.adv'}) { 
                   9503:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9504:                                     if ($disposition eq 'automatic') {
                   9505:                                         $refused = '';
                   9506:                                     } elsif ($disposition eq '') {
                   9507:                                         $checkbystatus = 1;
                   9508:                                     } 
                   9509:                                 } else {
                   9510:                                     $checkbystatus = 1;
                   9511:                                 }
                   9512:                                 if ($checkbystatus) {
                   9513:                                     if ($env{'environment.inststatus'}) {
                   9514:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9515:                                         foreach my $type (@inststatuses) {
                   9516:                                             if (($type ne '') &&
                   9517:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9518:                                                 $refused = '';
                   9519:                                             }
                   9520:                                         }
                   9521:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9522:                                         $refused = '';
                   9523:                                     }
                   9524:                                 }
                   9525:                             }
                   9526:                         }
                   9527:                     }
1.1017    raeburn  9528:                 }
                   9529:                 if ($refused) {
1.947     raeburn  9530:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9531:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9532: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9533:                     return 'refused';
                   9534:                 }
1.932     raeburn  9535:             }
1.1131    raeburn  9536:         } elsif ($role eq 'au') {
                   9537:             if ($url ne '/'.$udom.'/') {
                   9538:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9539:                          ' to assign author role for '.$uname.':'.$udom.
                   9540:                          ' in domain: '.$url.' refused (wrong domain).');
                   9541:                 return 'refused';
                   9542:             }
1.104     www      9543:         }
1.21      www      9544:         $mrole=$role;
                   9545:     }
1.620     albertel 9546:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9547:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9548:     if ($end) { $command.='_'.$end; }
1.21      www      9549:     if ($start) {
                   9550: 	if ($end) { 
1.81      www      9551:            $command.='_'.$start; 
1.21      www      9552:         } else {
1.81      www      9553:            $command.='_0_'.$start;
1.21      www      9554:         }
                   9555:     }
1.739     raeburn  9556:     my $origstart = $start;
                   9557:     my $origend = $end;
1.957     raeburn  9558:     my $delflag;
1.357     www      9559: # actually delete
                   9560:     if ($deleteflag) {
1.373     www      9561: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9562: # modify command to delete the role
1.620     albertel 9563:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9564:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9565: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9566: # set start and finish to negative values for userrolelog
                   9567:            $start=-1;
                   9568:            $end=-1;
1.957     raeburn  9569:            $delflag = 1;
1.357     www      9570:         }
                   9571:     }
                   9572: # send command
1.349     www      9573:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9574: # log new user role if status is ok
1.349     www      9575:     if ($answer eq 'ok') {
1.663     raeburn  9576: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9577:         if (($role eq 'cc') || ($role eq 'in') ||
                   9578:             ($role eq 'ep') || ($role eq 'ad') ||
                   9579:             ($role eq 'ta') || ($role eq 'st') ||
                   9580:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9581:             ($role eq 'co')) {
1.1200    raeburn  9582: # for course roles, perform group memberships changes triggered by role change.
                   9583:             unless ($role =~ /^gr/) {
                   9584:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9585:                                                  $origstart,$selfenroll,$context);
                   9586:             }
1.1184    raeburn  9587:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9588:                            $selfenroll,$context);
                   9589:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9590:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9591:                  ($role eq 'da')) {
1.1184    raeburn  9592:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9593:                            $context);
                   9594:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9595:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9596:                              $context); 
                   9597:         }
1.1053    raeburn  9598:         if ($role eq 'cc') {
                   9599:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9600:         }
1.349     www      9601:     }
                   9602:     return $answer;
1.169     harris41 9603: }
                   9604: 
1.1053    raeburn  9605: sub autoupdate_coowners {
                   9606:     my ($url,$end,$start,$uname,$udom) = @_;
                   9607:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9608:     if (($cdom ne '') && ($cnum ne '')) {
                   9609:         my $now = time;
                   9610:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9611:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9612:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9613:             my $instcode = $coursehash{'internal.coursecode'};
                   9614:             if ($instcode ne '') {
1.1056    raeburn  9615:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9616:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9617:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9618:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9619:                         if ($result eq 'valid') {
                   9620:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9621:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9622:                                     push(@newcoowners,$coowner);
                   9623:                                 }
                   9624:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9625:                                     push(@newcoowners,$uname.':'.$udom);
                   9626:                                 }
                   9627:                                 @newcoowners = sort(@newcoowners);
                   9628:                             } else {
                   9629:                                 push(@newcoowners,$uname.':'.$udom);
                   9630:                             }
                   9631:                         } else {
                   9632:                             if ($coursehash{'internal.co-owners'}) {
                   9633:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9634:                                     unless ($coowner eq $uname.':'.$udom) {
                   9635:                                         push(@newcoowners,$coowner);
                   9636:                                     }
                   9637:                                 }
                   9638:                                 unless (@newcoowners > 0) {
                   9639:                                     $delcoowners = 1;
                   9640:                                     $coowners = '';
                   9641:                                 }
                   9642:                             }
                   9643:                         }
                   9644:                         if (@newcoowners || $delcoowners) {
                   9645:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9646:                                             $delcoowners,@newcoowners);
                   9647:                         }
                   9648:                     }
                   9649:                 }
                   9650:             }
                   9651:         }
                   9652:     }
                   9653: }
                   9654: 
                   9655: sub store_coowners {
                   9656:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9657:     my $cid = $cdom.'_'.$cnum;
                   9658:     my ($coowners,$delresult,$putresult);
                   9659:     if (@newcoowners) {
                   9660:         $coowners = join(',',@newcoowners);
                   9661:         my %coownershash = (
                   9662:                             'internal.co-owners' => $coowners,
                   9663:                            );
                   9664:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9665:         if ($putresult eq 'ok') {
                   9666:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9667:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9668:             }
                   9669:         }
                   9670:     }
                   9671:     if ($delcoowners) {
                   9672:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9673:         if ($delresult eq 'ok') {
                   9674:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9675:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9676:             }
                   9677:         }
                   9678:     }
                   9679:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9680:         my %crsinfo =
                   9681:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9682:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9683:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9684:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9685:         }
                   9686:     }
                   9687: }
                   9688: 
1.169     harris41 9689: # -------------------------------------------------- Modify user authentication
1.197     www      9690: # Overrides without validation
                   9691: 
1.169     harris41 9692: sub modifyuserauth {
                   9693:     my ($udom,$uname,$umode,$upass)=@_;
                   9694:     my $uhome=&homeserver($uname,$udom);
1.197     www      9695:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9696:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9697:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9698:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9699:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9700: 		     &escape($upass),$uhome);
1.620     albertel 9701:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9702:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9703:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9704:     &log($udom,,$uname,$uhome,
1.620     albertel 9705:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9706:                                      $env{'user.name'}.', '.$umode.
1.197     www      9707:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9708:     unless ($reply eq 'ok') {
1.197     www      9709:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9710: 	return 'error: '.$reply;
                   9711:     }   
1.170     harris41 9712:     return 'ok';
1.80      www      9713: }
                   9714: 
1.81      www      9715: # --------------------------------------------------------------- Modify a user
1.80      www      9716: 
1.81      www      9717: sub modifyuser {
1.206     matthew  9718:     my ($udom,    $uname, $uid,
                   9719:         $umode,   $upass, $first,
                   9720:         $middle,  $last,  $gene,
1.1058    raeburn  9721:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9722:     $udom= &LONCAPA::clean_domain($udom);
                   9723:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9724:     my $showcandelete = 'none';
                   9725:     if (ref($candelete) eq 'ARRAY') {
                   9726:         if (@{$candelete} > 0) {
                   9727:             $showcandelete = join(', ',@{$candelete});
                   9728:         }
                   9729:     }
1.81      www      9730:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9731:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9732: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9733:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9734:                                      ' desiredhome not specified'). 
1.620     albertel 9735:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9736:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9737:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9738:     my $newuser;
                   9739:     if ($uhome eq 'no_host') {
                   9740:         $newuser = 1;
1.1368    raeburn  9741:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9742:                 ($umode eq 'lti')) {
                   9743:             return 'error: more information needed to create new user';
                   9744:         }
1.1075    raeburn  9745:     }
1.80      www      9746: # ----------------------------------------------------------------- Create User
1.406     albertel 9747:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9748: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9749:         my $unhome='';
1.844     albertel 9750:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9751:             $unhome = $desiredhome;
1.620     albertel 9752: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9753: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9754:         } else { # load balancing routine for determining $unhome
1.81      www      9755:             my $loadm=10000000;
1.841     albertel 9756: 	    my %servers = &get_servers($udom,'library');
                   9757: 	    foreach my $tryserver (keys(%servers)) {
                   9758: 		my $answer=reply('load',$tryserver);
                   9759: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9760: 		    $loadm=$answer;
                   9761: 		    $unhome=$tryserver;
                   9762: 		}
1.80      www      9763: 	    }
                   9764:         }
                   9765:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9766: 	    return 'error: unable to find a home server for '.$uname.
                   9767:                    ' in domain '.$udom;
1.80      www      9768:         }
                   9769:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9770:                          &escape($upass),$unhome);
                   9771: 	unless ($reply eq 'ok') {
                   9772:             return 'error: '.$reply;
                   9773:         }   
1.230     stredwic 9774:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9775:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9776: 	    return 'error: unable verify users home machine.';
1.80      www      9777:         }
1.209     matthew  9778:     }   # End of creation of new user
1.80      www      9779: # ---------------------------------------------------------------------- Add ID
                   9780:     if ($uid) {
                   9781:        $uid=~tr/A-Z/a-z/;
                   9782:        my %uidhash=&idrget($udom,$uname);
1.196     www      9783:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9784:          && (!$forceid)) {
1.80      www      9785: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9786: 	      return 'error: user id "'.$uid.'" does not match '.
                   9787:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9788:           }
                   9789:        } else {
1.1300    raeburn  9790: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9791:        }
                   9792:     }
                   9793: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9794:     my @tmp=&get('environment',
1.899     raeburn  9795: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9796:                     'permanentemail','inststatus'],
1.134     albertel 9797: 		   $udom,$uname);
1.1075    raeburn  9798:     my (%names,%oldnames);
1.313     matthew  9799:     if ($tmp[0] =~ m/^error:.*/) { 
                   9800:         %names=(); 
                   9801:     } else {
                   9802:         %names = @tmp;
1.1075    raeburn  9803:         %oldnames = %names;
1.313     matthew  9804:     }
1.388     www      9805: #
1.1058    raeburn  9806: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9807: # of users did not contain them), do not overwrite existing values
                   9808: # unless field is in $candelete array ref.  
                   9809: #
                   9810: 
                   9811:     my @fields = ('firstname','middlename','lastname','generation',
                   9812:                   'permanentemail','id');
                   9813:     my %newvalues;
                   9814:     if (ref($candelete) eq 'ARRAY') {
                   9815:         foreach my $field (@fields) {
                   9816:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9817:                 if ($field eq 'firstname') {
                   9818:                     $names{$field} = $first;
                   9819:                 } elsif ($field eq 'middlename') {
                   9820:                     $names{$field} = $middle;
                   9821:                 } elsif ($field eq 'lastname') {
                   9822:                     $names{$field} = $last;
                   9823:                 } elsif ($field eq 'generation') { 
                   9824:                     $names{$field} = $gene;
                   9825:                 } elsif ($field eq 'permanentemail') {
                   9826:                     $names{$field} = $email;
                   9827:                 } elsif ($field eq 'id') {
                   9828:                     $names{$field}  = $uid;
                   9829:                 }
                   9830:             }
                   9831:         }
                   9832:     }
1.388     www      9833:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9834:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9835:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9836:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9837:     if ($email) {
                   9838:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9839:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9840:     }
1.899     raeburn  9841:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9842:     if (defined($inststatus)) {
                   9843:         $names{'inststatus'} = '';
                   9844:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9845:         if (ref($usertypes) eq 'HASH') {
                   9846:             my @okstatuses; 
                   9847:             foreach my $item (split(/:/,$inststatus)) {
                   9848:                 if (defined($usertypes->{$item})) {
                   9849:                     push(@okstatuses,$item);  
                   9850:                 }
                   9851:             }
                   9852:             if (@okstatuses) {
                   9853:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9854:             }
                   9855:         }
                   9856:     }
1.1075    raeburn  9857:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9858:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9859:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9860:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9861:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9862:     } else {
                   9863:         $logmsg .= ' during self creation';
                   9864:     }
1.1075    raeburn  9865:     my $changed;
                   9866:     if ($newuser) {
                   9867:         $changed = 1;
                   9868:     } else {
                   9869:         foreach my $field (@fields) {
                   9870:             if ($names{$field} ne $oldnames{$field}) {
                   9871:                 $changed = 1;
                   9872:                 last;
                   9873:             }
                   9874:         }
                   9875:     }
                   9876:     unless ($changed) {
                   9877:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9878:         &logthis($logmsg);
                   9879:         return 'ok';
                   9880:     }
                   9881:     my $reply = &put('environment', \%names, $udom,$uname);
                   9882:     if ($reply ne 'ok') { 
                   9883:         return 'error: '.$reply;
                   9884:     }
1.1087    raeburn  9885:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9886:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9887:     }
1.1075    raeburn  9888:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9889:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9890:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9891:     &logthis($logmsg);
1.134     albertel 9892:     return 'ok';
1.80      www      9893: }
                   9894: 
1.81      www      9895: # -------------------------------------------------------------- Modify student
1.80      www      9896: 
1.81      www      9897: sub modifystudent {
                   9898:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9899:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9900:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9901:     if (!$cid) {
1.620     albertel 9902: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9903: 	    return 'not_in_class';
                   9904: 	}
1.80      www      9905:     }
                   9906: # --------------------------------------------------------------- Make the user
1.81      www      9907:     my $reply=&modifyuser
1.209     matthew  9908: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9909:          $desiredhome,$email,$inststatus);
1.80      www      9910:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9911:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9912:     # student's environment
1.297     matthew  9913:     $uid = undef if (!$forceid);
1.455     albertel 9914:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9915:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9916:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9917:     return $reply;
                   9918: }
                   9919: 
                   9920: sub modify_student_enrollment {
1.1216    raeburn  9921:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9922:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9923:     my ($cdom,$cnum,$chome);
                   9924:     if (!$cid) {
1.620     albertel 9925: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9926: 	    return 'not_in_class';
                   9927: 	}
1.620     albertel 9928: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9929: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9930:     } else {
                   9931: 	($cdom,$cnum)=split(/_/,$cid);
                   9932:     }
1.620     albertel 9933:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9934:     if (!$chome) {
1.457     raeburn  9935: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9936:     }
1.455     albertel 9937:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9938:     # Make sure the user exists
1.81      www      9939:     my $uhome=&homeserver($uname,$udom);
                   9940:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9941: 	return 'error: no such user';
                   9942:     }
1.297     matthew  9943:     # Get student data if we were not given enough information
                   9944:     if (!defined($first)  || $first  eq '' || 
                   9945:         !defined($last)   || $last   eq '' || 
                   9946:         !defined($uid)    || $uid    eq '' || 
                   9947:         !defined($middle) || $middle eq '' || 
                   9948:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9949:         # They did not supply us with enough data to enroll the student, so
                   9950:         # we need to pick up more information.
1.297     matthew  9951:         my %tmp = &get('environment',
1.294     matthew  9952:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9953:                        ,$udom,$uname);
                   9954: 
1.800     albertel 9955:         #foreach my $key (keys(%tmp)) {
                   9956:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9957:         #}
1.294     matthew  9958:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9959:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9960:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9961:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9962:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9963:     }
1.556     albertel 9964:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9965:     my $user = "$uname:$udom";
                   9966:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9967:     my $reply=cput('classlist',
1.1148    raeburn  9968: 		   {$user => 
1.1314    raeburn  9969: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9970: 		   $cdom,$cnum);
1.1148    raeburn  9971:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9972:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9973:     } else { 
1.81      www      9974: 	return 'error: '.$reply;
                   9975:     }
1.297     matthew  9976:     # Add student role to user
1.83      www      9977:     my $uurl='/'.$cid;
1.81      www      9978:     $uurl=~s/\_/\//g;
                   9979:     if ($usec) {
                   9980: 	$uurl.='/'.$usec;
                   9981:     }
1.1148    raeburn  9982:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9983:                              $selfenroll,$context);
                   9984:     if ($result ne 'ok') {
                   9985:         if ($old_entry{$user} ne '') {
                   9986:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9987:         } else {
                   9988:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9989:         }
                   9990:     }
                   9991:     return $result; 
1.21      www      9992: }
                   9993: 
1.556     albertel 9994: sub format_name {
                   9995:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9996:     my $name;
                   9997:     if ($first ne 'lastname') {
                   9998: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9999:     } else {
                   10000: 	if ($lastname=~/\S/) {
                   10001: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10002: 	    $name=~s/\s+,/,/;
                   10003: 	} else {
                   10004: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10005: 	}
                   10006:     }
                   10007:     $name=~s/^\s+//;
                   10008:     $name=~s/\s+$//;
                   10009:     $name=~s/\s+/ /g;
                   10010:     return $name;
                   10011: }
                   10012: 
1.84      www      10013: # ------------------------------------------------- Write to course preferences
                   10014: 
                   10015: sub writecoursepref {
                   10016:     my ($courseid,%prefs)=@_;
                   10017:     $courseid=~s/^\///;
                   10018:     $courseid=~s/\_/\//g;
                   10019:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10020:     my $chome=homeserver($cnum,$cdomain);
                   10021:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10022: 	return 'error: no such course';
                   10023:     }
                   10024:     my $cstring='';
1.800     albertel 10025:     foreach my $pref (keys(%prefs)) {
                   10026: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10027:     }
1.84      www      10028:     $cstring=~s/\&$//;
                   10029:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10030: }
                   10031: 
                   10032: # ---------------------------------------------------------- Make/modify course
                   10033: 
                   10034: sub createcourse {
1.741     raeburn  10035:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10036:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10037:     $url=&declutter($url);
                   10038:     my $cid='';
1.1028    raeburn  10039:     if ($context eq 'requestcourses') {
                   10040:         my $can_create = 0;
                   10041:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10042:         if ($udom eq $ownerdom) {
                   10043:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10044:                                   $context)) {
                   10045:                 $can_create = 1;
                   10046:             }
                   10047:         } else {
                   10048:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10049:                                            $category);
                   10050:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10051:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10052:                 if (@curr > 0) {
                   10053:                     my @options = qw(approval validate autolimit);
                   10054:                     my $optregex = join('|',@options);
                   10055:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10056:                         $can_create = 1;
                   10057:                     }
                   10058:                 }
                   10059:             }
                   10060:         }
                   10061:         if ($can_create) {
                   10062:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10063:                 unless (&allowed('ccc',$udom)) {
                   10064:                     return 'refused'; 
                   10065:                 }
1.1017    raeburn  10066:             }
                   10067:         } else {
                   10068:             return 'refused';
                   10069:         }
1.1028    raeburn  10070:     } elsif (!&allowed('ccc',$udom)) {
                   10071:         return 'refused';
1.84      www      10072:     }
1.1011    raeburn  10073: # --------------------------------------------------------------- Get Unique ID
                   10074:     my $uname;
                   10075:     if ($cnum =~ /^$match_courseid$/) {
                   10076:         my $chome=&homeserver($cnum,$udom,'true');
                   10077:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10078:             $uname = $cnum;
                   10079:         } else {
1.1038    raeburn  10080:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10081:         }
                   10082:     } else {
1.1038    raeburn  10083:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10084:     }
                   10085:     return $uname if ($uname =~ /^error/);
                   10086: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10087:     if (!defined($course_server)) {
                   10088:         if (defined(&domain($udom,'primary'))) {
                   10089:             $course_server = &domain($udom,'primary');
                   10090:         } else {
                   10091:             $course_server = $env{'user.home'}; 
                   10092:         }
                   10093:     }
                   10094:     my %host_servers =
                   10095:         &Apache::lonnet::get_servers($udom,'library');
                   10096:     unless ($host_servers{$course_server}) {
                   10097:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10098:     }
1.84      www      10099: # ------------------------------------------------------------- Make the course
                   10100:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10101:                       $course_server);
1.84      www      10102:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10103:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10104:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10105: 	return 'error: no such course';
                   10106:     }
1.271     www      10107: # ----------------------------------------------------------------- Course made
1.516     raeburn  10108: # log existence
1.1029    raeburn  10109:     my $now = time;
1.918     raeburn  10110:     my $newcourse = {
                   10111:                     $udom.'_'.$uname => {
1.921     raeburn  10112:                                      description => $description,
                   10113:                                      inst_code   => $inst_code,
                   10114:                                      owner       => $course_owner,
                   10115:                                      type        => $crstype,
1.1029    raeburn  10116:                                      creator     => $env{'user.name'}.':'.
                   10117:                                                     $env{'user.domain'},
                   10118:                                      created     => $now,
                   10119:                                      context     => $context,
1.918     raeburn  10120:                                                 },
                   10121:                     };
1.921     raeburn  10122:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10123: # set toplevel url
1.271     www      10124:     my $topurl=$url;
                   10125:     unless ($nonstandard) {
                   10126: # ------------------------------------------ For standard courses, make top url
                   10127:         my $mapurl=&clutter($url);
1.278     www      10128:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10129:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10130: <map>
                   10131: <resource id="1" type="start"></resource>
                   10132: <resource id="2" src="$mapurl"></resource>
                   10133: <resource id="3" type="finish"></resource>
                   10134: <link index="1" from="1" to="2"></link>
                   10135: <link index="2" from="2" to="3"></link>
                   10136: </map>
                   10137: ENDINITMAP
                   10138:         $topurl=&declutter(
1.638     albertel 10139:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10140:                           );
                   10141:     }
                   10142: # ----------------------------------------------------------- Write preferences
1.84      www      10143:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10144:                      ('description'              => $description,
                   10145:                       'url'                      => $topurl,
                   10146:                       'internal.creator'         => $env{'user.name'}.':'.
                   10147:                                                     $env{'user.domain'},
                   10148:                       'internal.created'         => $now,
                   10149:                       'internal.creationcontext' => $context)
                   10150:                     );
1.84      www      10151:     return '/'.$udom.'/'.$uname;
                   10152: }
                   10153: 
1.1011    raeburn  10154: # ------------------------------------------------------------------- Create ID
                   10155: sub generate_coursenum {
1.1038    raeburn  10156:     my ($udom,$crstype) = @_;
1.1011    raeburn  10157:     my $domdesc = &domain($udom);
                   10158:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10159:     my $first;
                   10160:     if ($crstype eq 'Community') {
                   10161:         $first = '0';
                   10162:     } else {
                   10163:         $first = int(1+rand(9)); 
                   10164:     } 
                   10165:     my $uname=$first.
1.1011    raeburn  10166:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10167:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10168:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10169: # ----------------------------------------------- Make sure that does not exist
                   10170:     my $uhome=&homeserver($uname,$udom,'true');
                   10171:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10172:         if ($crstype eq 'Community') {
                   10173:             $first = '0';
                   10174:         } else {
                   10175:             $first = int(1+rand(9));
                   10176:         }
                   10177:         $uname=$first.
1.1011    raeburn  10178:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10179:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10180:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10181:         $uhome=&homeserver($uname,$udom,'true');
                   10182:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10183:             return 'error: unable to generate unique course-ID';
                   10184:         }
                   10185:     }
                   10186:     return $uname;
                   10187: }
                   10188: 
1.813     albertel 10189: sub is_course {
1.1167    droeschl 10190:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10191:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10192: 
1.1381    raeburn  10193:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10194:     my $uhome=&homeserver($cnum,$cdom);
                   10195:     my $iscourse;
                   10196:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10197:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10198:     } else {
                   10199:         my $hashid = $cdom.':'.$cnum;
                   10200:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10201:         unless (defined($cached)) {
                   10202:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10203:                                         $cnum,undef,undef,'.');
                   10204:             $iscourse = 0;
                   10205:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10206:                 $iscourse = 1;
                   10207:             }
                   10208:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10209:         }
                   10210:     }
                   10211:     return unless ($iscourse);
1.1167    droeschl 10212:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10213: }
                   10214: 
1.1015    raeburn  10215: sub store_userdata {
                   10216:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10217:     my $result;
1.1016    raeburn  10218:     if ($datakey ne '') {
1.1013    raeburn  10219:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10220:             if ($udom eq '' || $uname eq '') {
                   10221:                 $udom = $env{'user.domain'};
                   10222:                 $uname = $env{'user.name'};
                   10223:             }
                   10224:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10225:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10226:                 $result = 'error: no_host';
                   10227:             } else {
                   10228:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10229:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10230: 
                   10231:                 my $namevalue='';
                   10232:                 foreach my $key (keys(%{$storehash})) {
                   10233:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10234:                 }
                   10235:                 $namevalue=~s/\&$//;
1.1224    raeburn  10236:                 unless ($namespace eq 'courserequests') {
                   10237:                     $datakey = &escape($datakey);
                   10238:                 }
1.1105    raeburn  10239:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10240:                                   $namevalue,$uhome);
1.1013    raeburn  10241:             }
                   10242:         } else {
                   10243:             $result = 'error: data to store was not a hash reference'; 
                   10244:         }
                   10245:     } else {
                   10246:         $result= 'error: invalid requestkey'; 
                   10247:     }
                   10248:     return $result;
                   10249: }
                   10250: 
1.21      www      10251: # ---------------------------------------------------------- Assign Custom Role
                   10252: 
                   10253: sub assigncustomrole {
1.957     raeburn  10254:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10255:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10256:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10257: }
                   10258: 
                   10259: # ----------------------------------------------------------------- Revoke Role
                   10260: 
                   10261: sub revokerole {
1.957     raeburn  10262:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10263:     my $now=time;
1.965     raeburn  10264:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10265: }
                   10266: 
                   10267: # ---------------------------------------------------------- Revoke Custom Role
                   10268: 
                   10269: sub revokecustomrole {
1.957     raeburn  10270:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10271:     my $now=time;
1.357     www      10272:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10273:            $deleteflag,$selfenroll,$context);
1.17      www      10274: }
                   10275: 
1.533     banghart 10276: # ------------------------------------------------------------ Disk usage
1.535     albertel 10277: sub diskusage {
1.955     raeburn  10278:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10279:     $directorypath =~ s/\/$//;
                   10280:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10281:                        .&escape($getpropath).':'.&escape($uname).':'
                   10282:                        .&escape($udom),homeserver($uname,$udom));
                   10283:     if ($listing eq 'unknown_cmd') {
                   10284:         if ($getpropath) {
                   10285:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10286:         }
                   10287:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10288:     }
1.514     albertel 10289:     return $listing;
1.512     banghart 10290: }
                   10291: 
1.566     banghart 10292: sub is_locked {
1.1096    raeburn  10293:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10294:     my @check;
                   10295:     my $is_locked;
1.1093    raeburn  10296:     push (@check,$file_name);
1.613     albertel 10297:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10298: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10299:     my ($tmp)=keys(%locked);
                   10300:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10301:     
1.566     banghart 10302:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10303:         $is_locked = 'false';
                   10304:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10305:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10306:                $is_locked = 'true';
1.1096    raeburn  10307:                if (ref($which) eq 'ARRAY') {
                   10308:                    push(@{$which},$entry);
                   10309:                } else {
                   10310:                    last;
                   10311:                }
1.745     raeburn  10312:            }
                   10313:        }
1.566     banghart 10314:     } else {
                   10315:         $is_locked = 'false';
                   10316:     }
1.1093    raeburn  10317:     return $is_locked;
1.566     banghart 10318: }
                   10319: 
1.759     albertel 10320: sub declutter_portfile {
                   10321:     my ($file) = @_;
1.833     albertel 10322:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10323:     return $file;
                   10324: }
                   10325: 
1.559     banghart 10326: # ------------------------------------------------------------- Mark as Read Only
                   10327: 
                   10328: sub mark_as_readonly {
                   10329:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10330:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10331:     my ($tmp)=keys(%current_permissions);
                   10332:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10333:     foreach my $file (@{$files}) {
1.759     albertel 10334: 	$file = &declutter_portfile($file);
1.561     banghart 10335:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10336:     }
1.613     albertel 10337:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10338:     return;
                   10339: }
                   10340: 
1.572     banghart 10341: # ------------------------------------------------------------Save Selected Files
                   10342: 
                   10343: sub save_selected_files {
                   10344:     my ($user, $path, @files) = @_;
                   10345:     my $filename = $user."savedfiles";
1.573     banghart 10346:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10347:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10348:     foreach my $file (@files) {
1.620     albertel 10349:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10350:     }
                   10351:     foreach my $file (@other_files) {
1.574     banghart 10352:         print (OUT $file."\n");
1.572     banghart 10353:     }
1.574     banghart 10354:     close (OUT);
1.572     banghart 10355:     return 'ok';
                   10356: }
                   10357: 
1.574     banghart 10358: sub clear_selected_files {
                   10359:     my ($user) = @_;
                   10360:     my $filename = $user."savedfiles";
1.1359    raeburn  10361:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10362:     print (OUT undef);
                   10363:     close (OUT);
                   10364:     return ("ok");    
                   10365: }
                   10366: 
1.572     banghart 10367: sub files_in_path {
                   10368:     my ($user, $path) = @_;
                   10369:     my $filename = $user."savedfiles";
                   10370:     my %return_files;
1.1359    raeburn  10371:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10372:     while (my $line_in = <IN>) {
1.574     banghart 10373:         chomp ($line_in);
                   10374:         my @paths_and_file = split (m!/!, $line_in);
                   10375:         my $file_part = pop (@paths_and_file);
                   10376:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10377:         $path_part.='/';
                   10378:         my $path_and_file = $path_part.$file_part;
                   10379:         if ($path_part eq $path) {
                   10380:             $return_files{$file_part}= 'selected';
                   10381:         }
                   10382:     }
1.574     banghart 10383:     close (IN);
                   10384:     return (\%return_files);
1.572     banghart 10385: }
                   10386: 
                   10387: # called in portfolio select mode, to show files selected NOT in current directory
                   10388: sub files_not_in_path {
                   10389:     my ($user, $path) = @_;
                   10390:     my $filename = $user."savedfiles";
                   10391:     my @return_files;
                   10392:     my $path_part;
1.1359    raeburn  10393:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10394:     while (my $line = <IN>) {
1.572     banghart 10395:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10396:         my @paths_and_file = split(m|/|, $line);
                   10397:         my $file_part = pop(@paths_and_file);
                   10398:         chomp($file_part);
                   10399:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10400:         $path_part .= '/';
                   10401:         my $path_and_file = $path_part.$file_part;
                   10402:         if ($path_part ne $path) {
1.800     albertel 10403:             push(@return_files, ($path_and_file));
1.572     banghart 10404:         }
                   10405:     }
1.800     albertel 10406:     close(OUT);
1.574     banghart 10407:     return (@return_files);
1.572     banghart 10408: }
                   10409: 
1.1273    raeburn  10410: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10411:  
                   10412: sub portfiles_versioning {
                   10413:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10414:     my $portfolio_root = '/userfiles/portfolio';
                   10415:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10416:     foreach my $file (@{$portfiles}) {
                   10417:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10418:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10419:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10420:         my $getpropath = 1;
                   10421:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10422:                                              $stu_name,$getpropath);
                   10423:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10424:         my $new_answer = 
                   10425:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10426:         if ($new_answer ne 'problem getting file') {
                   10427:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10428:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10429:                               [$symb,$env{'request.course.id'},'graded']);
                   10430:         }
                   10431:     }
                   10432: }
                   10433: 
                   10434: sub get_next_version {
                   10435:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10436:     my $version;
                   10437:     if (ref($dir_list) eq 'ARRAY') {
                   10438:         foreach my $row (@{$dir_list}) {
                   10439:             my ($file) = split(/\&/,$row,2);
                   10440:             my ($file_name,$file_version,$file_ext) =
                   10441:                 &file_name_version_ext($file);
                   10442:             if (($file_name eq $answer_name) &&
                   10443:                 ($file_ext eq $answer_ext)) {
                   10444:                      # gets here if filename and extension match,
                   10445:                      # regardless of version
                   10446:                 if ($file_version ne '') {
                   10447:                     # a versioned file is found  so save it for later
                   10448:                     if ($file_version > $version) {
                   10449:                         $version = $file_version;
                   10450:                     }
                   10451:                 }
                   10452:             }
                   10453:         }
                   10454:     }
                   10455:     $version ++;
                   10456:     return($version);
                   10457: }
                   10458: 
                   10459: sub version_selected_portfile {
                   10460:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10461:     my ($answer_name,$answer_ver,$answer_ext) =
                   10462:         &file_name_version_ext($file_name);
                   10463:     my $new_answer;
                   10464:     $env{'form.copy'} =
                   10465:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10466:     if($env{'form.copy'} eq '-1') {
                   10467:         $new_answer = 'problem getting file';
                   10468:     } else {
                   10469:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10470:         my $copy_result = 
                   10471:             &finishuserfileupload($stu_name,$domain,'copy',
                   10472:                                   '/portfolio'.$directory.$new_answer);
                   10473:     }
                   10474:     undef($env{'form.copy'});
                   10475:     return ($new_answer);
                   10476: }
                   10477: 
                   10478: sub file_name_version_ext {
                   10479:     my ($file)=@_;
                   10480:     my @file_parts = split(/\./, $file);
                   10481:     my ($name,$version,$ext);
                   10482:     if (@file_parts > 1) {
                   10483:         $ext=pop(@file_parts);
                   10484:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10485:             $version=pop(@file_parts);
                   10486:         }
                   10487:         $name=join('.',@file_parts);
                   10488:     } else {
                   10489:         $name=join('.',@file_parts);
                   10490:     }
                   10491:     return($name,$version,$ext);
                   10492: }
                   10493: 
1.745     raeburn  10494: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10495: 
1.745     raeburn  10496: sub get_portfile_permissions {
                   10497:     my ($domain,$user) = @_;
1.613     albertel 10498:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10499:     my ($tmp)=keys(%current_permissions);
                   10500:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10501:     return \%current_permissions;
                   10502: }
                   10503: 
                   10504: #---------------------------------------------Get portfolio file access controls
                   10505: 
1.749     raeburn  10506: sub get_access_controls {
1.745     raeburn  10507:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10508:     my %access;
                   10509:     my $real_file = $file;
                   10510:     $file =~ s/\.meta$//;
1.745     raeburn  10511:     if (defined($file)) {
1.749     raeburn  10512:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10513:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10514:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10515:             }
                   10516:         }
1.745     raeburn  10517:     } else {
1.749     raeburn  10518:         foreach my $key (keys(%{$current_permissions})) {
                   10519:             if ($key =~ /\0accesscontrol$/) {
                   10520:                 if (defined($group)) {
                   10521:                     if ($key !~ m-^\Q$group\E/-) {
                   10522:                         next;
                   10523:                     }
                   10524:                 }
                   10525:                 my ($fullpath) = split(/\0/,$key);
                   10526:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10527:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10528:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10529:                     }
                   10530:                 }
                   10531:             }
                   10532:         }
                   10533:     }
                   10534:     return %access;
                   10535: }
                   10536: 
                   10537: sub modify_access_controls {
                   10538:     my ($file_name,$changes,$domain,$user)=@_;
                   10539:     my ($outcome,$deloutcome);
                   10540:     my %store_permissions;
                   10541:     my %new_values;
                   10542:     my %new_control;
                   10543:     my %translation;
                   10544:     my @deletions = ();
                   10545:     my $now = time;
                   10546:     if (exists($$changes{'activate'})) {
                   10547:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10548:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10549:             my $numnew = scalar(@newitems);
                   10550:             for (my $i=0; $i<$numnew; $i++) {
                   10551:                 my $newkey = $newitems[$i];
                   10552:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10553:                 if ($newkey =~ /^\d+:/) { 
                   10554:                     $newkey =~ s/^(\d+)/$newid/;
                   10555:                     $translation{$1} = $newid;
                   10556:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10557:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10558:                     $translation{$1} = $newid;
                   10559:                 }
1.749     raeburn  10560:                 $new_values{$file_name."\0".$newkey} = 
                   10561:                                           $$changes{'activate'}{$newitems[$i]};
                   10562:                 $new_control{$newkey} = $now;
                   10563:             }
                   10564:         }
                   10565:     }
                   10566:     my %todelete;
                   10567:     my %changed_items;
                   10568:     foreach my $action ('delete','update') {
                   10569:         if (exists($$changes{$action})) {
                   10570:             if (ref($$changes{$action}) eq 'HASH') {
                   10571:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10572:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10573:                     if ($action eq 'delete') { 
                   10574:                         $todelete{$itemnum} = 1;
                   10575:                     } else {
                   10576:                         $changed_items{$itemnum} = $key;
                   10577:                     }
                   10578:                 }
1.745     raeburn  10579:             }
                   10580:         }
1.749     raeburn  10581:     }
                   10582:     # get lock on access controls for file.
                   10583:     my $lockhash = {
                   10584:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10585:                                                        ':'.$env{'user.domain'},
                   10586:                    }; 
                   10587:     my $tries = 0;
                   10588:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10589:    
1.1288    damieng  10590:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10591:         $tries ++;
1.1289    damieng  10592:         sleep(0.1);
1.749     raeburn  10593:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10594:     }
                   10595:     if ($gotlock eq 'ok') {
                   10596:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10597:         my ($tmp)=keys(%curr_permissions);
                   10598:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10599:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10600:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10601:             if (ref($curr_controls) eq 'HASH') {
                   10602:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10603:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10604:                     if (defined($todelete{$itemnum})) {
                   10605:                         push(@deletions,$file_name."\0".$control_item);
                   10606:                     } else {
                   10607:                         if (defined($changed_items{$itemnum})) {
                   10608:                             $new_control{$changed_items{$itemnum}} = $now;
                   10609:                             push(@deletions,$file_name."\0".$control_item);
                   10610:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10611:                         } else {
                   10612:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10613:                         }
                   10614:                     }
1.745     raeburn  10615:                 }
                   10616:             }
                   10617:         }
1.970     raeburn  10618:         my ($group);
                   10619:         if (&is_course($domain,$user)) {
                   10620:             ($group,my $file) = split(/\//,$file_name,2);
                   10621:         }
1.749     raeburn  10622:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10623:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10624:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10625:         #  remove lock
                   10626:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10627:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10628:         my $sqlresult =
1.970     raeburn  10629:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10630:                                     $group);
1.749     raeburn  10631:     } else {
                   10632:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10633:     }
1.749     raeburn  10634:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10635: }
                   10636: 
1.827     raeburn  10637: sub make_public_indefinitely {
1.1271    raeburn  10638:     my (@requrl) = @_;
                   10639:     return &automated_portfile_access('public',\@requrl);
                   10640: }
                   10641: 
                   10642: sub automated_portfile_access {
                   10643:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10644:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10645:         return 'invalid';
                   10646:     }
1.1271    raeburn  10647:     my %urls;
                   10648:     if (ref($addsref) eq 'ARRAY') {
                   10649:         foreach my $requrl (@{$addsref}) {
                   10650:             if (&is_portfolio_url($requrl)) {
                   10651:                 unless (exists($urls{$requrl})) {
                   10652:                     $urls{$requrl} = 'add';
                   10653:                 }
                   10654:             }
                   10655:         }
                   10656:     }
                   10657:     if (ref($delsref) eq 'ARRAY') {
                   10658:         foreach my $requrl (@{$delsref}) { 
                   10659:             if (&is_portfolio_url($requrl)) {
                   10660:                 unless (exists($urls{$requrl})) {
                   10661:                     $urls{$requrl} = 'delete'; 
                   10662:                 }
                   10663:             }
                   10664:         }
                   10665:     }
                   10666:     unless (keys(%urls)) {
                   10667:         return 'invalid';
                   10668:     }
                   10669:     my $ip;
                   10670:     if ($accesstype eq 'ip') {
                   10671:         if (ref($info) eq 'HASH') {
                   10672:             if ($info->{'ip'} ne '') {
                   10673:                 $ip = $info->{'ip'};
                   10674:             }
                   10675:         }
                   10676:         if ($ip eq '') {
                   10677:             return 'invalid';
                   10678:         }
                   10679:     }
                   10680:     my $errors;
1.827     raeburn  10681:     my $now = time;
1.1271    raeburn  10682:     my %current_perms;
                   10683:     foreach my $requrl (sort(keys(%urls))) {
                   10684:         my $action;
                   10685:         if ($urls{$requrl} eq 'add') {
                   10686:             $action = 'activate';
                   10687:         } else {
                   10688:             $action = 'none';
                   10689:         }
                   10690:         my $aclnum = 0;
1.827     raeburn  10691:         my (undef,$udom,$unum,$file_name,$group) =
                   10692:             &parse_portfolio_url($requrl);
1.1271    raeburn  10693:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10694:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10695:         }
                   10696:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10697:                                                    $group,$file_name);
                   10698:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10699:             my ($num,$scope,$end,$start) = 
                   10700:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10701:             if ($scope eq $accesstype) {
                   10702:                 if (($start <= $now) && ($end == 0)) {
                   10703:                     if ($accesstype eq 'ip') {
                   10704:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10705:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10706:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10707:                                     if ($urls{$requrl} eq 'add') {
                   10708:                                         $action = 'none';
                   10709:                                         last;
                   10710:                                     } else {
                   10711:                                         $action = 'delete';
                   10712:                                         $aclnum = $num;
                   10713:                                         last;
                   10714:                                     }
                   10715:                                 }
                   10716:                             }
                   10717:                         }
                   10718:                     } elsif ($accesstype eq 'public') {
                   10719:                         if ($urls{$requrl} eq 'add') {
                   10720:                             $action = 'none';
                   10721:                             last;
                   10722:                         } else {
                   10723:                             $action = 'delete';
                   10724:                             $aclnum = $num;
                   10725:                             last;
                   10726:                         }
                   10727:                     }
                   10728:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10729:                     $action = 'update';
                   10730:                     $aclnum = $num;
1.1271    raeburn  10731:                     last;
1.827     raeburn  10732:                 }
                   10733:             }
                   10734:         }
                   10735:         if ($action eq 'none') {
1.1271    raeburn  10736:             next;
1.827     raeburn  10737:         } else {
                   10738:             my %changes;
                   10739:             my $newend = 0;
                   10740:             my $newstart = $now;
1.1271    raeburn  10741:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10742:             $changes{$action}{$newkey} = {
1.1271    raeburn  10743:                 type => $accesstype,
1.827     raeburn  10744:                 time => {
                   10745:                     start => $newstart,
                   10746:                     end   => $newend,
                   10747:                 },
                   10748:             };
1.1271    raeburn  10749:             if ($accesstype eq 'ip') {
                   10750:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10751:             }
1.827     raeburn  10752:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10753:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10754:             unless ($outcome eq 'ok') {
                   10755:                 $errors .= $outcome.' ';
                   10756:             }
1.827     raeburn  10757:         }
1.1271    raeburn  10758:     }
                   10759:     if ($errors) {
                   10760:         $errors =~ s/\s$//;
                   10761:         return $errors;
1.827     raeburn  10762:     } else {
1.1271    raeburn  10763:         return 'ok';
1.827     raeburn  10764:     }
                   10765: }
                   10766: 
1.745     raeburn  10767: #------------------------------------------------------Get Marked as Read Only
                   10768: 
                   10769: sub get_marked_as_readonly {
                   10770:     my ($domain,$user,$what,$group) = @_;
                   10771:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10772:     my @readonly_files;
1.629     banghart 10773:     my $cmp1=$what;
                   10774:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10775:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10776:         if (defined($group)) {
                   10777:             if ($file_name !~ m-^\Q$group\E/-) {
                   10778:                 next;
                   10779:             }
                   10780:         }
1.561     banghart 10781:         if (ref($value) eq "ARRAY"){
                   10782:             foreach my $stored_what (@{$value}) {
1.629     banghart 10783:                 my $cmp2=$stored_what;
1.759     albertel 10784:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10785:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10786:                 }
1.629     banghart 10787:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10788:                     push(@readonly_files, $file_name);
1.745     raeburn  10789:                     last;
1.563     banghart 10790:                 } elsif (!defined($what)) {
                   10791:                     push(@readonly_files, $file_name);
1.745     raeburn  10792:                     last;
1.561     banghart 10793:                 }
                   10794:             }
1.745     raeburn  10795:         }
1.561     banghart 10796:     }
                   10797:     return @readonly_files;
                   10798: }
1.577     banghart 10799: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10800: 
1.577     banghart 10801: sub get_marked_as_readonly_hash {
1.745     raeburn  10802:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10803:     my %readonly_files;
1.745     raeburn  10804:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10805:         if (defined($group)) {
                   10806:             if ($file_name !~ m-^\Q$group\E/-) {
                   10807:                 next;
                   10808:             }
                   10809:         }
1.577     banghart 10810:         if (ref($value) eq "ARRAY"){
                   10811:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10812:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10813:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10814:                         if ($lock_descriptor eq 'graded') {
                   10815:                             $readonly_files{$file_name} = 'graded';
                   10816:                         } elsif ($lock_descriptor eq 'handback') {
                   10817:                             $readonly_files{$file_name} = 'handback';
                   10818:                         } else {
                   10819:                             if (!exists($readonly_files{$file_name})) {
                   10820:                                 $readonly_files{$file_name} = 'locked';
                   10821:                             }
                   10822:                         }
1.745     raeburn  10823:                     }
1.750     banghart 10824:                 } 
1.577     banghart 10825:             }
                   10826:         } 
                   10827:     }
                   10828:     return %readonly_files;
                   10829: }
1.559     banghart 10830: # ------------------------------------------------------------ Unmark as Read Only
                   10831: 
                   10832: sub unmark_as_readonly {
1.629     banghart 10833:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10834:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10835:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10836:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10837:     my $symb_crs = $what;
                   10838:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10839:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10840:     my ($tmp)=keys(%current_permissions);
                   10841:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10842:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10843:     foreach my $file (@readonly_files) {
1.759     albertel 10844: 	my $clean_file = &declutter_portfile($file);
                   10845: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10846: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10847:         my @new_locks;
                   10848:         my @del_keys;
                   10849:         if (ref($current_locks) eq "ARRAY"){
                   10850:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10851:                 my $compare=$locker;
1.749     raeburn  10852:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10853:                     $compare=join('',@{$locker});
1.746     raeburn  10854:                     if ($compare ne $symb_crs) {
                   10855:                         push(@new_locks, $locker);
                   10856:                     }
1.563     banghart 10857:                 }
                   10858:             }
1.650     albertel 10859:             if (scalar(@new_locks) > 0) {
1.563     banghart 10860:                 $current_permissions{$file} = \@new_locks;
                   10861:             } else {
                   10862:                 push(@del_keys, $file);
1.613     albertel 10863:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10864:                 delete($current_permissions{$file});
1.563     banghart 10865:             }
                   10866:         }
1.561     banghart 10867:     }
1.613     albertel 10868:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10869:     return;
                   10870: }
1.512     banghart 10871: 
1.17      www      10872: # ------------------------------------------------------------ Directory lister
                   10873: 
                   10874: sub dirlist {
1.955     raeburn  10875:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10876:     $uri=~s/^\///;
                   10877:     $uri=~s/\/$//;
1.253     stredwic 10878:     my ($udom, $uname);
1.955     raeburn  10879:     if ($getuserdir) {
1.253     stredwic 10880:         $udom = $userdomain;
                   10881:         $uname = $username;
1.955     raeburn  10882:     } else {
                   10883:         (undef,$udom,$uname)=split(/\//,$uri);
                   10884:         if(defined($userdomain)) {
                   10885:             $udom = $userdomain;
                   10886:         }
                   10887:         if(defined($username)) {
                   10888:             $uname = $username;
                   10889:         }
1.253     stredwic 10890:     }
1.955     raeburn  10891:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10892: 
1.955     raeburn  10893:     $dirRoot = $perlvar{'lonDocRoot'};
                   10894:     if (defined($getpropath)) {
                   10895:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10896:         $dirRoot =~ s/\/$//;
1.955     raeburn  10897:     } elsif (defined($getuserdir)) {
                   10898:         my $subdir=$uname.'__';
                   10899:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10900:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10901:                    ."/$udom/$subdir/$uname";
                   10902:     } elsif (defined($alternateRoot)) {
                   10903:         $dirRoot = $alternateRoot;
1.751     banghart 10904:     }
1.253     stredwic 10905: 
                   10906:     if($udom) {
                   10907:         if($uname) {
1.1135    raeburn  10908:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10909:             if ($uhome eq 'no_host') {
                   10910:                 return ([],'no_host');
                   10911:             }
1.955     raeburn  10912:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10913:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10914:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10915:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10916:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10917:             } else {
                   10918:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10919:             }
1.605     matthew  10920:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10921:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10922:                 @listing_results = split(/:/,$listing);
                   10923:             } else {
                   10924:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10925:             }
1.1135    raeburn  10926:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10927:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10928:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10929:                 return ([],$listing);
                   10930:             } else {
                   10931:                 return (\@listing_results);
1.1135    raeburn  10932:             }
1.955     raeburn  10933:         } elsif(!$alternateRoot) {
1.1136    raeburn  10934:             my (%allusers,%listerror);
1.841     albertel 10935: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10936:  	    foreach my $tryserver (keys(%servers)) {
                   10937:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10938:                                   &escape($udom),$tryserver);
                   10939:                 if ($listing eq 'unknown_cmd') {
                   10940: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10941: 				      $udom, $tryserver);
                   10942:                 } else {
                   10943:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10944:                 }
1.841     albertel 10945: 		if ($listing eq 'unknown_cmd') {
                   10946: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10947: 				      $udom, $tryserver);
                   10948: 		    @listing_results = split(/:/,$listing);
                   10949: 		} else {
                   10950: 		    @listing_results =
                   10951: 			map { &unescape($_); } split(/:/,$listing);
                   10952: 		}
1.1136    raeburn  10953:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10954:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10955:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10956:                     $listerror{$tryserver} = $listing;
                   10957:                 } else {
1.841     albertel 10958: 		    foreach my $line (@listing_results) {
                   10959: 			my ($entry) = split(/&/,$line,2);
                   10960: 			$allusers{$entry} = 1;
                   10961: 		    }
                   10962: 		}
1.253     stredwic 10963:             }
1.1136    raeburn  10964:             my @alluserslist=();
1.800     albertel 10965:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10966:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10967:             }
1.1318    droeschl 10968: 
                   10969:             if (!%listerror) {
                   10970:                 # no errors
                   10971:                 return (\@alluserslist);
                   10972:             } elsif (scalar(keys(%servers)) == 1) {
                   10973:                 # one library server, one error 
                   10974:                 my ($key) = keys(%listerror);
                   10975:                 return (\@alluserslist, $listerror{$key});
                   10976:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10977:                 # con_lost indicates that we might miss data from at least one
                   10978:                 # library server
                   10979:                 return (\@alluserslist, 'con_lost');
                   10980:             } else {
                   10981:                 # multiple library servers and no con_lost -> data should be
                   10982:                 # complete. 
                   10983:                 return (\@alluserslist);
                   10984:             }
                   10985: 
1.253     stredwic 10986:         } else {
1.1136    raeburn  10987:             return ([],'missing username');
1.253     stredwic 10988:         }
1.955     raeburn  10989:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10990:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10991:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10992:         return (\@all_domains);
1.955     raeburn  10993:     } else {
1.1136    raeburn  10994:         return ([],'missing domain');
1.275     stredwic 10995:     }
                   10996: }
                   10997: 
                   10998: # --------------------------------------------- GetFileTimestamp
                   10999: # This function utilizes dirlist and returns the date stamp for
                   11000: # when it was last modified.  It will also return an error of -1
                   11001: # if an error occurs
                   11002: 
                   11003: sub GetFileTimestamp {
1.955     raeburn  11004:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11005:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11006:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11007:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11008:                                     undef,$getuserdir);
                   11009:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11010:         return -1;
                   11011:     }
                   11012:     if (ref($fileref) eq 'ARRAY') {
                   11013:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11014:         # @stats contains first the filename, then the stat output
                   11015:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11016:     } else {
                   11017:         return -1;
1.253     stredwic 11018:     }
1.26      www      11019: }
                   11020: 
1.712     albertel 11021: sub stat_file {
                   11022:     my ($uri) = @_;
1.787     albertel 11023:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11024: 
1.955     raeburn  11025:     my ($udom,$uname,$file);
1.712     albertel 11026:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11027: 	($udom,$uname,$file) =
1.811     albertel 11028: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11029: 	$file = 'userfiles/'.$file;
                   11030:     }
                   11031:     if ($uri =~ m-^/res/-) {
                   11032: 	($udom,$uname) = 
1.807     albertel 11033: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11034: 	$file = $uri;
                   11035:     }
                   11036: 
                   11037:     if (!$udom || !$uname || !$file) {
                   11038: 	# unable to handle the uri
                   11039: 	return ();
                   11040:     }
1.956     raeburn  11041:     my $getpropath;
                   11042:     if ($file =~ /^userfiles\//) {
                   11043:         $getpropath = 1;
                   11044:     }
1.1136    raeburn  11045:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11046:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11047:         return ();
                   11048:     } else {
                   11049:         if (ref($listref) eq 'ARRAY') {
                   11050:             my @stats = split('&',$listref->[0]);
                   11051: 	    shift(@stats); #filename is first
                   11052: 	    return @stats;
                   11053:         }
1.712     albertel 11054:     }
                   11055:     return ();
                   11056: }
                   11057: 
1.1313    raeburn  11058: # --------------------------------------------------------- recursedirs
                   11059: # Recursive function to traverse either a specific user's Authoring Space
                   11060: # or corresponding Published Resource Space, and populate the hash ref:
                   11061: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11062: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11063: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11064: # files in Authoring Space.
                   11065: #
                   11066: # Inputs:
                   11067: #
                   11068: # $is_home - true if current server is home server for user's space
                   11069: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11070: # $docroot - Document root (i.e., /home/httpd/html
                   11071: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11072: # $relpath - Current path (relative to top level).
                   11073: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11074: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11075: #
                   11076: # Returns: nothing
                   11077: #
                   11078: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11079: #
                   11080: # Currently used by interface/londocs.pm to create linked select boxes for
                   11081: # directory and filename to import a Course "Author" resource into a course, and
                   11082: # also to create linked select boxes for Authoring Space and Directory to choose
                   11083: # save location for creation of a new "standard" problem from the Course Editor.
                   11084: #
                   11085: 
                   11086: sub recursedirs {
                   11087:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11088:     return unless (ref($dirhashref) eq 'HASH');
                   11089:     my $currpath = $docroot.$toppath;
                   11090:     if ($relpath) {
                   11091:         $currpath .= "/$relpath";
                   11092:     }
                   11093:     my $savefile;
                   11094:     if (ref($filehashref)) {
                   11095:         $savefile = 1;
                   11096:     }
                   11097:     if ($is_home) {
                   11098:         if (opendir(my $dirh,$currpath)) {
                   11099:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11100:                 next if ($item eq '');
                   11101:                 if (-d "$currpath/$item") {
                   11102:                     my $newpath;
                   11103:                     if ($relpath) {
                   11104:                         $newpath = "$relpath/$item";
                   11105:                     } else {
                   11106:                         $newpath = $item;
                   11107:                     }
                   11108:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11109:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11110:                 } elsif ($savefile) {
                   11111:                     if ($context eq 'priv') {
                   11112:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11113:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11114:                         }
                   11115:                     } else {
                   11116:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11117:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11118:                         }
                   11119:                     }
                   11120:                 }
                   11121:             }
                   11122:             closedir($dirh);
                   11123:         }
                   11124:     } else {
                   11125:         my ($dirlistref,$listerror) =
                   11126:             &dirlist($toppath.$relpath);
                   11127:         my @dir_lines;
                   11128:         my $dirptr=16384;
                   11129:         if (ref($dirlistref) eq 'ARRAY') {
                   11130:             foreach my $dir_line (sort
                   11131:                               {
                   11132:                                   my ($afile)=split('&',$a,2);
                   11133:                                   my ($bfile)=split('&',$b,2);
                   11134:                                   return (lc($afile) cmp lc($bfile));
                   11135:                               } (@{$dirlistref})) {
                   11136:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11137:                     split(/\&/,$dir_line,16);
                   11138:                 $item =~ s/\s+$//;
                   11139:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11140:                 if ($dirptr&$testdir) {
                   11141:                     my $newpath;
                   11142:                     if ($relpath) {
                   11143:                         $newpath = "$relpath/$item";
                   11144:                     } else {
                   11145:                         $relpath = '/';
                   11146:                         $newpath = $item;
                   11147:                     }
                   11148:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11149:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11150:                 } elsif ($savefile) {
                   11151:                     if ($context eq 'priv') {
                   11152:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11153:                             $filehashref->{$relpath}{$item} = 1;
                   11154:                         }
                   11155:                     } else {
                   11156:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11157:                             $filehashref->{$relpath}{$item} = 1;
                   11158:                         }
                   11159:                     }
                   11160:                 }
                   11161:             }
                   11162:         }
                   11163:     }
                   11164:     return;
                   11165: }
                   11166: 
1.26      www      11167: # -------------------------------------------------------- Value of a Condition
                   11168: 
1.713     albertel 11169: # gets the value of a specific preevaluated condition
                   11170: #    stored in the string  $env{user.state.<cid>}
                   11171: # or looks up a condition reference in the bighash and if if hasn't
                   11172: # already been evaluated recurses into docondval to get the value of
                   11173: # the condition, then memoizing it to 
                   11174: #   $env{user.state.<cid>.<condition>}
1.40      www      11175: sub directcondval {
                   11176:     my $number=shift;
1.620     albertel 11177:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11178: 	&Apache::lonuserstate::evalstate();
                   11179:     }
1.713     albertel 11180:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11181: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11182:     } elsif ($number =~ /^_/) {
                   11183: 	my $sub_condition;
                   11184: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11185: 		&GDBM_READER(),0640)) {
                   11186: 	    $sub_condition=$bighash{'conditions'.$number};
                   11187: 	    untie(%bighash);
                   11188: 	}
                   11189: 	my $value = &docondval($sub_condition);
1.949     raeburn  11190: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11191: 	return $value;
                   11192:     }
1.620     albertel 11193:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11194:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11195:     } else {
                   11196:        return 2;
                   11197:     }
                   11198: }
                   11199: 
1.713     albertel 11200: # get the collection of conditions for this resource
1.26      www      11201: sub condval {
                   11202:     my $condidx=shift;
1.54      www      11203:     my $allpathcond='';
1.713     albertel 11204:     foreach my $cond (split(/\|/,$condidx)) {
                   11205: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11206: 	    $allpathcond.=
                   11207: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11208: 	}
1.191     harris41 11209:     }
1.54      www      11210:     $allpathcond=~s/\|$//;
1.713     albertel 11211:     return &docondval($allpathcond);
                   11212: }
                   11213: 
                   11214: #evaluates an expression of conditions
                   11215: sub docondval {
                   11216:     my ($allpathcond) = @_;
                   11217:     my $result=0;
                   11218:     if ($env{'request.course.id'}
                   11219: 	&& defined($allpathcond)) {
                   11220: 	my $operand='|';
                   11221: 	my @stack;
                   11222: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11223: 	    if ($chunk eq '(') {
                   11224: 		push @stack,($operand,$result);
                   11225: 	    } elsif ($chunk eq ')') {
                   11226: 		my $before=pop @stack;
                   11227: 		if (pop @stack eq '&') {
                   11228: 		    $result=$result>$before?$before:$result;
                   11229: 		} else {
                   11230: 		    $result=$result>$before?$result:$before;
                   11231: 		}
                   11232: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11233: 		$operand=$chunk;
                   11234: 	    } else {
                   11235: 		my $new=directcondval($chunk);
                   11236: 		if ($operand eq '&') {
                   11237: 		    $result=$result>$new?$new:$result;
                   11238: 		} else {
                   11239: 		    $result=$result>$new?$result:$new;
                   11240: 		}
                   11241: 	    }
                   11242: 	}
1.26      www      11243:     }
                   11244:     return $result;
1.421     albertel 11245: }
                   11246: 
                   11247: # ---------------------------------------------------- Devalidate courseresdata
                   11248: 
                   11249: sub devalidatecourseresdata {
                   11250:     my ($coursenum,$coursedomain)=@_;
                   11251:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11252:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11253: }
                   11254: 
1.763     www      11255: 
1.200     www      11256: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11257: #
                   11258: #  Parameters:
                   11259: #      $coursenum    - Number of the course.
                   11260: #      $coursedomain - Domain at which the course was created.
                   11261: #  Returns:
                   11262: #     A hash of the course parameters along (I think) with timestamps
                   11263: #     and version info.
1.877     foxr     11264: 
1.624     albertel 11265: sub get_courseresdata {
                   11266:     my ($coursenum,$coursedomain)=@_;
1.200     www      11267:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11268:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11269:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11270:     my %dumpreply;
1.417     albertel 11271:     unless (defined($cached)) {
1.624     albertel 11272: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11273: 	$result=\%dumpreply;
1.251     albertel 11274: 	my ($tmp) = keys(%dumpreply);
                   11275: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11276: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11277: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11278: 	    return $tmp;
1.416     albertel 11279: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11280: 	    $result=undef;
1.599     albertel 11281: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11282: 	}
                   11283:     }
1.624     albertel 11284:     return $result;
                   11285: }
                   11286: 
1.633     albertel 11287: sub devalidateuserresdata {
                   11288:     my ($uname,$udom)=@_;
                   11289:     my $hashid="$udom:$uname";
                   11290:     &devalidate_cache_new('userres',$hashid);
                   11291: }
                   11292: 
1.624     albertel 11293: sub get_userresdata {
                   11294:     my ($uname,$udom)=@_;
                   11295:     #most student don\'t have any data set, check if there is some data
                   11296:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11297: 
                   11298:     my $hashid="$udom:$uname";
                   11299:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11300:     if (!defined($cached)) {
                   11301: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11302: 	$result=\%resourcedata;
                   11303: 	&do_cache_new('userres',$hashid,$result,600);
                   11304:     }
                   11305:     my ($tmp)=keys(%$result);
                   11306:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11307: 	return $result;
                   11308:     }
                   11309:     #error 2 occurs when the .db doesn't exist
                   11310:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11311:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11312: 	    &logthis("<font color=\"blue\">WARNING:".
                   11313: 		     " Trying to get resource data for ".
                   11314: 		     $uname." at ".$udom.": ".
                   11315: 		     $tmp."</font>");
                   11316:         }
1.624     albertel 11317:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11318: 	#&EXT_cache_set($udom,$uname);
                   11319: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11320: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11321:     }
                   11322:     return $tmp;
                   11323: }
1.879     foxr     11324: #----------------------------------------------- resdata - return resource data
                   11325: #  Purpose:
                   11326: #    Return resource data for either users or for a course.
                   11327: #  Parameters:
                   11328: #     $name      - Course/user name.
                   11329: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11330: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11331: #     $mapp      - decluttered URL of enclosing map  
                   11332: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11333: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11334: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11335: #     $courseid  - CourseID (first part of param identifier).
                   11336: #     $modifier  - Middle part of param identifier.
                   11337: #     $what      - Last part of param identifier.
1.879     foxr     11338: #     @which     - Array of names of resources desired.
                   11339: #  Returns:
                   11340: #     The value of the first reasource in @which that is found in the
                   11341: #     resource hash.
                   11342: #  Exceptional Conditions:
                   11343: #     If the $type passed in is not valid (not the string 'course' or 
                   11344: #     'user', an undefined  reference is returned.
                   11345: #     If none of the resources are found, an undef is returned
1.624     albertel 11346: sub resdata {
1.1301    raeburn  11347:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11348:         $modifier,$what,@which)=@_;
1.624     albertel 11349:     my $result;
                   11350:     if ($type eq 'course') {
                   11351: 	$result=&get_courseresdata($name,$domain);
                   11352:     } elsif ($type eq 'user') {
                   11353: 	$result=&get_userresdata($name,$domain);
                   11354:     }
                   11355:     if (!ref($result)) { return $result; }    
1.251     albertel 11356:     foreach my $item (@which) {
1.1301    raeburn  11357:         if ($item->[1] eq 'course') {
                   11358:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11359:                 unless ($$recursed) {
1.1302    raeburn  11360:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11361:                     $$recursed = 1;
                   11362:                 }
                   11363:                 foreach my $item (@${recurseup}) {
                   11364:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11365:                     last if (defined($result->{$norecursechk}));
                   11366:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11367:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11368:                 }
                   11369:             }
                   11370:         }
                   11371:         if (defined($result->{$item->[0]})) {
1.927     albertel 11372: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11373: 	}
1.250     albertel 11374:     }
1.291     albertel 11375:     return undef;
1.200     www      11376: }
                   11377: 
1.1360    raeburn  11378: sub get_domain_lti {
                   11379:     my ($cdom,$context) = @_;
                   11380:     my ($name,%lti);
                   11381:     if ($context eq 'consumer') {
                   11382:         $name = 'ltitools';
                   11383:     } elsif ($context eq 'provider') {
                   11384:         $name = 'lti';
                   11385:     } else {
                   11386:         return %lti;
                   11387:     }
                   11388:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11389:     if (defined($cached)) {
                   11390:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11391:             %lti = %{$result};
1.1298    raeburn  11392:         }
                   11393:     } else {
1.1360    raeburn  11394:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11395:         if (ref($domconfig{$name}) eq 'HASH') {
                   11396:             %lti = %{$domconfig{$name}};
                   11397:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11398:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11399:                 foreach my $id (keys(%lti)) {
                   11400:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11401:                         foreach my $item ('key','secret') {
1.1360    raeburn  11402:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11403:                         }
                   11404:                     }
                   11405:                 }
                   11406:             }
1.1298    raeburn  11407:         }
                   11408:         my $cachetime = 24*60*60;
1.1360    raeburn  11409:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11410:     }
1.1360    raeburn  11411:     return %lti;
1.1298    raeburn  11412: }
                   11413: 
1.1236    raeburn  11414: sub get_numsuppfiles {
                   11415:     my ($cnum,$cdom,$ignorecache)=@_;
                   11416:     my $hashid=$cnum.':'.$cdom;
                   11417:     my ($suppcount,$cached);
                   11418:     unless ($ignorecache) {
                   11419:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11420:     }
                   11421:     unless (defined($cached)) {
                   11422:         my $chome=&homeserver($cnum,$cdom);
                   11423:         unless ($chome eq 'no_host') {
1.1366    raeburn  11424:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11425:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11426:             ($suppcount,$supptools,$errors) =
                   11427:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11428:                                                          $supptools,$errors);
1.1236    raeburn  11429:         }
                   11430:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11431:     }
                   11432:     return $suppcount;
                   11433: }
                   11434: 
1.379     matthew  11435: #
                   11436: # EXT resource caching routines
                   11437: #
                   11438: 
1.1302    raeburn  11439: {
                   11440: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11441: #
                   11442: # The course for which we cache
                   11443: my $cachedmapkey='';
                   11444: # The cached recursive maps for this course
                   11445: my %cachedmaps=();
                   11446: # When this was last done
                   11447: my $cachedmaptime='';
                   11448: 
1.379     matthew  11449: sub clear_EXT_cache_status {
1.383     albertel 11450:     &delenv('cache.EXT.');
1.379     matthew  11451: }
                   11452: 
                   11453: sub EXT_cache_status {
                   11454:     my ($target_domain,$target_user) = @_;
1.383     albertel 11455:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11456:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11457:         # We know already the user has no data
                   11458:         return 1;
                   11459:     } else {
                   11460:         return 0;
                   11461:     }
                   11462: }
                   11463: 
                   11464: sub EXT_cache_set {
                   11465:     my ($target_domain,$target_user) = @_;
1.383     albertel 11466:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11467:     #&appenv({$cachename => time});
1.379     matthew  11468: }
                   11469: 
1.28      www      11470: # --------------------------------------------------------- Value of a Variable
1.58      www      11471: sub EXT {
1.715     albertel 11472: 
1.1228    raeburn  11473:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11474:     unless ($varname) { return ''; }
1.218     albertel 11475:     #get real user name/domain, courseid and symb
                   11476:     my $courseid;
1.359     albertel 11477:     my $publicuser;
1.427     www      11478:     if ($symbparm) {
                   11479: 	$symbparm=&get_symb_from_alias($symbparm);
                   11480:     }
1.218     albertel 11481:     if (!($uname && $udom)) {
1.790     albertel 11482:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11483:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11484:     } else {
1.620     albertel 11485: 	$courseid=$env{'request.course.id'};
1.218     albertel 11486:     }
1.48      www      11487:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11488:     my $rest;
1.320     albertel 11489:     if (defined($therest[0])) {
1.48      www      11490:        $rest=join('.',@therest);
                   11491:     } else {
                   11492:        $rest='';
                   11493:     }
1.320     albertel 11494: 
1.57      www      11495:     my $qualifierrest=$qualifier;
                   11496:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11497:     my $spacequalifierrest=$space;
                   11498:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11499:     if ($realm eq 'user') {
1.48      www      11500: # --------------------------------------------------------------- user.resource
                   11501: 	if ($space eq 'resource') {
1.651     albertel 11502: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11503: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11504: 		 &&
1.744     albertel 11505: 		 ($symbparm eq &symbread()) ) {	
                   11506: 		# if we are in the middle of processing the resource the
                   11507: 		# get the value we are planning on committing
                   11508:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11509:                     return $Apache::lonhomework::results{$qualifierrest};
                   11510:                 } else {
                   11511:                     return $Apache::lonhomework::history{$qualifierrest};
                   11512:                 }
1.335     albertel 11513: 	    } else {
1.359     albertel 11514: 		my %restored;
1.620     albertel 11515: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11516: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11517: 		} else {
                   11518: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11519: 		}
1.335     albertel 11520: 		return $restored{$qualifierrest};
                   11521: 	    }
1.48      www      11522: # ----------------------------------------------------------------- user.access
                   11523:         } elsif ($space eq 'access') {
1.218     albertel 11524: 	    # FIXME - not supporting calls for a specific user
1.48      www      11525:             return &allowed($qualifier,$rest);
                   11526: # ------------------------------------------ user.preferences, user.environment
                   11527:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11528: 	    if (($uname eq $env{'user.name'}) &&
                   11529: 		($udom eq $env{'user.domain'})) {
                   11530: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11531: 	    } else {
1.359     albertel 11532: 		my %returnhash;
                   11533: 		if (!$publicuser) {
                   11534: 		    %returnhash=&userenvironment($udom,$uname,
                   11535: 						 $qualifierrest);
                   11536: 		}
1.218     albertel 11537: 		return $returnhash{$qualifierrest};
                   11538: 	    }
1.48      www      11539: # ----------------------------------------------------------------- user.course
                   11540:         } elsif ($space eq 'course') {
1.218     albertel 11541: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11542:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11543: # ------------------------------------------------------------------- user.role
                   11544:         } elsif ($space eq 'role') {
1.218     albertel 11545: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11546:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11547:             if ($qualifier eq 'value') {
                   11548: 		return $role;
                   11549:             } elsif ($qualifier eq 'extent') {
                   11550:                 return $where;
                   11551:             }
                   11552: # ----------------------------------------------------------------- user.domain
                   11553:         } elsif ($space eq 'domain') {
1.218     albertel 11554:             return $udom;
1.48      www      11555: # ------------------------------------------------------------------- user.name
                   11556:         } elsif ($space eq 'name') {
1.218     albertel 11557:             return $uname;
1.48      www      11558: # ---------------------------------------------------- Any other user namespace
1.29      www      11559:         } else {
1.359     albertel 11560: 	    my %reply;
                   11561: 	    if (!$publicuser) {
                   11562: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11563: 	    }
                   11564: 	    return $reply{$qualifierrest};
1.48      www      11565:         }
1.236     www      11566:     } elsif ($realm eq 'query') {
                   11567: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11568:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11569: 						[$spacequalifierrest]);
1.620     albertel 11570: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11571:    } elsif ($realm eq 'request') {
1.48      www      11572: # ------------------------------------------------------------- request.browser
                   11573:         if ($space eq 'browser') {
1.1145    bisitz   11574:             return $env{'browser.'.$qualifier};
1.57      www      11575: # ------------------------------------------------------------ request.filename
                   11576:         } else {
1.620     albertel 11577:             return $env{'request.'.$spacequalifierrest};
1.29      www      11578:         }
1.28      www      11579:     } elsif ($realm eq 'course') {
1.48      www      11580: # ---------------------------------------------------------- course.description
1.620     albertel 11581:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11582:     } elsif ($realm eq 'resource') {
1.165     www      11583: 
1.620     albertel 11584: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11585: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11586: 	}
1.693     albertel 11587: 
1.1232    raeburn  11588:         if ($qualifier eq '') {
                   11589: 	    if ($space eq 'title') {
                   11590: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11591: 	        return &gettitle($symbparm);
                   11592: 	    }
1.693     albertel 11593: 	
1.1232    raeburn  11594: 	    if ($space eq 'map') {
                   11595: 	        my ($map) = &decode_symb($symbparm);
                   11596: 	        return &symbread($map);
                   11597: 	    }
                   11598:             if ($space eq 'maptitle') {
                   11599:                 my ($map) = &decode_symb($symbparm);
                   11600:                 return &gettitle($map);
                   11601:             }
                   11602: 	    if ($space eq 'filename') {
                   11603: 	        if ($symbparm) {
                   11604: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11605: 	        }
                   11606: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11607: 	    }
1.1232    raeburn  11608: 
1.1233    raeburn  11609:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11610:                 if ($space eq 'visibleparts') {
                   11611:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11612:                     my $item;
                   11613:                     if (ref($navmap)) {
                   11614:                         my $res = $navmap->getBySymb($symbparm);
                   11615:                         my $parts = $res->parts();
                   11616:                         if (ref($parts) eq 'ARRAY') {
                   11617:                             $item = join(',',@{$parts});
                   11618:                         }
                   11619:                         undef($navmap);
1.1232    raeburn  11620:                     }
1.1233    raeburn  11621:                     return $item;
1.1232    raeburn  11622:                 }
                   11623:             }
                   11624:         }
1.693     albertel 11625: 
1.1301    raeburn  11626: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11627: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11628:         if (($courseid eq '') && ($cid)) {
                   11629:             $courseid = $cid;
                   11630:         }
                   11631: 	if (($symbparm && $courseid) && 
                   11632: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11633: 
1.218     albertel 11634: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11635: 
1.60      www      11636: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11637: 	    my $symbp=$symbparm;
1.1301    raeburn  11638: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11639: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11640:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11641: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11642: 	    if (($env{'user.name'} eq $uname) &&
                   11643: 		($env{'user.domain'} eq $udom)) {
                   11644: 		$section=$env{'request.course.sec'};
1.733     raeburn  11645:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11646:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11647: 	    } else {
1.539     albertel 11648: 		if (! defined($usection)) {
1.551     albertel 11649: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11650: 		} else {
                   11651: 		    $section = $usection;
                   11652: 		}
1.733     raeburn  11653:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11654: 	    }
                   11655: 
                   11656: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11657: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11658:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11659: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11660: 
1.593     albertel 11661: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11662: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11663:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11664: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11665: 
1.60      www      11666: # ----------------------------------------------------------- first, check user
1.624     albertel 11667: 
1.1301    raeburn  11668: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11669:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11670: 				       ([$courselevelr,'resource'],
                   11671: 					[$courselevelm,'map'     ],
1.1301    raeburn  11672:                                         [$courseleveli,'map'     ],
1.927     albertel 11673: 					[$courselevel, 'course'  ]));
1.931     albertel 11674: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11675: 
1.594     albertel 11676: # ------------------------------------------------ second, check some of course
1.684     raeburn  11677:             my $coursereply;
1.691     raeburn  11678:             if (@groups > 0) {
                   11679:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11680:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11681:                                        $mapp,\$recursed,\@recurseup);
                   11682:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11683:             }
1.96      www      11684: 
1.684     raeburn  11685: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11686: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11687: 				  'course',$mapp,\$recursed,\@recurseup,
                   11688:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11689: 				  ([$seclevelr,   'resource'],
                   11690: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11691:                                    [$secleveli,   'map'     ],
1.927     albertel 11692: 				   [$seclevel,    'course'  ],
                   11693: 				   [$courselevelr,'resource']));
                   11694: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11695: 
1.60      www      11696: # ------------------------------------------------------ third, check map parms
1.218     albertel 11697: 	    my %parmhash=();
                   11698: 	    my $thisparm='';
                   11699: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11700: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11701: 		    &GDBM_READER(),0640)) {
1.218     albertel 11702: 		$thisparm=$parmhash{$symbparm};
                   11703: 		untie(%parmhash);
                   11704: 	    }
1.927     albertel 11705: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11706: 	}
1.594     albertel 11707: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11708:  
                   11709:         my $what = $spacequalifierrest;
                   11710: 	$what=~s/\./\_/;
1.282     albertel 11711: 	my $filename;
                   11712: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11713: 	if ($symbparm) {
1.409     www      11714: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11715: 	} else {
1.620     albertel 11716: 	    $filename=$env{'request.filename'};
1.282     albertel 11717: 	}
1.1362    raeburn  11718:         my $toolsymb;
                   11719:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11720:             $toolsymb = $symbparm;
                   11721:         }
                   11722: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11723: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11724: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11725: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11726: 
1.1301    raeburn  11727: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11728: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11729: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11730: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11731: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11732: 				     'course',$mapp,\$recursed,\@recurseup,
                   11733:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11734: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11735:                                       [$courseleveli,'map'   ],
1.927     albertel 11736: 				      [$courselevel, 'course']));
                   11737: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11738: 	}
1.145     www      11739: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11740: 	unless ($space eq '0') {
1.336     albertel 11741: 	    my @parts=split(/_/,$space);
                   11742: 	    my $id=pop(@parts);
                   11743: 	    my $part=join('_',@parts);
                   11744: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11745: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11746: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11747: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11748: 	}
1.395     albertel 11749: 	if ($recurse) { return undef; }
1.1362    raeburn  11750: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11751: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11752: # ---------------------------------------------------- Any other user namespace
                   11753:     } elsif ($realm eq 'environment') {
                   11754: # ----------------------------------------------------------------- environment
1.620     albertel 11755: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11756: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11757: 	} else {
1.770     albertel 11758: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11759: 		return '';
                   11760: 	    }
1.219     albertel 11761: 	    my %returnhash=&userenvironment($udom,$uname,
                   11762: 					    $spacequalifierrest);
                   11763: 	    return $returnhash{$spacequalifierrest};
                   11764: 	}
1.28      www      11765:     } elsif ($realm eq 'system') {
1.48      www      11766: # ----------------------------------------------------------------- system.time
                   11767: 	if ($space eq 'time') {
                   11768: 	    return time;
                   11769:         }
1.696     albertel 11770:     } elsif ($realm eq 'server') {
                   11771: # ----------------------------------------------------------------- system.time
                   11772: 	if ($space eq 'name') {
                   11773: 	    return $ENV{'SERVER_NAME'};
                   11774:         }
1.28      www      11775:     }
1.48      www      11776:     return '';
1.61      www      11777: }
                   11778: 
1.927     albertel 11779: sub get_reply {
                   11780:     my ($reply_value) = @_;
1.940     raeburn  11781:     if (ref($reply_value) eq 'ARRAY') {
                   11782:         if (wantarray) {
                   11783: 	    return @$reply_value;
                   11784:         }
                   11785:         return $reply_value->[0];
                   11786:     } else {
                   11787:         return $reply_value;
1.927     albertel 11788:     }
                   11789: }
                   11790: 
1.691     raeburn  11791: sub check_group_parms {
1.1301    raeburn  11792:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11793:         $recursed,$recurseupref) = @_;
                   11794:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11795:                   [$what,'course']);
                   11796:     my $coursereply;
1.691     raeburn  11797:     foreach my $group (@{$groups}) {
1.1301    raeburn  11798:         my @groupitems = ();
1.691     raeburn  11799:         foreach my $level (@levels) {
1.927     albertel 11800:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11801:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11802:         }
1.1301    raeburn  11803:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11804:                                    $env{'course.'.$courseid.'.domain'},
                   11805:                                    'course',$mapp,$recursed,$recurseupref,
                   11806:                                    $courseid,'.['.$group.'].',$what,
                   11807:                                    @groupitems);
                   11808:         last if (defined($coursereply));
1.691     raeburn  11809:     }
                   11810:     return $coursereply;
                   11811: }
                   11812: 
1.1301    raeburn  11813: sub get_map_hierarchy {
1.1302    raeburn  11814:     my ($mapname,$courseid) = @_;
                   11815:     my @recurseup = ();
1.1301    raeburn  11816:     if ($mapname) {
1.1302    raeburn  11817:         if (($cachedmapkey eq $courseid) &&
                   11818:             (abs($cachedmaptime-time)<5)) {
                   11819:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11820:                 return @{$cachedmaps{$mapname}};
                   11821:             }
                   11822:         }
1.1301    raeburn  11823:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11824:         if (ref($navmap)) {
                   11825:             @recurseup = $navmap->recurseup_maps($mapname);
                   11826:             undef($navmap);
1.1302    raeburn  11827:             $cachedmaps{$mapname} = \@recurseup;
                   11828:             $cachedmaptime=time;
                   11829:             $cachedmapkey=$courseid;
1.1301    raeburn  11830:         }
                   11831:     }
                   11832:     return @recurseup;
                   11833: }
                   11834: 
1.1302    raeburn  11835: }
                   11836: 
1.691     raeburn  11837: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11838:     my ($courseid,@groups) = @_;
                   11839:     @groups = sort(@groups);
1.691     raeburn  11840:     return @groups;
                   11841: }
                   11842: 
1.395     albertel 11843: sub packages_tab_default {
1.1362    raeburn  11844:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11845:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11846: 
                   11847:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11848:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11849: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11850: 	if ($pack_type eq 'default') {
                   11851: 	    $do_default=1;
                   11852: 	} elsif ($pack_type eq 'extension') {
                   11853: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11854: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11855: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11856: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11857: 	}
                   11858:     }
                   11859:     # first look for a package that matches the requested part id
                   11860:     foreach my $package (@specifics) {
                   11861: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11862: 	next if ($pack_part ne $part);
                   11863: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11864: 	    return $packagetab{"$pack_type&$name&default"};
                   11865: 	}
                   11866:     }
                   11867:     # look for any possible matching non extension_ package
                   11868:     foreach my $package (@specifics) {
                   11869: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11870: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11871: 	    return $packagetab{"$pack_type&$name&default"};
                   11872: 	}
1.585     albertel 11873: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11874: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11875: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11876: 	}
                   11877:     }
1.738     albertel 11878:     # look for any posible extension_ match
                   11879:     foreach my $package (@extension) {
                   11880: 	my ($package,$pack_type)=@{$package};
                   11881: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11882: 	    return $packagetab{"$pack_type&$name&default"};
                   11883: 	}
                   11884: 	if (defined($packagetab{$package."&$name&default"})) {
                   11885: 	    return $packagetab{$package."&$name&default"};
                   11886: 	}
                   11887:     }
                   11888:     # look for a global default setting
                   11889:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11890: 	return $packagetab{"default&$name&default"};
                   11891:     }
1.395     albertel 11892:     return undef;
                   11893: }
                   11894: 
1.334     albertel 11895: sub add_prefix_and_part {
                   11896:     my ($prefix,$part)=@_;
                   11897:     my $keyroot;
                   11898:     if (defined($prefix) && $prefix !~ /^__/) {
                   11899: 	# prefix that has a part already
                   11900: 	$keyroot=$prefix;
                   11901:     } elsif (defined($prefix)) {
                   11902: 	# prefix that is missing a part
                   11903: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11904:     } else {
                   11905: 	# no prefix at all
                   11906: 	if (defined($part)) { $keyroot='_'.$part; }
                   11907:     }
                   11908:     return $keyroot;
                   11909: }
                   11910: 
1.71      www      11911: # ---------------------------------------------------------------- Get metadata
                   11912: 
1.599     albertel 11913: my %metaentry;
1.1070    www      11914: my %importedpartids;
1.1369    raeburn  11915: my %importedrespids;
1.71      www      11916: sub metadata {
1.1362    raeburn  11917:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11918:     $uri=&declutter($uri);
1.288     albertel 11919:     # if it is a non metadata possible uri return quickly
1.529     albertel 11920:     if (($uri eq '') || 
                   11921: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11922: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11923:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11924: 	return undef;
                   11925:     }
1.1261    raeburn  11926:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11927: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11928: 	return undef;
1.288     albertel 11929:     }
1.73      www      11930:     my $filename=$uri;
                   11931:     $uri=~s/\.meta$//;
1.172     www      11932: #
                   11933: # Is the metadata already cached?
1.177     www      11934: # Look at timestamp of caching
1.172     www      11935: # Everything is cached by the main uri, libraries are never directly cached
                   11936: #
1.428     albertel 11937:     if (!defined($liburi)) {
1.599     albertel 11938: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11939: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11940:     }
1.1362    raeburn  11941: 
                   11942: #
                   11943: # If the uri is for an external tool the file from
                   11944: # which metadata should be retrieved depends on whether
                   11945: # the tool had been configured to be gradable (set in the Course
                   11946: # Editor or Resource Editor).
                   11947: #
                   11948: # If a valid symb has been included as the third arg in the call
                   11949: # to &metadata() that can be used to retrieve the value of
                   11950: # parameter_0_gradable set for the resource, and included in the
                   11951: # uploaded map containing the tool. The value is retrieved via
                   11952: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11953: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11954: # is retrieved via &get().
                   11955: #
                   11956: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11957: # hiddenresource and encrypturl (during course initialization)
                   11958: # the map-level parameter for resource.0.gradable included in the 
                   11959: # uploaded map containing the tool will not yet have been stored
                   11960: # in the user_course_parms.db file for the user's session, so in 
                   11961: # this case fall back to retrieving gradable status from the
                   11962: # exttool_$marker.db file.
1.1362    raeburn  11963: #
                   11964: # In order to avoid an infinite loop, &metadata() will return
                   11965: # before a call to &EXT(), if the uri is for an external tool
                   11966: # and the $what for which metadata is being requested is
                   11967: # parameter_0_gradable or 0_gradable.
                   11968: #
                   11969: 
                   11970:     if ($uri =~ /ext\.tool$/) {
                   11971:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11972:             return;
                   11973:         } else {
                   11974:             my ($checked,$use_passback);
                   11975:             if ($toolsymb ne '') {
                   11976:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11977:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11978:                     $checked = 1;
                   11979:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11980:                         $use_passback = 1;
                   11981:                     }
                   11982:                 }
                   11983:             }
                   11984:             unless ($checked) {
                   11985:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11986:                 $marker=~s/\D//g;
1.1363    raeburn  11987:                 if ($marker) {
1.1362    raeburn  11988:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11989:                     $use_passback = $toolsettings{'gradable'};
                   11990:                 }
                   11991:             }
                   11992:             if ($use_passback) {
                   11993:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11994:             } else {
                   11995:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11996:             }
                   11997:         }
                   11998:     }
                   11999: 
1.428     albertel 12000:     {
1.1069    www      12001: # Imported parts would go here
1.1369    raeburn  12002:         my @origfiletagids=();
1.1069    www      12003:         my $importedparts=0;
1.1369    raeburn  12004: 
                   12005: # Imported responseids would go here
                   12006:         my $importedresponses=0;
1.172     www      12007: #
                   12008: # Is this a recursive call for a library?
                   12009: #
1.599     albertel 12010: #	if (! exists($metacache{$uri})) {
                   12011: #	    $metacache{$uri}={};
                   12012: #	}
1.924     albertel 12013: 	my $cachetime = 60*60;
1.171     www      12014:         if ($liburi) {
                   12015: 	    $liburi=&declutter($liburi);
                   12016:             $filename=$liburi;
1.401     bowersj2 12017:         } else {
1.599     albertel 12018: 	    &devalidate_cache_new('meta',$uri);
                   12019: 	    undef(%metaentry);
1.401     bowersj2 12020: 	}
1.140     www      12021:         my %metathesekeys=();
1.73      www      12022:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12023: 	my $metastring;
1.1140    www      12024: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12025: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12026: 	    $metastring = 
1.929     albertel 12027: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12028: 					  ('grade_target' => 'meta'));
                   12029: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12030: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12031:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12032: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12033: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12034: 	    $metastring=&getfile($file);
1.489     albertel 12035: 	}
1.208     albertel 12036:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12037:         my $token;
1.140     www      12038:         undef %metathesekeys;
1.71      www      12039:         while ($token=$parser->get_token) {
1.339     albertel 12040: 	    if ($token->[0] eq 'S') {
                   12041: 		if (defined($token->[2]->{'package'})) {
1.172     www      12042: #
                   12043: # This is a package - get package info
                   12044: #
1.339     albertel 12045: 		    my $package=$token->[2]->{'package'};
                   12046: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12047: 		    if (defined($token->[2]->{'id'})) { 
                   12048: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12049: 		    }
1.599     albertel 12050: 		    if ($metaentry{':packages'}) {
                   12051: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12052: 		    } else {
1.599     albertel 12053: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12054: 		    }
1.736     albertel 12055: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12056: 			my $part=$keyroot;
                   12057: 			$part=~s/^\_//;
1.736     albertel 12058: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12059: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12060: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12061: 			    # ignore package.tab specified default values
                   12062:                             # here &package_tab_default() will fetch those
                   12063: 			    if ($subp eq 'default') { next; }
1.736     albertel 12064: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12065: 			    my $unikey;
                   12066: 			    if ($pack =~ /_0$/) {
                   12067: 				$unikey='parameter_0_'.$name;
                   12068: 				$part=0;
                   12069: 			    } else {
                   12070: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12071: 			    }
1.339     albertel 12072: 			    if ($subp eq 'display') {
                   12073: 				$value.=' [Part: '.$part.']';
                   12074: 			    }
1.599     albertel 12075: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12076: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12077: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12078: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12079: 			    }
1.599     albertel 12080: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12081: 				$metaentry{':'.$unikey}=
                   12082: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12083: 			    }
1.339     albertel 12084: 			}
                   12085: 		    }
                   12086: 		} else {
1.172     www      12087: #
                   12088: # This is not a package - some other kind of start tag
1.339     albertel 12089: #
                   12090: 		    my $entry=$token->[1];
1.1068    www      12091: 		    my $unikey='';
1.175     www      12092: 
1.339     albertel 12093: 		    if ($entry eq 'import') {
1.175     www      12094: #
                   12095: # Importing a library here
1.339     albertel 12096: #
1.1067    www      12097:                         my $location=$parser->get_text('/import');
                   12098:                         my $dir=$filename;
                   12099:                         $dir=~s|[^/]*$||;
                   12100:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12101: 
                   12102:                         my $importid=$token->[2]->{'id'};
1.1068    www      12103:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12104: #
                   12105: # Check metadata for imported file to
                   12106: # see if it contained response items
                   12107: #
1.1372    raeburn  12108:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12109:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12110:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12111:                                                            $depthcount+1));
                   12112:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12113:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12114:                                                              undef,$depthcount+1);
                   12115:                             if ($libresponseorder ne '') {
                   12116:                                 if ($#origfiletagids<0) {
                   12117:                                     undef(%importedrespids);
                   12118:                                     undef(%importedpartids);
                   12119:                                 }
1.1373    raeburn  12120:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12121:                                 if (@respids) {
                   12122:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12123:                                 }
                   12124:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12125:                                     $importedresponses = 1;
1.1369    raeburn  12126: # We need to get the original file and the imported file to get the response order correct
                   12127: # Load and inspect original file
1.1372    raeburn  12128:                                     if ($#origfiletagids<0) {
                   12129:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12130:                                         $origfile=&getfile($origfilelocation);
                   12131:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12132:                                     }
1.1369    raeburn  12133:                                 }
                   12134:                             }
                   12135:                         }
1.1370    raeburn  12136: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12137: # hash populated for imported library file
                   12138:                         %metaentry = %currmetaentry;
                   12139:                         undef(%currmetaentry);
1.1374    raeburn  12140:                         if ($importmode eq 'part') {
1.1068    www      12141: # Import as part(s)
1.1069    www      12142:                            $importedparts=1;
                   12143: # We need to get the original file and the imported file to get the part order correct
                   12144: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12145: # Load and inspect original file if we didn't do that already
                   12146:                            if ($#origfiletagids<0) {
                   12147:                                undef(%importedrespids);
                   12148:                                undef(%importedpartids);
                   12149:                                if ($origfile eq '') {
                   12150:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12151:                                    $origfile=&getfile($origfilelocation);
                   12152:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12153:                                }
1.1070    www      12154:                            }
1.1372    raeburn  12155:                            my @impfilepartids;
                   12156: # If <partorder> tag is included in metadata for the imported file
                   12157: # get the parts in the imported file from that.
                   12158:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12159:                                %currmetaentry = %metaentry;
                   12160:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12161:                                                             $depthcount+1);
                   12162:                                %metaentry = %currmetaentry;
                   12163:                                undef(%currmetaentry);
                   12164:                                if ($libpartorder ne '') {
                   12165:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12166:                                }
                   12167:                            } else {
                   12168: # If no <partorder> tag available, load and inspect imported file
                   12169:                                my $impfile=&getfile($location);
                   12170:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12171:                            }
1.1069    www      12172:                            if ($#impfilepartids>=0) {
                   12173: # This problem had parts
1.1070    www      12174:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12175:                            } else {
                   12176: # Importing by turning a single problem into a problem part
                   12177: # It gets the import-tags ID as part-ID
                   12178:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12179:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12180:                            }
1.1068    www      12181:                         } else {
1.1374    raeburn  12182: # Import as problem or as normal import
                   12183:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12184:                             unless ($importmode eq 'problem') {
1.1068    www      12185: # Normal import
1.1374    raeburn  12186:                                 if (defined($token->[2]->{'id'})) {
                   12187:                                     $unikey.='_'.$token->[2]->{'id'};
                   12188:                                 }
                   12189:                             }
                   12190: # Check metadata for imported file to
                   12191: # see if it contained parts
                   12192:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12193:                                 %currmetaentry = %metaentry;
                   12194:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12195:                                                              $depthcount+1);
                   12196:                                 %metaentry = %currmetaentry;
                   12197:                                 undef(%currmetaentry);
                   12198:                                 if ($libpartorder ne '') {
                   12199:                                     $importedparts = 1;
                   12200:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12201:                                 }
                   12202:                             }
1.1067    www      12203:                         }
1.339     albertel 12204: 			if ($depthcount<20) {
1.736     albertel 12205: 			    my $metadata = 
1.1362    raeburn  12206: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12207: 					  $depthcount+1);
                   12208: 			    foreach my $meta (split(',',$metadata)) {
                   12209: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12210: 				$metathesekeys{$meta}=1;
1.339     albertel 12211: 			    }
1.1068    www      12212:                         }
1.1067    www      12213: 		    } else {
                   12214: #
                   12215: # Not importing, some other kind of non-package, non-library start tag
                   12216: # 
                   12217:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12218:                         if (defined($token->[2]->{'id'})) {
                   12219:                             $unikey.='_'.$token->[2]->{'id'};
                   12220:                         }
1.339     albertel 12221: 			if (defined($token->[2]->{'name'})) { 
                   12222: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12223: 			}
                   12224: 			$metathesekeys{$unikey}=1;
1.736     albertel 12225: 			foreach my $param (@{$token->[3]}) {
                   12226: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12227: 				$token->[2]->{$param};
1.339     albertel 12228: 			}
                   12229: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12230: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12231: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12232: 		 # only ws inside the tag, and not in default, so use default
                   12233: 		 # as value
1.599     albertel 12234: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12235: 			} elsif ( $internaltext =~ /\S/ ) {
                   12236: 		  # something interesting inside the tag
                   12237: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12238: 			} else {
1.908     albertel 12239: 		  # no interesting values, don't set a default
1.339     albertel 12240: 			}
1.172     www      12241: # end of not-a-package not-a-library import
1.339     albertel 12242: 		    }
1.172     www      12243: # end of not-a-package start tag
1.339     albertel 12244: 		}
1.172     www      12245: # the next is the end of "start tag"
1.339     albertel 12246: 	    }
                   12247: 	}
1.483     albertel 12248: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12249: 	$extension = lc($extension);
                   12250: 	if ($extension eq 'htm') { $extension='html'; }
                   12251: 
1.737     albertel 12252: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12253: 	    #no specific packages #how's our extension
                   12254: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12255: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12256: 					 \%metathesekeys);
                   12257: 	}
1.883     albertel 12258: 
                   12259: 	if (!exists($metaentry{':packages'})
                   12260: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12261: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12262: 		#no specific packages well let's get default then
                   12263: 		if ($key!~/^default&/) { next; }
1.488     albertel 12264: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12265: 					     \%metathesekeys);
                   12266: 	    }
                   12267: 	}
1.338     www      12268: # are there custom rights to evaluate
1.599     albertel 12269: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12270: 
1.338     www      12271:     #
                   12272:     # Importing a rights file here
1.339     albertel 12273:     #
                   12274: 	    unless ($depthcount) {
1.599     albertel 12275: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12276: 		my $dir=$filename;
                   12277: 		$dir=~s|[^/]*$||;
                   12278: 		$location=&filelocation($dir,$location);
1.736     albertel 12279: 		my $rights_metadata =
1.1362    raeburn  12280: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12281: 			      $depthcount+1);
                   12282: 		foreach my $rights (split(',',$rights_metadata)) {
                   12283: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12284: 		    $metathesekeys{$rights}=1;
1.339     albertel 12285: 		}
                   12286: 	    }
                   12287: 	}
1.737     albertel 12288: 	# uniqifiy package listing
                   12289: 	my %seen;
                   12290: 	my @uniq_packages =
                   12291: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12292: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12293: 
1.1369    raeburn  12294:         if (($importedresponses) || ($importedparts)) {
                   12295:             if ($importedparts) {
1.1070    www      12296: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12297:                 $metaentry{':partorder'}='';
                   12298:                 $metathesekeys{'partorder'}=1;
                   12299:             }
                   12300:             if ($importedresponses) {
                   12301: # We had imported responses and need to rebuil responseorder
                   12302:                 $metaentry{':responseorder'}='';
                   12303:                 $metathesekeys{'responseorder'}=1;
                   12304:             }
                   12305:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12306:                 my $origid = $origfiletagids[$index+1];
                   12307:                 if ($origfiletagids[$index] eq 'part') {
                   12308: # Original part, part of the problem
                   12309:                     if ($importedparts) {
                   12310:                         $metaentry{':partorder'}.=','.$origid;
                   12311:                     }
                   12312:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12313:                     if ($importedparts) {
                   12314: # We have imported parts at this position
1.1373    raeburn  12315:                         if ($importedpartids{$origid} ne '') {
                   12316:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12317:                         }
1.1369    raeburn  12318:                     }
                   12319:                     if ($importedresponses) {
                   12320: # We have imported responses at this position
1.1373    raeburn  12321:                         if ($importedrespids{$origid} ne '') {
                   12322:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12323:                         }
                   12324:                     }
                   12325:                 } else {
                   12326: # Original response item, part of the problem
                   12327:                     if ($importedresponses) {
                   12328:                         $metaentry{':responseorder'}.=','.$origid;
                   12329:                     }
                   12330:                 }
                   12331:             }
                   12332:             if ($importedparts) {
                   12333:                 $metaentry{':partorder'}=~s/^\,//;
                   12334:             }
                   12335:             if ($importedresponses) {
                   12336:                 $metaentry{':responseorder'}=~s/^\,//;
                   12337:             }
1.1070    www      12338:         }
1.737     albertel 12339: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12340: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12341: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12342:         unless ($liburi) {
                   12343: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12344:         }
1.177     www      12345: # this is the end of "was not already recently cached
1.71      www      12346:     }
1.599     albertel 12347:     return $metaentry{':'.$what};
1.261     albertel 12348: }
                   12349: 
1.488     albertel 12350: sub metadata_create_package_def {
1.483     albertel 12351:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12352:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12353:     if ($subp eq 'default') { next; }
                   12354:     
1.599     albertel 12355:     if (defined($metaentry{':packages'})) {
                   12356: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12357:     } else {
1.599     albertel 12358: 	$metaentry{':packages'}=$package;
1.483     albertel 12359:     }
                   12360:     my $value=$packagetab{$key};
                   12361:     my $unikey;
                   12362:     $unikey='parameter_0_'.$name;
1.599     albertel 12363:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12364:     $$metathesekeys{$unikey}=1;
1.599     albertel 12365:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12366: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12367:     }
1.599     albertel 12368:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12369: 	$metaentry{':'.$unikey}=
                   12370: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12371:     }
                   12372: }
                   12373: 
1.261     albertel 12374: sub metadata_generate_part0 {
                   12375:     my ($metadata,$metacache,$uri) = @_;
                   12376:     my %allnames;
1.737     albertel 12377:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12378: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12379: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12380: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12381: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12382: 	    $allnames{$name}=$part;
                   12383: 	  }
                   12384: 	}
                   12385:     }
                   12386:     foreach my $name (keys(%allnames)) {
                   12387:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12388:       my $key=":parameter_0_$name";
1.261     albertel 12389:       $$metacache{"$key.part"}='0';
                   12390:       $$metacache{"$key.name"}=$name;
1.428     albertel 12391:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12392: 					   $allnames{$name}.'_'.$name.
                   12393: 					   '.type'};
1.428     albertel 12394:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12395: 			     '.display'};
1.644     www      12396:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12397:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12398:       $$metacache{"$key.display"}=$olddis;
                   12399:     }
1.71      www      12400: }
                   12401: 
1.764     albertel 12402: # ------------------------------------------------------ Devalidate title cache
                   12403: 
                   12404: sub devalidate_title_cache {
                   12405:     my ($url)=@_;
                   12406:     if (!$env{'request.course.id'}) { return; }
                   12407:     my $symb=&symbread($url);
                   12408:     if (!$symb) { return; }
                   12409:     my $key=$env{'request.course.id'}."\0".$symb;
                   12410:     &devalidate_cache_new('title',$key);
                   12411: }
                   12412: 
1.1014    droeschl 12413: # ------------------------------------------------- Get the title of a course
                   12414: 
                   12415: sub current_course_title {
                   12416:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12417: }
1.301     www      12418: # ------------------------------------------------- Get the title of a resource
                   12419: 
                   12420: sub gettitle {
                   12421:     my $urlsymb=shift;
                   12422:     my $symb=&symbread($urlsymb);
1.534     albertel 12423:     if ($symb) {
1.620     albertel 12424: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12425: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12426: 	if (defined($cached)) { 
                   12427: 	    return $result;
                   12428: 	}
1.534     albertel 12429: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12430: 	my $title='';
1.907     albertel 12431: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12432: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12433: 	} else {
                   12434: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12435: 		    &GDBM_READER(),0640)) {
                   12436: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12437: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12438: 		untie(%bighash);
                   12439: 	    }
1.534     albertel 12440: 	}
                   12441: 	$title=~s/\&colon\;/\:/gs;
                   12442: 	if ($title) {
1.1159    www      12443: # Remember both $symb and $title for dynamic metadata
                   12444:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12445:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12446: # Cache this title and then return it
1.599     albertel 12447: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12448: 	}
                   12449: 	$urlsymb=$url;
                   12450:     }
                   12451:     my $title=&metadata($urlsymb,'title');
                   12452:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12453:     return $title;
1.301     www      12454: }
1.613     albertel 12455: 
1.614     albertel 12456: sub get_slot {
                   12457:     my ($which,$cnum,$cdom)=@_;
                   12458:     if (!$cnum || !$cdom) {
1.790     albertel 12459: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12460: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12461: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12462:     }
1.703     albertel 12463:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12464:     my %slotinfo;
                   12465:     if (exists($remembered{$key})) {
                   12466: 	$slotinfo{$which} = $remembered{$key};
                   12467:     } else {
                   12468: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12469: 	&Apache::lonhomework::showhash(%slotinfo);
                   12470: 	my ($tmp)=keys(%slotinfo);
                   12471: 	if ($tmp=~/^error:/) { return (); }
                   12472: 	$remembered{$key} = $slotinfo{$which};
                   12473:     }
1.616     albertel 12474:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12475: 	return %{$slotinfo{$which}};
                   12476:     }
                   12477:     return $slotinfo{$which};
1.614     albertel 12478: }
1.1150    raeburn  12479: 
                   12480: sub get_reservable_slots {
                   12481:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12482:     my $now = time;
                   12483:     my $reservable_info;
                   12484:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12485:     if (exists($remembered{$key})) {
                   12486:         $reservable_info = $remembered{$key};
                   12487:     } else {
                   12488:         my %resv;
                   12489:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12490:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12491:         $reservable_info = \%resv;
                   12492:         $remembered{$key} = $reservable_info;
                   12493:     }
                   12494:     return $reservable_info;
                   12495: }
                   12496: 
                   12497: sub get_course_slots {
                   12498:     my ($cnum,$cdom) = @_;
                   12499:     my $hashid=$cnum.':'.$cdom;
                   12500:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12501:     if (defined($cached)) {
                   12502:         if (ref($result) eq 'HASH') {
                   12503:             return %{$result};
                   12504:         }
                   12505:     } else {
                   12506:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12507:         my ($tmp) = keys(%slots);
                   12508:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12509:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12510:             return %slots;
                   12511:         }
                   12512:     }
                   12513:     return;
                   12514: }
                   12515: 
                   12516: sub devalidate_slots_cache {
                   12517:     my ($cnum,$cdom)=@_;
                   12518:     my $hashid=$cnum.':'.$cdom;
                   12519:     &devalidate_cache_new('allslots',$hashid);
                   12520: }
                   12521: 
1.1181    raeburn  12522: sub get_coursechange {
                   12523:     my ($cdom,$cnum) = @_;
                   12524:     if ($cdom eq '' || $cnum eq '') {
                   12525:         return unless ($env{'request.course.id'});
                   12526:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12527:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12528:     }
                   12529:     my $hashid=$cdom.'_'.$cnum;
                   12530:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12531:     if ((defined($cached)) && ($change ne '')) {
                   12532:         return $change;
                   12533:     } else {
                   12534:         my %crshash;
                   12535:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12536:         if ($crshash{'internal.contentchange'} eq '') {
                   12537:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12538:             if ($change eq '') {
                   12539:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12540:                 $change = $crshash{'internal.created'};
                   12541:             }
                   12542:         } else {
                   12543:             $change = $crshash{'internal.contentchange'};
                   12544:         }
                   12545:         my $cachetime = 600;
                   12546:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12547:     }
                   12548:     return $change;
                   12549: }
                   12550: 
                   12551: sub devalidate_coursechange_cache {
                   12552:     my ($cnum,$cdom)=@_;
                   12553:     my $hashid=$cnum.':'.$cdom;
                   12554:     &devalidate_cache_new('crschange',$hashid);
                   12555: }
                   12556: 
1.31      www      12557: # ------------------------------------------------- Update symbolic store links
                   12558: 
                   12559: sub symblist {
                   12560:     my ($mapname,%newhash)=@_;
1.438     www      12561:     $mapname=&deversion(&declutter($mapname));
1.31      www      12562:     my %hash;
1.620     albertel 12563:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12564:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12565:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12566: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12567: 		next if ($url eq 'last_known'
                   12568: 			 && $env{'form.no_update_last_known'});
                   12569: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12570: 						    $newhash{$url}->[1],
                   12571: 						    $newhash{$url}->[0]);
1.191     harris41 12572:             }
1.31      www      12573:             if (untie(%hash)) {
                   12574: 		return 'ok';
                   12575:             }
                   12576:         }
                   12577:     }
                   12578:     return 'error';
1.212     www      12579: }
                   12580: 
                   12581: # --------------------------------------------------------------- Verify a symb
                   12582: 
                   12583: sub symbverify {
1.1190    raeburn  12584:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12585:     my $thisfn=$thisurl;
1.439     www      12586:     $thisfn=&declutter($thisfn);
1.215     www      12587: # direct jump to resource in page or to a sequence - will construct own symbs
                   12588:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12589: # check URL part
1.409     www      12590:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12591: 
1.431     www      12592:     unless ($url eq $thisfn) { return 0; }
1.213     www      12593: 
1.216     www      12594:     $symb=&symbclean($symb);
1.510     www      12595:     $thisurl=&deversion($thisurl);
1.439     www      12596:     $thisfn=&deversion($thisfn);
1.213     www      12597: 
                   12598:     my %bighash;
                   12599:     my $okay=0;
1.431     www      12600: 
1.620     albertel 12601:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12602:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12603:         my $noclutter;
1.1032    raeburn  12604:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12605:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12606:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12607:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12608:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12609:                 $noclutter = 1;
                   12610:             }
                   12611:         }
                   12612:         my $ids;
                   12613:         if ($noclutter) {
                   12614:             $ids=$bighash{'ids_'.$thisurl};
                   12615:         } else {
                   12616:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12617:         }
1.1102    raeburn  12618:         unless ($ids) {
                   12619:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12620:             $ids=$bighash{$idkey};
1.216     www      12621:         }
                   12622:         if ($ids) {
                   12623: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12624:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12625:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12626:             }
1.800     albertel 12627: 	    foreach my $id (split(/\,/,$ids)) {
                   12628: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12629:                if (
                   12630:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12631:    eq $symb) {
                   12632:                    if (ref($encstate)) {
                   12633:                        $$encstate = $bighash{'encrypted_'.$id};
                   12634:                    }
1.620     albertel 12635: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12636: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12637:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12638: 		       $okay=1;
1.1202    raeburn  12639:                        last;
1.582     albertel 12640: 		   }
                   12641: 	       }
1.216     www      12642: 	   }
                   12643:         }
1.213     www      12644: 	untie(%bighash);
                   12645:     }
                   12646:     return $okay;
1.31      www      12647: }
                   12648: 
1.210     www      12649: # --------------------------------------------------------------- Clean-up symb
                   12650: 
                   12651: sub symbclean {
                   12652:     my $symb=shift;
1.568     albertel 12653:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12654: # remove version from map
                   12655:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12656: 
1.210     www      12657: # remove version from URL
                   12658:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12659: 
1.507     www      12660: # remove wrapper
                   12661: 
1.510     www      12662:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12663:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12664:     return $symb;
1.409     www      12665: }
                   12666: 
                   12667: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12668: 
                   12669: sub encode_symb {
                   12670:     my ($map,$resid,$url)=@_;
                   12671:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12672: }
1.409     www      12673: 
                   12674: sub decode_symb {
1.568     albertel 12675:     my $symb=shift;
                   12676:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12677:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12678:     return (&fixversion($map),$resid,&fixversion($url));
                   12679: }
                   12680: 
                   12681: sub fixversion {
                   12682:     my $fn=shift;
1.609     banghart 12683:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12684:     my %bighash;
                   12685:     my $uri=&clutter($fn);
1.620     albertel 12686:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12687: # is this cached?
1.599     albertel 12688:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12689:     if (defined($cached)) { return $result; }
                   12690: # unfortunately not cached, or expired
1.620     albertel 12691:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12692: 	    &GDBM_READER(),0640)) {
                   12693:  	if ($bighash{'version_'.$uri}) {
                   12694:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12695:  	    unless (($version eq 'mostrecent') || 
                   12696: 		    ($version==&getversion($uri))) {
1.440     www      12697:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12698:  	    }
                   12699:  	}
                   12700:  	untie %bighash;
1.413     www      12701:     }
1.599     albertel 12702:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12703: }
                   12704: 
                   12705: sub deversion {
                   12706:     my $url=shift;
                   12707:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12708:     return $url;
1.210     www      12709: }
                   12710: 
1.31      www      12711: # ------------------------------------------------------ Return symb list entry
                   12712: 
                   12713: sub symbread {
1.1282    raeburn  12714:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12715:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12716:     if (defined($env{$cache_str})) {
                   12717:         if ($ignorecachednull) {
                   12718:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12719:         } else {
                   12720:             return $env{$cache_str};
                   12721:         }
                   12722:     }
1.242     www      12723: # no filename provided? try from environment
1.1265    raeburn  12724:     unless ($thisfn) {
1.620     albertel 12725:         if ($env{'request.symb'}) {
                   12726: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12727: 	}
1.620     albertel 12728: 	$thisfn=$env{'request.filename'};
1.44      www      12729:     }
1.569     albertel 12730:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12731: # is that filename actually a symb? Verify, clean, and return
                   12732:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12733: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12734: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12735: 	}
1.242     www      12736:     }
1.44      www      12737:     $thisfn=declutter($thisfn);
1.31      www      12738:     my %hash;
1.37      www      12739:     my %bighash;
                   12740:     my $syval='';
1.620     albertel 12741:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12742:         my $targetfn = $thisfn;
1.609     banghart 12743:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12744:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12745:         }
1.687     albertel 12746: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12747: 	    $targetfn=$1;
                   12748: 	}
1.620     albertel 12749:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12750:                       &GDBM_READER(),0640)) {
1.481     raeburn  12751: 	    $syval=$hash{$targetfn};
1.37      www      12752:             untie(%hash);
                   12753:         }
                   12754: # ---------------------------------------------------------- There was an entry
                   12755:         if ($syval) {
1.601     albertel 12756: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12757: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12758: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12759: 		    #return $env{$cache_str}='';
1.601     albertel 12760: 		#}    
                   12761: 		#$syval.=$1;
                   12762: 	    #}
1.37      www      12763:         } else {
                   12764: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12765:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12766:                             &GDBM_READER(),0640)) {
1.37      www      12767: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12768:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12769:               unless ($ids) { 
                   12770:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12771:               }
                   12772:               unless ($ids) {
                   12773: # alias?
                   12774: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12775:               }
1.37      www      12776:               if ($ids) {
                   12777: # ------------------------------------------------------------------- Has ID(s)
                   12778:                  my @possibilities=split(/\,/,$ids);
1.39      www      12779:                  if ($#possibilities==0) {
                   12780: # ----------------------------------------------- There is only one possibility
1.37      www      12781: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12782: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12783: 						    $resid,$thisfn);
1.1282    raeburn  12784:                      if (ref($possibles) eq 'HASH') {
                   12785:                          $possibles->{$syval} = 1;    
                   12786:                      }
                   12787:                      if ($checkforblock) {
                   12788:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12789:                          if (@blockers) {
                   12790:                              $syval = '';
                   12791:                              return;
                   12792:                          }
                   12793:                      }
                   12794:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12795: # ------------------------------------------ There is more than one possibility
                   12796:                      my $realpossible=0;
1.800     albertel 12797:                      foreach my $id (@possibilities) {
                   12798: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12799:                          my $canaccess;
                   12800:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12801:                              $canaccess = 1;
                   12802:                          } else { 
                   12803:                              $canaccess = &allowed('bre',$file);
                   12804:                          }
                   12805:                          if ($canaccess) {
                   12806:          		     my ($mapid,$resid)=split(/\./,$id);
                   12807:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12808:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12809: 						             $resid,$thisfn);
                   12810:                                  if (ref($possibles) eq 'HASH') {
                   12811:                                      $possibles->{$syval} = 1;
                   12812:                                  }
                   12813:                                  if ($checkforblock) {
                   12814:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12815:                                      unless (@blockers > 0) {
                   12816:                                          $syval = $poss_syval;
                   12817:                                          $realpossible++;
                   12818:                                      }
                   12819:                                  } else {
                   12820:                                      $syval = $poss_syval;
                   12821:                                      $realpossible++;
                   12822:                                  }
                   12823:                              }
1.39      www      12824: 			 }
1.191     harris41 12825:                      }
1.39      www      12826: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12827:                  } else {
                   12828:                      $syval='';
1.37      www      12829:                  }
                   12830: 	      }
1.1282    raeburn  12831:               untie(%bighash);
1.481     raeburn  12832:            }
1.31      www      12833:         }
1.62      www      12834:         if ($syval) {
1.620     albertel 12835: 	    return $env{$cache_str}=$syval;
1.62      www      12836:         }
1.31      www      12837:     }
1.949     raeburn  12838:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12839:     return $env{$cache_str}='';
1.31      www      12840: }
                   12841: 
                   12842: # ---------------------------------------------------------- Return random seed
                   12843: 
1.32      www      12844: sub numval {
                   12845:     my $txt=shift;
                   12846:     $txt=~tr/A-J/0-9/;
                   12847:     $txt=~tr/a-j/0-9/;
                   12848:     $txt=~tr/K-T/0-9/;
                   12849:     $txt=~tr/k-t/0-9/;
                   12850:     $txt=~tr/U-Z/0-5/;
                   12851:     $txt=~tr/u-z/0-5/;
                   12852:     $txt=~s/\D//g;
1.564     albertel 12853:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12854:     return int($txt);
1.368     albertel 12855: }
                   12856: 
1.484     albertel 12857: sub numval2 {
                   12858:     my $txt=shift;
                   12859:     $txt=~tr/A-J/0-9/;
                   12860:     $txt=~tr/a-j/0-9/;
                   12861:     $txt=~tr/K-T/0-9/;
                   12862:     $txt=~tr/k-t/0-9/;
                   12863:     $txt=~tr/U-Z/0-5/;
                   12864:     $txt=~tr/u-z/0-5/;
                   12865:     $txt=~s/\D//g;
                   12866:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12867:     my $total;
                   12868:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12869:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12870:     return int($total);
                   12871: }
                   12872: 
1.575     albertel 12873: sub numval3 {
                   12874:     use integer;
                   12875:     my $txt=shift;
                   12876:     $txt=~tr/A-J/0-9/;
                   12877:     $txt=~tr/a-j/0-9/;
                   12878:     $txt=~tr/K-T/0-9/;
                   12879:     $txt=~tr/k-t/0-9/;
                   12880:     $txt=~tr/U-Z/0-5/;
                   12881:     $txt=~tr/u-z/0-5/;
                   12882:     $txt=~s/\D//g;
                   12883:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12884:     my $total;
                   12885:     foreach my $val (@txts) { $total+=$val; }
                   12886:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12887:     return $total;
                   12888: }
                   12889: 
1.675     albertel 12890: sub digest {
                   12891:     my ($data)=@_;
                   12892:     my $digest=&Digest::MD5::md5($data);
                   12893:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12894:     my ($e,$f);
                   12895:     {
                   12896:         use integer;
                   12897:         $e=($a+$b);
                   12898:         $f=($c+$d);
                   12899:         if ($_64bit) {
                   12900:             $e=(($e<<32)>>32);
                   12901:             $f=(($f<<32)>>32);
                   12902:         }
                   12903:     }
                   12904:     if (wantarray) {
                   12905: 	return ($e,$f);
                   12906:     } else {
                   12907: 	my $g;
                   12908: 	{
                   12909: 	    use integer;
                   12910: 	    $g=($e+$f);
                   12911: 	    if ($_64bit) {
                   12912: 		$g=(($g<<32)>>32);
                   12913: 	    }
                   12914: 	}
                   12915: 	return $g;
                   12916:     }
                   12917: }
                   12918: 
1.368     albertel 12919: sub latest_rnd_algorithm_id {
1.675     albertel 12920:     return '64bit5';
1.366     albertel 12921: }
1.32      www      12922: 
1.503     albertel 12923: sub get_rand_alg {
                   12924:     my ($courseid)=@_;
1.790     albertel 12925:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12926:     if ($courseid) {
1.620     albertel 12927: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12928:     }
                   12929:     return &latest_rnd_algorithm_id();
                   12930: }
                   12931: 
1.562     albertel 12932: sub validCODE {
                   12933:     my ($CODE)=@_;
                   12934:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12935:     return 0;
                   12936: }
                   12937: 
1.491     albertel 12938: sub getCODE {
1.620     albertel 12939:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12940:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12941: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12942: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12943: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12944:     }
                   12945:     return undef;
                   12946: }
1.1133    foxr     12947: #
                   12948: #  Determines the random seed for a specific context:
                   12949: #
                   12950: # parameters:
                   12951: #   symb      - in course context the symb for the seed.
                   12952: #   course_id - The course id of the form domain_coursenum.
                   12953: #   domain    - Domain for the user.
                   12954: #   course    - Course for the user.
                   12955: #   cenv      - environment of the course.
                   12956: #
                   12957: # NOTE:
                   12958: #   All parameters are picked out of the environment if missing
                   12959: #   or not defined.
                   12960: #   If a symb cannot be determined the current time is used instead.
                   12961: #
                   12962: #  For a given well defined symb, courside, domain, username,
                   12963: #  and course environment, the seed is reproducible.
                   12964: #
1.31      www      12965: sub rndseed {
1.1133    foxr     12966:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12967:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12968:     if (!defined($symb)) {
1.366     albertel 12969: 	unless ($symb=$wsymb) { return time; }
                   12970:     }
1.1146    foxr     12971:     if (!defined $courseid) { 
                   12972: 	$courseid=$wcourseid; 
                   12973:     }
                   12974:     if (!defined $domain) { $domain=$wdomain; }
                   12975:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12976: 
                   12977:     my $which;
                   12978:     if (defined($cenv->{'rndseed'})) {
                   12979: 	$which = $cenv->{'rndseed'};
                   12980:     } else {
                   12981: 	$which =&get_rand_alg($courseid);
                   12982:     }
1.491     albertel 12983:     if (defined(&getCODE())) {
1.1133    foxr     12984: 
1.675     albertel 12985: 	if ($which eq '64bit5') {
                   12986: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12987: 	} elsif ($which eq '64bit4') {
1.575     albertel 12988: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12989: 	} else {
                   12990: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12991: 	}
1.675     albertel 12992:     } elsif ($which eq '64bit5') {
                   12993: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12994:     } elsif ($which eq '64bit4') {
                   12995: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12996:     } elsif ($which eq '64bit3') {
                   12997: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12998:     } elsif ($which eq '64bit2') {
                   12999: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13000:     } elsif ($which eq '64bit') {
                   13001: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13002:     }
                   13003:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13004: }
                   13005: 
                   13006: sub rndseed_32bit {
                   13007:     my ($symb,$courseid,$domain,$username)=@_;
                   13008:     {
                   13009: 	use integer;
                   13010: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13011: 	my $symbseed=numval($symb) << 22;
                   13012: 	my $namechck=unpack("%32C*",$username) << 17;
                   13013: 	my $nameseed=numval($username) << 12;
                   13014: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13015: 	my $courseseed=unpack("%32C*",$courseid);
                   13016: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13017: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13018: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13019: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13020: 	return $num;
                   13021:     }
                   13022: }
                   13023: 
                   13024: sub rndseed_64bit {
                   13025:     my ($symb,$courseid,$domain,$username)=@_;
                   13026:     {
                   13027: 	use integer;
                   13028: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13029: 	my $symbseed=numval($symb) << 10;
                   13030: 	my $namechck=unpack("%32S*",$username);
                   13031: 	
                   13032: 	my $nameseed=numval($username) << 21;
                   13033: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13034: 	my $courseseed=unpack("%32S*",$courseid);
                   13035: 	
                   13036: 	my $num1=$symbchck+$symbseed+$namechck;
                   13037: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13038: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13039: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13040: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13041: 	return "$num1,$num2";
1.155     albertel 13042:     }
1.366     albertel 13043: }
                   13044: 
1.443     albertel 13045: sub rndseed_64bit2 {
                   13046:     my ($symb,$courseid,$domain,$username)=@_;
                   13047:     {
                   13048: 	use integer;
                   13049: 	# strings need to be an even # of cahracters long, it it is odd the
                   13050:         # last characters gets thrown away
                   13051: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13052: 	my $symbseed=numval($symb) << 10;
                   13053: 	my $namechck=unpack("%32S*",$username.' ');
                   13054: 	
                   13055: 	my $nameseed=numval($username) << 21;
1.501     albertel 13056: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13057: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13058: 	
                   13059: 	my $num1=$symbchck+$symbseed+$namechck;
                   13060: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13061: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13062: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13063: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13064: 	return "$num1,$num2";
                   13065:     }
                   13066: }
                   13067: 
                   13068: sub rndseed_64bit3 {
                   13069:     my ($symb,$courseid,$domain,$username)=@_;
                   13070:     {
                   13071: 	use integer;
                   13072: 	# strings need to be an even # of cahracters long, it it is odd the
                   13073:         # last characters gets thrown away
                   13074: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13075: 	my $symbseed=numval2($symb) << 10;
                   13076: 	my $namechck=unpack("%32S*",$username.' ');
                   13077: 	
                   13078: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13079: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13080: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13081: 	
                   13082: 	my $num1=$symbchck+$symbseed+$namechck;
                   13083: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13084: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13085: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13086: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13087: 	
1.503     albertel 13088: 	return "$num1:$num2";
1.443     albertel 13089:     }
                   13090: }
                   13091: 
1.575     albertel 13092: sub rndseed_64bit4 {
                   13093:     my ($symb,$courseid,$domain,$username)=@_;
                   13094:     {
                   13095: 	use integer;
                   13096: 	# strings need to be an even # of cahracters long, it it is odd the
                   13097:         # last characters gets thrown away
                   13098: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13099: 	my $symbseed=numval3($symb) << 10;
                   13100: 	my $namechck=unpack("%32S*",$username.' ');
                   13101: 	
                   13102: 	my $nameseed=numval3($username) << 21;
                   13103: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13104: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13105: 	
                   13106: 	my $num1=$symbchck+$symbseed+$namechck;
                   13107: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13108: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13109: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13110: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13111: 	
1.575     albertel 13112: 	return "$num1:$num2";
                   13113:     }
                   13114: }
                   13115: 
1.675     albertel 13116: sub rndseed_64bit5 {
                   13117:     my ($symb,$courseid,$domain,$username)=@_;
                   13118:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13119:     return "$num1:$num2";
                   13120: }
                   13121: 
1.366     albertel 13122: sub rndseed_CODE_64bit {
                   13123:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13124:     {
1.366     albertel 13125: 	use integer;
1.443     albertel 13126: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13127: 	my $symbseed=numval2($symb);
1.491     albertel 13128: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13129: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13130: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13131: 	my $num1=$symbseed+$CODEchck;
                   13132: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13133: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13134: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13135: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13136: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13137: 	return "$num1:$num2";
1.366     albertel 13138:     }
                   13139: }
                   13140: 
1.575     albertel 13141: sub rndseed_CODE_64bit4 {
                   13142:     my ($symb,$courseid,$domain,$username)=@_;
                   13143:     {
                   13144: 	use integer;
                   13145: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13146: 	my $symbseed=numval3($symb);
                   13147: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13148: 	my $CODEseed=numval3(&getCODE());
                   13149: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13150: 	my $num1=$symbseed+$CODEchck;
                   13151: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13152: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13153: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13154: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13155: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13156: 	return "$num1:$num2";
                   13157:     }
                   13158: }
                   13159: 
1.675     albertel 13160: sub rndseed_CODE_64bit5 {
                   13161:     my ($symb,$courseid,$domain,$username)=@_;
                   13162:     my $code = &getCODE();
                   13163:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13164:     return "$num1:$num2";
                   13165: }
                   13166: 
1.366     albertel 13167: sub setup_random_from_rndseed {
                   13168:     my ($rndseed)=@_;
1.503     albertel 13169:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13170:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13171:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13172:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13173:         } else {
                   13174:             &Math::Random::random_set_seed($num1,$num2);
                   13175:         }
1.366     albertel 13176:     } else {
                   13177: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13178:     }
1.36      albertel 13179: }
                   13180: 
1.474     albertel 13181: sub latest_receipt_algorithm_id {
1.835     albertel 13182:     return 'receipt3';
1.474     albertel 13183: }
                   13184: 
1.480     www      13185: sub recunique {
                   13186:     my $fucourseid=shift;
                   13187:     my $unique;
1.835     albertel 13188:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13189: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13190: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13191:     } else {
                   13192: 	$unique=$perlvar{'lonReceipt'};
                   13193:     }
                   13194:     return unpack("%32C*",$unique);
                   13195: }
                   13196: 
                   13197: sub recprefix {
                   13198:     my $fucourseid=shift;
                   13199:     my $prefix;
1.835     albertel 13200:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13201: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13202: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13203:     } else {
                   13204: 	$prefix=$perlvar{'lonHostID'};
                   13205:     }
                   13206:     return unpack("%32C*",$prefix);
                   13207: }
                   13208: 
1.76      www      13209: sub ireceipt {
1.474     albertel 13210:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13211: 
                   13212:     my $return =&recprefix($fucourseid).'-';
                   13213: 
                   13214:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13215: 	$env{'request.state'} eq 'construct') {
                   13216: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13217: 	return $return;
                   13218:     }
                   13219: 
1.76      www      13220:     my $cuname=unpack("%32C*",$funame);
                   13221:     my $cudom=unpack("%32C*",$fudom);
                   13222:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13223:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13224:     my $cunique=&recunique($fucourseid);
1.474     albertel 13225:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13226:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13227: 
1.790     albertel 13228: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13229: 			       
                   13230: 	$return.= ($cunique%$cuname+
                   13231: 		   $cunique%$cudom+
                   13232: 		   $cusymb%$cuname+
                   13233: 		   $cusymb%$cudom+
                   13234: 		   $cucourseid%$cuname+
                   13235: 		   $cucourseid%$cudom+
                   13236: 		   $cpart%$cuname+
                   13237: 		   $cpart%$cudom);
                   13238:     } else {
                   13239: 	$return.= ($cunique%$cuname+
                   13240: 		   $cunique%$cudom+
                   13241: 		   $cusymb%$cuname+
                   13242: 		   $cusymb%$cudom+
                   13243: 		   $cucourseid%$cuname+
                   13244: 		   $cucourseid%$cudom);
                   13245:     }
                   13246:     return $return;
1.76      www      13247: }
                   13248: 
                   13249: sub receipt {
1.474     albertel 13250:     my ($part)=@_;
1.790     albertel 13251:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13252:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13253: }
1.260     ng       13254: 
1.790     albertel 13255: sub whichuser {
                   13256:     my ($passedsymb)=@_;
                   13257:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13258:     if (defined($env{'form.grade_symb'})) {
                   13259: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13260: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13261: 	if (!$allowed &&
                   13262: 	    exists($env{'request.course.sec'}) &&
                   13263: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13264: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13265: 			      '/'.$env{'request.course.sec'});
                   13266: 	}
                   13267: 	if ($allowed) {
                   13268: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13269: 	    $courseid=$tmp_courseid;
                   13270: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13271: 	    ($name)=&get_env_multiple('form.grade_username');
                   13272: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13273: 	}
                   13274:     }
                   13275:     if (!$passedsymb) {
                   13276: 	$symb=&symbread();
                   13277:     } else {
                   13278: 	$symb=$passedsymb;
                   13279:     }
                   13280:     $courseid=$env{'request.course.id'};
                   13281:     $domain=$env{'user.domain'};
                   13282:     $name=$env{'user.name'};
                   13283:     if ($name eq 'public' && $domain eq 'public') {
                   13284: 	if (!defined($env{'form.username'})) {
                   13285: 	    $env{'form.username'}.=time.rand(10000000);
                   13286: 	}
                   13287: 	$name.=$env{'form.username'};
                   13288:     }
                   13289:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13290: 
                   13291: }
                   13292: 
1.36      albertel 13293: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13294: # returns either the contents of the file or 
                   13295: # -1 if the file doesn't exist
1.481     raeburn  13296: #
                   13297: # if the target is a file that was uploaded via DOCS, 
                   13298: # a check will be made to see if a current copy exists on the local server,
                   13299: # if it does this will be served, otherwise a copy will be retrieved from
                   13300: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13301: # the local server.   
1.472     albertel 13302: 
1.36      albertel 13303: sub getfile {
1.538     albertel 13304:     my ($file) = @_;
1.609     banghart 13305:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13306:     &repcopy($file);
                   13307:     return &readfile($file);
                   13308: }
                   13309: 
                   13310: sub repcopy_userfile {
                   13311:     my ($file)=@_;
1.1142    raeburn  13312:     my $londocroot = $perlvar{'lonDocRoot'};
                   13313:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13314:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13315:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13316: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13317:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13318:     if (-e "$file") {
1.828     www      13319: # we already have a local copy, check it out
1.538     albertel 13320: 	my @fileinfo = stat($file);
1.828     www      13321: 	my $rtncode;
                   13322: 	my $info;
1.538     albertel 13323: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13324: 	if ($lwpresp ne 'ok') {
1.828     www      13325: # there is no such file anymore, even though we had a local copy
1.482     albertel 13326: 	    if ($rtncode eq '404') {
1.538     albertel 13327: 		unlink($file);
1.482     albertel 13328: 	    }
                   13329: 	    return -1;
                   13330: 	}
                   13331: 	if ($info < $fileinfo[9]) {
1.828     www      13332: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13333: 	    return 'ok';
1.828     www      13334: 	} else {
                   13335: # the file is outdated, get rid of it
                   13336: 	    unlink($file);
1.482     albertel 13337: 	}
1.828     www      13338:     }
                   13339: # one way or the other, at this point, we don't have the file
                   13340: # construct the correct path for the file
                   13341:     my @parts = ($cdom,$cnum); 
                   13342:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13343: 	push @parts, split(/\//,$1);
                   13344:     }
                   13345:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13346:     foreach my $part (@parts) {
                   13347: 	$path .= '/'.$part;
                   13348: 	if (!-e $path) {
                   13349: 	    mkdir($path,0770);
1.482     albertel 13350: 	}
                   13351:     }
1.828     www      13352: # now the path exists for sure
                   13353: # get a user agent
                   13354:     my $transferfile=$file.'.in.transfer';
                   13355: # FIXME: this should flock
                   13356:     if (-e $transferfile) { return 'ok'; }
                   13357:     my $request;
                   13358:     $uri=~s/^\///;
1.980     raeburn  13359:     my $homeserver = &homeserver($cnum,$cdom);
                   13360:     my $protocol = $protocol{$homeserver};
                   13361:     $protocol = 'http' if ($protocol ne 'https');
                   13362:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13363:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13364: # did it work?
                   13365:     if ($response->is_error()) {
                   13366: 	unlink($transferfile);
                   13367: 	&logthis("Userfile repcopy failed for $uri");
                   13368: 	return -1;
                   13369:     }
                   13370: # worked, rename the transfer file
                   13371:     rename($transferfile,$file);
1.607     raeburn  13372:     return 'ok';
1.481     raeburn  13373: }
                   13374: 
1.517     albertel 13375: sub tokenwrapper {
                   13376:     my $uri=shift;
1.980     raeburn  13377:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13378:     $uri=~s|^/||;
1.620     albertel 13379:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13380:     my $token=$1;
1.552     albertel 13381:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13382:     if ($udom && $uname && $file) {
                   13383: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13384:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13385:         my $homeserver = &homeserver($uname,$udom);
                   13386:         my $protocol = $protocol{$homeserver};
                   13387:         $protocol = 'http' if ($protocol ne 'https');
                   13388:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13389:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13390:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13391:     } else {
                   13392:         return '/adm/notfound.html';
                   13393:     }
                   13394: }
                   13395: 
1.828     www      13396: # call with reqtype HEAD: get last modification time
                   13397: # call with reqtype GET: get the file contents
                   13398: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13399: #
1.481     raeburn  13400: sub getuploaded {
                   13401:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13402:     $uri=~s/^\///;
1.980     raeburn  13403:     my $homeserver = &homeserver($cnum,$cdom);
                   13404:     my $protocol = $protocol{$homeserver};
                   13405:     $protocol = 'http' if ($protocol ne 'https');
                   13406:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13407:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13408:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13409:     $$rtncode = $response->code;
1.482     albertel 13410:     if (! $response->is_success()) {
                   13411: 	return 'failed';
                   13412:     }      
                   13413:     if ($reqtype eq 'HEAD') {
1.486     www      13414: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13415:     } elsif ($reqtype eq 'GET') {
                   13416: 	$$info = $response->content;
1.472     albertel 13417:     }
1.482     albertel 13418:     return 'ok';
1.36      albertel 13419: }
                   13420: 
1.481     raeburn  13421: sub readfile {
                   13422:     my $file = shift;
                   13423:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13424:     my $fh;
1.1359    raeburn  13425:     open($fh,"<",$file);
1.481     raeburn  13426:     my $a='';
1.800     albertel 13427:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13428:     return $a;
                   13429: }
                   13430: 
1.36      albertel 13431: sub filelocation {
1.590     banghart 13432:     my ($dir,$file) = @_;
                   13433:     my $location;
                   13434:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13435: 
                   13436:     if ($file =~ m-^/adm/-) {
                   13437: 	$file=~s-^/adm/wrapper/-/-;
                   13438: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13439:     }
1.882     albertel 13440: 
1.1139    www      13441:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13442:         $location = $file;
1.609     banghart 13443:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13444:         my ($udom,$uname,$filename)=
1.811     albertel 13445:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13446:         my $home=&homeserver($uname,$udom);
                   13447:         my $is_me=0;
                   13448:         my @ids=&current_machine_ids();
                   13449:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13450:         if ($is_me) {
1.1117    foxr     13451:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13452:         } else {
                   13453:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13454:   	      $udom.'/'.$uname.'/'.$filename;
                   13455:         }
1.882     albertel 13456:     } elsif ($file =~ m-^/adm/-) {
                   13457: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13458:     } else {
                   13459:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13460:         $file=~s:^/(res|priv)/:/:;
                   13461:         my $space=$1;
1.590     banghart 13462:         if ( !( $file =~ m:^/:) ) {
                   13463:             $location = $dir. '/'.$file;
                   13464:         } else {
1.1142    raeburn  13465:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13466:         }
1.59      albertel 13467:     }
1.590     banghart 13468:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13469:     while ($location=~m{/\.\./}) {
                   13470: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13471: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13472: 	} else {
                   13473: 	    $location=~ s{/\.\./}{/}g;
                   13474: 	}
                   13475:     } #remove dir/..
1.590     banghart 13476:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13477:     return $location;
1.46      www      13478: }
1.36      albertel 13479: 
1.46      www      13480: sub hreflocation {
                   13481:     my ($dir,$file)=@_;
1.980     raeburn  13482:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13483: 	$file=filelocation($dir,$file);
1.700     albertel 13484:     } elsif ($file=~m-^/adm/-) {
                   13485: 	$file=~s-^/adm/wrapper/-/-;
                   13486: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13487:     }
                   13488:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13489: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13490:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13491: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13492: 	        {/uploaded/$1/$2/}x;
1.46      www      13493:     }
1.913     albertel 13494:     if ($file=~ m{^/userfiles/}) {
                   13495: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13496:     }
1.462     albertel 13497:     return $file;
1.465     albertel 13498: }
                   13499: 
1.1139    www      13500: 
                   13501: 
                   13502: 
                   13503: 
1.465     albertel 13504: sub current_machine_domains {
1.853     albertel 13505:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13506: }
                   13507: 
                   13508: sub machine_domains {
                   13509:     my ($hostname) = @_;
1.465     albertel 13510:     my @domains;
1.838     albertel 13511:     my %hostname = &all_hostnames();
1.465     albertel 13512:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13513: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13514: 	if ($hostname eq $name) {
1.844     albertel 13515: 	    push(@domains,&host_domain($id));
1.465     albertel 13516: 	}
                   13517:     }
                   13518:     return @domains;
                   13519: }
                   13520: 
                   13521: sub current_machine_ids {
1.853     albertel 13522:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13523: }
                   13524: 
                   13525: sub machine_ids {
                   13526:     my ($hostname) = @_;
                   13527:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13528:     my @ids;
1.888     albertel 13529:     my %name_to_host = &all_names();
1.889     albertel 13530:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13531: 	return @{ $name_to_host{$hostname} };
                   13532:     }
                   13533:     return;
1.31      www      13534: }
                   13535: 
1.824     raeburn  13536: sub additional_machine_domains {
                   13537:     my @domains;
1.1359    raeburn  13538:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13539:     while( my $line = <$fh>) {
                   13540:         $line =~ s/\s//g;
                   13541:         push(@domains,$line);
                   13542:     }
                   13543:     return @domains;
                   13544: }
                   13545: 
                   13546: sub default_login_domain {
                   13547:     my $domain = $perlvar{'lonDefDomain'};
                   13548:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13549:     foreach my $posdom (&current_machine_domains(),
                   13550:                         &additional_machine_domains()) {
                   13551:         if (lc($posdom) eq lc($testdomain)) {
                   13552:             $domain=$posdom;
                   13553:             last;
                   13554:         }
                   13555:     }
                   13556:     return $domain;
                   13557: }
                   13558: 
1.31      www      13559: # ------------------------------------------------------------- Declutters URLs
                   13560: 
                   13561: sub declutter {
                   13562:     my $thisfn=shift;
1.569     albertel 13563:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13564:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13565:         $thisfn=~s{^/home/httpd/html}{};
                   13566:     }
1.31      www      13567:     $thisfn=~s/^\///;
1.697     albertel 13568:     $thisfn=~s|^adm/wrapper/||;
                   13569:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13570:     $thisfn=~s/^res\///;
1.1172    bisitz   13571:     $thisfn=~s/^priv\///;
1.1032    raeburn  13572:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13573:         $thisfn=~s/\?.+$//;
                   13574:     }
1.268     www      13575:     return $thisfn;
                   13576: }
                   13577: 
                   13578: # ------------------------------------------------------------- Clutter up URLs
                   13579: 
                   13580: sub clutter {
                   13581:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13582:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13583: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13584:        $thisfn='/res'.$thisfn; 
                   13585:     }
1.1031    raeburn  13586:     if ($thisfn !~m|^/adm|) {
                   13587: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13588: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13589: 	} else {
                   13590: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13591: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13592: 	    if ($embstyle eq 'ssi'
                   13593: 		|| ($embstyle eq 'hdn')
                   13594: 		|| ($embstyle eq 'rat')
                   13595: 		|| ($embstyle eq 'prv')
                   13596: 		|| ($embstyle eq 'ign')) {
                   13597: 		#do nothing with these
                   13598: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13599: 		|| ($embstyle eq 'emb')
                   13600: 		|| ($embstyle eq 'wrp')) {
                   13601: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13602: 	    } elsif ($embstyle eq 'unk'
                   13603: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13604: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13605: 	    } else {
1.718     www      13606: #		&logthis("Got a blank emb style");
1.695     albertel 13607: 	    }
1.694     albertel 13608: 	}
1.1343    raeburn  13609:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13610:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13611:     }
1.31      www      13612:     return $thisfn;
1.12      www      13613: }
                   13614: 
1.787     albertel 13615: sub clutter_with_no_wrapper {
                   13616:     my $uri = &clutter(shift);
                   13617:     if ($uri =~ m-^/adm/-) {
                   13618: 	$uri =~ s-^/adm/wrapper/-/-;
                   13619: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13620:     }
                   13621:     return $uri;
                   13622: }
                   13623: 
1.557     albertel 13624: sub freeze_escape {
                   13625:     my ($value)=@_;
                   13626:     if (ref($value)) {
                   13627: 	$value=&nfreeze($value);
                   13628: 	return '__FROZEN__'.&escape($value);
                   13629:     }
                   13630:     return &escape($value);
                   13631: }
                   13632: 
1.11      www      13633: 
1.557     albertel 13634: sub thaw_unescape {
                   13635:     my ($value)=@_;
                   13636:     if ($value =~ /^__FROZEN__/) {
                   13637: 	substr($value,0,10,undef);
                   13638: 	$value=&unescape($value);
                   13639: 	return &thaw($value);
                   13640:     }
                   13641:     return &unescape($value);
                   13642: }
                   13643: 
1.436     albertel 13644: sub correct_line_ends {
                   13645:     my ($result)=@_;
                   13646:     $$result =~s/\r\n/\n/mg;
                   13647:     $$result =~s/\r/\n/mg;
1.415     albertel 13648: }
1.1       albertel 13649: # ================================================================ Main Program
                   13650: 
1.184     www      13651: sub goodbye {
1.204     albertel 13652:    &logthis("Starting Shut down");
1.443     albertel 13653: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13654:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13655: #converted
1.599     albertel 13656: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13657:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13658: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13659: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13660: #1.1 only
1.870     albertel 13661: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13662: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13663: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13664: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13665:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13666:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13667:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13668:    &flushcourselogs();
                   13669:    &logthis("Shutting down");
                   13670: }
                   13671: 
1.852     albertel 13672: sub get_dns {
1.1210    raeburn  13673:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13674:     if (!$ignore_cache) {
                   13675: 	my ($content,$cached)=
                   13676: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13677: 	if ($cached) {
1.1210    raeburn  13678: 	    &$func($content,$hashref);
1.869     albertel 13679: 	    return;
                   13680: 	}
                   13681:     }
                   13682: 
                   13683:     my %alldns;
1.1379    raeburn  13684:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13685:         foreach my $dns (<$config>) {
                   13686: 	    next if ($dns !~ /^\^(\S*)/x);
                   13687:             my $line = $1;
                   13688:             my ($host,$protocol) = split(/:/,$line);
                   13689:             if ($protocol ne 'https') {
                   13690:                 $protocol = 'http';
                   13691:             }
                   13692: 	    $alldns{$host} = $protocol;
1.979     raeburn  13693:         }
1.1379    raeburn  13694:         close($config);
1.869     albertel 13695:     }
                   13696:     while (%alldns) {
1.1263    raeburn  13697: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13698: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13699:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13700:         delete($alldns{$dns});
1.852     albertel 13701: 	next if ($response->is_error());
1.1379    raeburn  13702:         if ($url eq '/adm/dns/loncapaCRL') {
                   13703:             return &$func($response);
                   13704:         } else {
                   13705: 	    my @content = split("\n",$response->content);
                   13706: 	    unless ($nocache) {
                   13707: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   13708: 	    }
                   13709: 	    &$func(\@content,$hashref);
                   13710:             return;
                   13711:         }
                   13712:     }
                   13713:     my $which = (split('/',$url,4))[3];
                   13714:     if ($which eq 'loncapaCRL') {
                   13715:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   13716:         if (-e $diskfile) {
                   13717:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   13718:         } else {
                   13719:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   13720:         }
                   13721:     } else {
                   13722:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13723:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13724:             my @content = <$config>;
                   13725:             close($config);
                   13726:             &$func(\@content,$hashref);
                   13727:         }
1.852     albertel 13728:     }
1.1210    raeburn  13729:     return;
                   13730: }
                   13731: 
                   13732: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13733: sub parse_dns_checksums_tab {
1.1210    raeburn  13734:     my ($lines,$hashref) = @_;
1.1264    raeburn  13735:     my $lonhost = $perlvar{'lonHostID'};
                   13736:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13737:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13738:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13739:     my $webconfdir = '/etc/httpd/conf';
                   13740:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13741:         $webconfdir = '/etc/apache2';
                   13742:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13743:         if ($1 >= 10) {
                   13744:             $webconfdir = '/etc/apache2';
                   13745:         }
                   13746:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13747:         if ($1 >= 10.0) {
                   13748:             $webconfdir = '/etc/apache2';
                   13749:         }
                   13750:     }
1.1210    raeburn  13751:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13752:     my (%chksum,%revnum);
                   13753:     if (ref($lines) eq 'ARRAY') {
                   13754:         chomp(@{$lines});
1.1238    raeburn  13755:         my $version = shift(@{$lines});
                   13756:         if ($version eq $release) {  
1.1210    raeburn  13757:             foreach my $line (@{$lines}) {
1.1238    raeburn  13758:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13759:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13760:                     if ($webconfdir eq '/etc/apache2') {
                   13761:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13762:                     }
                   13763:                 }
1.1238    raeburn  13764:                 $chksum{$file} = $shasum;
                   13765:                 $revnum{$file} = $version;
1.1210    raeburn  13766:             }
                   13767:             if (ref($hashref) eq 'HASH') {
                   13768:                 %{$hashref} = (
                   13769:                                 sums     => \%chksum,
                   13770:                                 versions => \%revnum,
                   13771:                               );
                   13772:             }
                   13773:         }
                   13774:     }
1.869     albertel 13775:     return;
1.852     albertel 13776: }
1.1210    raeburn  13777: 
                   13778: sub fetch_dns_checksums {
1.1238    raeburn  13779:     my %checksums;
                   13780:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13781:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13782:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13783:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13784:              \%checksums);
1.1210    raeburn  13785:     return \%checksums;
                   13786: }
                   13787: 
1.1379    raeburn  13788: sub fetch_crl_pemfile {
                   13789:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   13790: }
                   13791: 
                   13792: sub save_crl_pem {
                   13793:     my ($response) = @_;
1.1380    raeburn  13794:     my ($msg,$hadchanges);
1.1379    raeburn  13795:     if (ref($response)) {
                   13796:         my $now = time;
                   13797:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   13798:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   13799:         if (open(my $fh,'>',"$tmpcrl")) {
                   13800:             print $fh $response->content;
                   13801:             close($fh);
                   13802:             if (-e $lonca) {
                   13803:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   13804:                     my $check = <PIPE>;
                   13805:                     close(PIPE);
                   13806:                     chomp($check);
                   13807:                     if ($check eq 'verify OK') {
                   13808:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  13809:                         my $backup;
1.1379    raeburn  13810:                         if (-e $dest) {
1.1380    raeburn  13811:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   13812:                                 $backup = 'ok';
                   13813:                             }
1.1379    raeburn  13814:                         }
                   13815:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   13816:                             $msg = 'ok';
1.1380    raeburn  13817:                             if ($backup) {
                   13818:                                 my (%oldnums,%newnums);
                   13819:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   13820:                                     while (<PIPE>) {
                   13821:                                         $oldnums{(split(/:/))[1]} = 1;
                   13822:                                     }
                   13823:                                     close(PIPE);
                   13824:                                 }
                   13825:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   13826:                                     while(<PIPE>) {
                   13827:                                         $newnums{(split(/:/))[1]} = 1;
                   13828:                                     }
                   13829:                                     close(PIPE);
                   13830:                                 }
                   13831:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   13832:                                     unless (exists($oldnums{$key})) {
                   13833:                                         $hadchanges = 1;
                   13834:                                         last;
                   13835:                                     }
                   13836:                                 }
                   13837:                                 unless ($hadchanges) {
                   13838:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   13839:                                         unless (exists($newnums{$key})) {
                   13840:                                             $hadchanges = 1;
                   13841:                                             last;
                   13842:                                         }
                   13843:                                     }
                   13844:                                 }
                   13845:                             }
1.1379    raeburn  13846:                         }
                   13847:                     } else {
                   13848:                         unlink($tmpcrl);
                   13849:                     }
                   13850:                 } else {
                   13851:                     unlink($tmpcrl);
                   13852:                 }
                   13853:             } else {
                   13854:                 unlink($tmpcrl);
                   13855:             }
                   13856:         }
                   13857:     }
1.1380    raeburn  13858:     return ($msg,$hadchanges);
1.1379    raeburn  13859: }
                   13860: 
1.327     albertel 13861: # ------------------------------------------------------------ Read domain file
                   13862: {
1.852     albertel 13863:     my $loaded;
1.846     albertel 13864:     my %domain;
                   13865: 
1.852     albertel 13866:     sub parse_domain_tab {
                   13867: 	my ($lines) = @_;
                   13868: 	foreach my $line (@$lines) {
                   13869: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13870: 
1.846     albertel 13871: 	    chomp($line);
1.852     albertel 13872: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13873: 	    my %this_domain;
                   13874: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13875: 			       'lang_def', 'city', 'longi', 'lati',
                   13876: 			       'primary') {
                   13877: 		$this_domain{$field} = shift(@elements);
                   13878: 	    }
                   13879: 	    $domain{$name} = \%this_domain;
1.852     albertel 13880: 	}
                   13881:     }
1.864     albertel 13882: 
                   13883:     sub reset_domain_info {
                   13884: 	undef($loaded);
                   13885: 	undef(%domain);
                   13886:     }
                   13887: 
1.852     albertel 13888:     sub load_domain_tab {
1.1293    raeburn  13889: 	my ($ignore_cache,$nocache) = @_;
                   13890: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13891: 	my $fh;
1.1359    raeburn  13892: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13893: 	    my @lines = <$fh>;
                   13894: 	    &parse_domain_tab(\@lines);
1.448     albertel 13895: 	}
1.852     albertel 13896: 	close($fh);
                   13897: 	$loaded = 1;
1.327     albertel 13898:     }
1.846     albertel 13899: 
                   13900:     sub domain {
1.852     albertel 13901: 	&load_domain_tab() if (!$loaded);
                   13902: 
1.846     albertel 13903: 	my ($name,$what) = @_;
                   13904: 	return if ( !exists($domain{$name}) );
                   13905: 
                   13906: 	if (!$what) {
                   13907: 	    return $domain{$name}{'description'};
                   13908: 	}
                   13909: 	return $domain{$name}{$what};
                   13910:     }
1.974     raeburn  13911: 
                   13912:     sub domain_info {
                   13913:         &load_domain_tab() if (!$loaded);
                   13914:         return %domain;
                   13915:     }
                   13916: 
1.327     albertel 13917: }
                   13918: 
                   13919: 
1.1       albertel 13920: # ------------------------------------------------------------- Read hosts file
                   13921: {
1.838     albertel 13922:     my %hostname;
1.844     albertel 13923:     my %hostdom;
1.845     albertel 13924:     my %libserv;
1.852     albertel 13925:     my $loaded;
1.888     albertel 13926:     my %name_to_host;
1.1074    raeburn  13927:     my %internetdom;
1.1107    raeburn  13928:     my %LC_dns_serv;
1.852     albertel 13929: 
                   13930:     sub parse_hosts_tab {
                   13931: 	my ($file) = @_;
                   13932: 	foreach my $configline (@$file) {
                   13933: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13934:             chomp($configline);
                   13935: 	    if ($configline =~ /^\^/) {
                   13936:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13937:                     $LC_dns_serv{$1} = 1;
                   13938:                 }
                   13939:                 next;
                   13940:             }
1.1074    raeburn  13941: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13942: 	    $name=~s/\s//g;
                   13943: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13944:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13945:                     my $curr = $hostname{$id};
                   13946:                     my $skip;
                   13947:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13948:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13949:                             $skip = 1;
                   13950:                         } else {
                   13951:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13952:                         }
                   13953:                     }
                   13954:                     unless ($skip) {
                   13955:                         push(@{$name_to_host{$name}},$id);
                   13956:                     }
                   13957:                 } else {
                   13958:                     push(@{$name_to_host{$name}},$id);
                   13959:                 }
1.852     albertel 13960: 		$hostname{$id}=$name;
                   13961: 		$hostdom{$id}=$domain;
                   13962: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13963:                 if (defined($protocol)) {
                   13964:                     if ($protocol eq 'https') {
                   13965:                         $protocol{$id} = $protocol;
                   13966:                     } else {
                   13967:                         $protocol{$id} = 'http'; 
                   13968:                     }
1.968     raeburn  13969:                 } else {
1.969     raeburn  13970:                     $protocol{$id} = 'http';
1.968     raeburn  13971:                 }
1.1074    raeburn  13972:                 if (defined($intdom)) {
                   13973:                     $internetdom{$id} = $intdom;
                   13974:                 }
1.852     albertel 13975: 	    }
                   13976: 	}
                   13977:     }
1.864     albertel 13978:     
                   13979:     sub reset_hosts_info {
1.897     albertel 13980: 	&purge_remembered();
1.864     albertel 13981: 	&reset_domain_info();
                   13982: 	&reset_hosts_ip_info();
1.1339    raeburn  13983:         undef(%internetdom);
1.892     albertel 13984: 	undef(%name_to_host);
1.864     albertel 13985: 	undef(%hostname);
                   13986: 	undef(%hostdom);
                   13987: 	undef(%libserv);
                   13988: 	undef($loaded);
                   13989:     }
1.1       albertel 13990: 
1.852     albertel 13991:     sub load_hosts_tab {
1.1293    raeburn  13992: 	my ($ignore_cache,$nocache) = @_;
                   13993: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13994: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13995: 	my @config = <$config>;
                   13996: 	&parse_hosts_tab(\@config);
                   13997: 	close($config);
                   13998: 	$loaded=1;
1.1       albertel 13999:     }
1.852     albertel 14000: 
1.838     albertel 14001:     sub hostname {
1.852     albertel 14002: 	&load_hosts_tab() if (!$loaded);
                   14003: 
1.838     albertel 14004: 	my ($lonid) = @_;
                   14005: 	return $hostname{$lonid};
                   14006:     }
1.845     albertel 14007: 
1.838     albertel 14008:     sub all_hostnames {
1.852     albertel 14009: 	&load_hosts_tab() if (!$loaded);
                   14010: 
1.838     albertel 14011: 	return %hostname;
                   14012:     }
1.845     albertel 14013: 
1.888     albertel 14014:     sub all_names {
1.1293    raeburn  14015:         my ($ignore_cache,$nocache) = @_;
                   14016: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14017: 
                   14018: 	return %name_to_host;
                   14019:     }
                   14020: 
1.974     raeburn  14021:     sub all_host_domain {
                   14022:         &load_hosts_tab() if (!$loaded);
                   14023:         return %hostdom;
                   14024:     }
                   14025: 
1.1339    raeburn  14026:     sub all_host_intdom {
                   14027:         &load_hosts_tab() if (!$loaded);
                   14028:         return %internetdom;
                   14029:     }
                   14030: 
1.845     albertel 14031:     sub is_library {
1.852     albertel 14032: 	&load_hosts_tab() if (!$loaded);
                   14033: 
1.845     albertel 14034: 	return exists($libserv{$_[0]});
                   14035:     }
                   14036: 
                   14037:     sub all_library {
1.852     albertel 14038: 	&load_hosts_tab() if (!$loaded);
                   14039: 
1.845     albertel 14040: 	return %libserv;
                   14041:     }
                   14042: 
1.1062    droeschl 14043:     sub unique_library {
                   14044: 	#2x reverse removes all hostnames that appear more than once
                   14045:         my %unique = reverse &all_library();
                   14046:         return reverse %unique;
                   14047:     }
                   14048: 
1.841     albertel 14049:     sub get_servers {
1.852     albertel 14050: 	&load_hosts_tab() if (!$loaded);
                   14051: 
1.841     albertel 14052: 	my ($domain,$type) = @_;
                   14053: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14054: 	                                          : %hostname;
                   14055: 	my %result;
1.842     albertel 14056: 	if (ref($domain) eq 'ARRAY') {
                   14057: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14058: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14059: 		    $result{$host} = $hostname;
                   14060: 		}
                   14061: 	    }
                   14062: 	} else {
                   14063: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14064: 		if ($hostdom{$host} eq $domain) {
                   14065: 		    $result{$host} = $hostname;
                   14066: 		}
1.841     albertel 14067: 	    }
                   14068: 	}
                   14069: 	return %result;
                   14070:     }
1.845     albertel 14071: 
1.1062    droeschl 14072:     sub get_unique_servers {
                   14073:         my %unique = reverse &get_servers(@_);
                   14074: 	return reverse %unique;
                   14075:     }
                   14076: 
1.844     albertel 14077:     sub host_domain {
1.852     albertel 14078: 	&load_hosts_tab() if (!$loaded);
                   14079: 
1.844     albertel 14080: 	my ($lonid) = @_;
                   14081: 	return $hostdom{$lonid};
                   14082:     }
                   14083: 
1.841     albertel 14084:     sub all_domains {
1.852     albertel 14085: 	&load_hosts_tab() if (!$loaded);
                   14086: 
1.841     albertel 14087: 	my %seen;
                   14088: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14089: 	return @uniq;
                   14090:     }
1.1074    raeburn  14091: 
                   14092:     sub internet_dom {
                   14093:         &load_hosts_tab() if (!$loaded);
                   14094: 
                   14095:         my ($lonid) = @_;
                   14096:         return $internetdom{$lonid};
                   14097:     }
1.1107    raeburn  14098: 
                   14099:     sub is_LC_dns {
                   14100:         &load_hosts_tab() if (!$loaded);
                   14101: 
                   14102:         my ($hostname) = @_;
                   14103:         return exists($LC_dns_serv{$hostname});
                   14104:     }
                   14105: 
1.1       albertel 14106: }
                   14107: 
1.847     albertel 14108: { 
                   14109:     my %iphost;
1.856     albertel 14110:     my %name_to_ip;
                   14111:     my %lonid_to_ip;
1.869     albertel 14112: 
1.847     albertel 14113:     sub get_hosts_from_ip {
                   14114: 	my ($ip) = @_;
                   14115: 	my %iphosts = &get_iphost();
                   14116: 	if (ref($iphosts{$ip})) {
                   14117: 	    return @{$iphosts{$ip}};
                   14118: 	}
                   14119: 	return;
1.839     albertel 14120:     }
1.864     albertel 14121:     
                   14122:     sub reset_hosts_ip_info {
                   14123: 	undef(%iphost);
                   14124: 	undef(%name_to_ip);
                   14125: 	undef(%lonid_to_ip);
                   14126:     }
1.856     albertel 14127: 
                   14128:     sub get_host_ip {
                   14129: 	my ($lonid) = @_;
                   14130: 	if (exists($lonid_to_ip{$lonid})) {
                   14131: 	    return $lonid_to_ip{$lonid};
                   14132: 	}
                   14133: 	my $name=&hostname($lonid);
                   14134:    	my $ip = gethostbyname($name);
                   14135: 	return if (!$ip || length($ip) ne 4);
                   14136: 	$ip=inet_ntoa($ip);
                   14137: 	$name_to_ip{$name}   = $ip;
                   14138: 	$lonid_to_ip{$lonid} = $ip;
                   14139: 	return $ip;
                   14140:     }
1.847     albertel 14141:     
                   14142:     sub get_iphost {
1.1293    raeburn  14143: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14144: 
1.869     albertel 14145: 	if (!$ignore_cache) {
                   14146: 	    if (%iphost) {
                   14147: 		return %iphost;
                   14148: 	    }
                   14149: 	    my ($ip_info,$cached)=
                   14150: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14151: 	    if ($cached) {
                   14152: 		%iphost      = %{$ip_info->[0]};
                   14153: 		%name_to_ip  = %{$ip_info->[1]};
                   14154: 		%lonid_to_ip = %{$ip_info->[2]};
                   14155: 		return %iphost;
                   14156: 	    }
                   14157: 	}
1.894     albertel 14158: 
                   14159: 	# get yesterday's info for fallback
                   14160: 	my %old_name_to_ip;
                   14161: 	my ($ip_info,$cached)=
                   14162: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14163: 	if ($cached) {
                   14164: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14165: 	}
                   14166: 
1.1293    raeburn  14167: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14168: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14169: 	    my $ip;
                   14170: 	    if (!exists($name_to_ip{$name})) {
                   14171: 		$ip = gethostbyname($name);
                   14172: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14173: 		    if (defined($old_name_to_ip{$name})) {
                   14174: 			$ip = $old_name_to_ip{$name};
                   14175: 			&logthis("Can't find $name defaulting to old $ip");
                   14176: 		    } else {
                   14177: 			&logthis("Name $name no IP found");
                   14178: 			next;
                   14179: 		    }
                   14180: 		} else {
                   14181: 		    $ip=inet_ntoa($ip);
1.847     albertel 14182: 		}
                   14183: 		$name_to_ip{$name} = $ip;
                   14184: 	    } else {
                   14185: 		$ip = $name_to_ip{$name};
1.653     albertel 14186: 	    }
1.888     albertel 14187: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14188: 		$lonid_to_ip{$id} = $ip;
                   14189: 	    }
                   14190: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14191: 	}
1.1293    raeburn  14192:         unless ($nocache) {
                   14193: 	    &do_cache_new('iphost','iphost',
                   14194: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14195: 		          48*60*60);
                   14196:         }
1.869     albertel 14197: 
1.847     albertel 14198: 	return %iphost;
1.598     albertel 14199:     }
                   14200: 
1.992     raeburn  14201:     #
                   14202:     #  Given a DNS returns the loncapa host name for that DNS 
                   14203:     # 
                   14204:     sub host_from_dns {
                   14205:         my ($dns) = @_;
                   14206:         my @hosts;
                   14207:         my $ip;
                   14208: 
1.993     raeburn  14209:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14210:             $ip = $name_to_ip{$dns};
                   14211:         }
                   14212:         if (!$ip) {
                   14213:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14214:             if (length($ip) == 4) { 
                   14215: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14216:             }
                   14217:         }
                   14218:         if ($ip) {
                   14219: 	    @hosts = get_hosts_from_ip($ip);
                   14220: 	    return $hosts[0];
                   14221:         }
                   14222:         return undef;
1.986     foxr     14223:     }
1.992     raeburn  14224: 
1.1074    raeburn  14225:     sub get_internet_names {
                   14226:         my ($lonid) = @_;
                   14227:         return if ($lonid eq '');
                   14228:         my ($idnref,$cached)=
                   14229:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14230:         if ($cached) {
                   14231:             return $idnref;
                   14232:         }
                   14233:         my $ip = &get_host_ip($lonid);
                   14234:         my @hosts = &get_hosts_from_ip($ip);
                   14235:         my %iphost = &get_iphost();
                   14236:         my (@idns,%seen);
                   14237:         foreach my $id (@hosts) {
                   14238:             my $dom = &host_domain($id);
                   14239:             my $prim_id = &domain($dom,'primary');
                   14240:             my $prim_ip = &get_host_ip($prim_id);
                   14241:             next if ($seen{$prim_ip});
                   14242:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14243:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14244:                     my $intdom = &internet_dom($id);
                   14245:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14246:                         push(@idns,$intdom);
                   14247:                     }
                   14248:                 }
                   14249:             }
                   14250:             $seen{$prim_ip} = 1;
                   14251:         }
1.1219    raeburn  14252:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14253:     }
                   14254: 
1.986     foxr     14255: }
                   14256: 
1.1079    raeburn  14257: sub all_loncaparevs {
1.1249    raeburn  14258:     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  14259: }
                   14260: 
1.1227    raeburn  14261: # ---------------------------------------------------------- Read loncaparev table
                   14262: {
                   14263:     sub load_loncaparevs { 
                   14264:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14265:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14266:                 while (my $configline=<$config>) {
                   14267:                     chomp($configline);
                   14268:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14269:                     $loncaparevs{$hostid}=$loncaparev;
                   14270:                 }
                   14271:                 close($config);
                   14272:             }
                   14273:         }
                   14274:     }
                   14275: }
                   14276: 
                   14277: # ---------------------------------------------------------- Read serverhostID table
                   14278: {
                   14279:     sub load_serverhomeIDs {
                   14280:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14281:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14282:                 while (my $configline=<$config>) {
                   14283:                     chomp($configline);
                   14284:                     my ($name,$id)=split(/:/,$configline);
                   14285:                     $serverhomeIDs{$name}=$id;
                   14286:                 }
                   14287:                 close($config);
                   14288:             }
                   14289:         }
                   14290:     }
                   14291: }
                   14292: 
                   14293: 
1.862     albertel 14294: BEGIN {
                   14295: 
                   14296: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14297:     unless ($readit) {
                   14298: {
                   14299:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14300:     %perlvar = (%perlvar,%{$configvars});
                   14301: }
                   14302: 
                   14303: 
1.1       albertel 14304: # ------------------------------------------------------ Read spare server file
                   14305: {
1.1359    raeburn  14306:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14307: 
                   14308:     while (my $configline=<$config>) {
                   14309:        chomp($configline);
1.284     matthew  14310:        if ($configline) {
1.784     albertel 14311: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14312: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14313: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14314:        }
                   14315:     }
1.448     albertel 14316:     close($config);
1.1       albertel 14317: }
1.11      www      14318: # ------------------------------------------------------------ Read permissions
                   14319: {
1.1359    raeburn  14320:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14321: 
                   14322:     while (my $configline=<$config>) {
1.448     albertel 14323: 	chomp($configline);
                   14324: 	if ($configline) {
                   14325: 	    my ($role,$perm)=split(/ /,$configline);
                   14326: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14327: 	}
1.11      www      14328:     }
1.448     albertel 14329:     close($config);
1.11      www      14330: }
                   14331: 
                   14332: # -------------------------------------------- Read plain texts for permissions
                   14333: {
1.1359    raeburn  14334:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14335: 
                   14336:     while (my $configline=<$config>) {
1.448     albertel 14337: 	chomp($configline);
                   14338: 	if ($configline) {
1.742     raeburn  14339: 	    my ($short,@plain)=split(/:/,$configline);
                   14340:             %{$prp{$short}} = ();
                   14341: 	    if (@plain > 0) {
                   14342:                 $prp{$short}{'std'} = $plain[0];
                   14343:                 for (my $i=1; $i<@plain; $i++) {
                   14344:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14345:                 }
                   14346:             }
1.448     albertel 14347: 	}
1.135     www      14348:     }
1.448     albertel 14349:     close($config);
1.135     www      14350: }
                   14351: 
                   14352: # ---------------------------------------------------------- Read package table
                   14353: {
1.1359    raeburn  14354:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14355: 
                   14356:     while (my $configline=<$config>) {
1.483     albertel 14357: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14358: 	chomp($configline);
                   14359: 	my ($short,$plain)=split(/:/,$configline);
                   14360: 	my ($pack,$name)=split(/\&/,$short);
                   14361: 	if ($plain ne '') {
                   14362: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14363: 	    $packagetab{$short}=$plain; 
                   14364: 	}
1.11      www      14365:     }
1.448     albertel 14366:     close($config);
1.329     matthew  14367: }
                   14368: 
1.1073    raeburn  14369: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14370: 
                   14371: &load_loncaparevs();
1.1073    raeburn  14372: 
1.1074    raeburn  14373: # ---------------------------------------------------------- Read serverhostID table
                   14374: 
1.1227    raeburn  14375: &load_serverhomeIDs();
                   14376: 
                   14377: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14378: {
                   14379:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14380:     if (-e $file) {
                   14381:         my $parser = HTML::LCParser->new($file);
                   14382:         while (my $token = $parser->get_token()) {
                   14383:             if ($token->[0] eq 'S') {
                   14384:                 my $item = $token->[1];
                   14385:                 my $name = $token->[2]{'name'};
                   14386:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14387:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14388:                 my $namematch = $token->[2]{'namematch'};
                   14389:                 if ($item eq 'parameter') {
                   14390:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14391:                         my $release = $parser->get_text();
                   14392:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14393:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14394:                     }
                   14395:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14396:                     my $release = $parser->get_text();
                   14397:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14398:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14399:                 }
                   14400:             }
                   14401:         }
                   14402:     }
1.1073    raeburn  14403: }
                   14404: 
1.1138    raeburn  14405: # ---------------------------------------------------------- Read managers table
                   14406: {
                   14407:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14408:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14409:             while (my $configline=<$config>) {
                   14410:                 chomp($configline);
                   14411:                 next if ($configline =~ /^\#/);
                   14412:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14413:                     $managerstab{$configline} = 1;
                   14414:                 }
                   14415:             }
                   14416:             close($config);
                   14417:         }
                   14418:     }
                   14419: }
                   14420: 
1.329     matthew  14421: # ------------- set up temporary directory
                   14422: {
1.1117    foxr     14423:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14424: 
1.11      www      14425: }
                   14426: 
1.794     albertel 14427: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14428: 				'compress_threshold'=> 20_000,
                   14429:  			        });
1.185     www      14430: 
1.281     www      14431: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14432: $dumpcount=0;
1.958     www      14433: $locknum=0;
1.22      www      14434: 
1.163     harris41 14435: &logtouch();
1.672     albertel 14436: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14437: $readit=1;
1.564     albertel 14438:     {
                   14439: 	use integer;
                   14440: 	my $test=(2**32)+1;
1.568     albertel 14441: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14442: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14443:     }
1.195     www      14444: }
1.1       albertel 14445: }
1.179     www      14446: 
1.1       albertel 14447: 1;
1.191     harris41 14448: __END__
                   14449: 
1.243     albertel 14450: =pod
                   14451: 
1.191     harris41 14452: =head1 NAME
                   14453: 
1.243     albertel 14454: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14455: 
                   14456: =head1 SYNOPSIS
                   14457: 
1.243     albertel 14458: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14459: 
                   14460:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14461: 
1.243     albertel 14462: Common parameters:
                   14463: 
                   14464: =over 4
                   14465: 
                   14466: =item *
                   14467: 
                   14468: $uname : an internal username (if $cname expecting a course Id specifically)
                   14469: 
                   14470: =item *
                   14471: 
                   14472: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14473: 
                   14474: =item *
                   14475: 
                   14476: $symb : a resource instance identifier
                   14477: 
                   14478: =item *
                   14479: 
                   14480: $namespace : the name of a .db file that contains the data needed or
                   14481: being set.
                   14482: 
                   14483: =back
                   14484: 
1.394     bowersj2 14485: =head1 OVERVIEW
1.191     harris41 14486: 
1.394     bowersj2 14487: lonnet provides subroutines which interact with the
                   14488: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14489: about classes, users, and resources.
1.243     albertel 14490: 
                   14491: For many of these objects you can also use this to store data about
                   14492: them or modify them in various ways.
1.191     harris41 14493: 
1.394     bowersj2 14494: =head2 Symbs
1.191     harris41 14495: 
1.394     bowersj2 14496: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14497: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14498: map, the resource number of the resource in the map, and the URL of
                   14499: the resource itself. The latter is somewhat redundant, but might help
                   14500: if maps change.
                   14501: 
                   14502: An example is
                   14503: 
                   14504:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14505: 
                   14506: The respective map entry is
                   14507: 
                   14508:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14509:   title="Problem 2">
                   14510:  </resource>
                   14511: 
                   14512: Symbs are used by the random number generator, as well as to store and
                   14513: restore data specific to a certain instance of for example a problem.
                   14514: 
                   14515: =head2 Storing And Retrieving Data
                   14516: 
                   14517: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14518: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14519: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14520: is is the non-critical message twin of cstore. These functions are for
                   14521: handlers to store a perl hash to a user's permanent data space in an
                   14522: easy manner, and to retrieve it again on another call. It is expected
                   14523: that a handler would use this once at the beginning to retrieve data,
                   14524: and then again once at the end to send only the new data back.
                   14525: 
                   14526: The data is stored in the user's data directory on the user's
                   14527: homeserver under the ID of the course.
                   14528: 
                   14529: The hash that is returned by restore will have all of the previous
                   14530: value for all of the elements of the hash.
                   14531: 
                   14532: Example:
                   14533: 
                   14534:  #creating a hash
                   14535:  my %hash;
                   14536:  $hash{'foo'}='bar';
                   14537: 
                   14538:  #storing it
                   14539:  &Apache::lonnet::cstore(\%hash);
                   14540: 
                   14541:  #changing a value
                   14542:  $hash{'foo'}='notbar';
                   14543: 
                   14544:  #adding a new value
                   14545:  $hash{'bar'}='foo';
                   14546:  &Apache::lonnet::cstore(\%hash);
                   14547: 
                   14548:  #retrieving the hash
                   14549:  my %history=&Apache::lonnet::restore();
                   14550: 
                   14551:  #print the hash
                   14552:  foreach my $key (sort(keys(%history))) {
                   14553:    print("\%history{$key} = $history{$key}");
                   14554:  }
                   14555: 
                   14556: Will print out:
1.191     harris41 14557: 
1.394     bowersj2 14558:  %history{1:foo} = bar
                   14559:  %history{1:keys} = foo:timestamp
                   14560:  %history{1:timestamp} = 990455579
                   14561:  %history{2:bar} = foo
                   14562:  %history{2:foo} = notbar
                   14563:  %history{2:keys} = foo:bar:timestamp
                   14564:  %history{2:timestamp} = 990455580
                   14565:  %history{bar} = foo
                   14566:  %history{foo} = notbar
                   14567:  %history{timestamp} = 990455580
                   14568:  %history{version} = 2
                   14569: 
                   14570: Note that the special hash entries C<keys>, C<version> and
                   14571: C<timestamp> were added to the hash. C<version> will be equal to the
                   14572: total number of versions of the data that have been stored. The
                   14573: C<timestamp> attribute will be the UNIX time the hash was
                   14574: stored. C<keys> is available in every historical section to list which
                   14575: keys were added or changed at a specific historical revision of a
                   14576: hash.
                   14577: 
                   14578: B<Warning>: do not store the hash that restore returns directly. This
                   14579: will cause a mess since it will restore the historical keys as if the
                   14580: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14581: 
1.394     bowersj2 14582: Calling convention:
1.191     harris41 14583: 
1.1225    raeburn  14584:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14585:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14586: 
1.394     bowersj2 14587: For more detailed information, see lonnet specific documentation.
1.191     harris41 14588: 
1.394     bowersj2 14589: =head1 RETURN MESSAGES
1.191     harris41 14590: 
1.394     bowersj2 14591: =over 4
1.191     harris41 14592: 
1.394     bowersj2 14593: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14594: 
1.394     bowersj2 14595: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14596: when the connection is brought back up
1.191     harris41 14597: 
1.394     bowersj2 14598: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14599: for later delivery
1.191     harris41 14600: 
1.967     bisitz   14601: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14602: 
1.394     bowersj2 14603: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14604: that was requested
1.191     harris41 14605: 
1.243     albertel 14606: =back
1.191     harris41 14607: 
1.243     albertel 14608: =head1 PUBLIC SUBROUTINES
1.191     harris41 14609: 
1.243     albertel 14610: =head2 Session Environment Functions
1.191     harris41 14611: 
1.243     albertel 14612: =over 4
1.191     harris41 14613: 
1.394     bowersj2 14614: =item * 
                   14615: X<appenv()>
1.949     raeburn  14616: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14617: the user envirnoment file, and will be restored for each access this
1.620     albertel 14618: user makes during this session, also modifies the %env for the current
1.949     raeburn  14619: process. Optional rolesarrayref - if defined contains a reference to an array
                   14620: of roles which are exempt from the restriction on modifying user.role entries 
                   14621: in the user's environment.db and in %env.    
1.191     harris41 14622: 
                   14623: =item *
1.394     bowersj2 14624: X<delenv()>
1.987     raeburn  14625: B<delenv($delthis,$regexp)>: removes all items from the session
                   14626: environment file that begin with $delthis. If the 
                   14627: optional second arg - $regexp - is true, $delthis is treated as a 
                   14628: regular expression, otherwise \Q$delthis\E is used. 
                   14629: The values are also deleted from the current processes %env.
1.191     harris41 14630: 
1.795     albertel 14631: =item * get_env_multiple($name) 
                   14632: 
                   14633: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14634: values may be defined and end up as an array ref.
                   14635: 
                   14636: returns an array of values
                   14637: 
1.243     albertel 14638: =back
                   14639: 
                   14640: =head2 User Information
1.191     harris41 14641: 
1.243     albertel 14642: =over 4
1.191     harris41 14643: 
                   14644: =item *
1.394     bowersj2 14645: X<queryauthenticate()>
                   14646: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14647: authentication scheme
                   14648: 
                   14649: =item *
1.394     bowersj2 14650: X<authenticate()>
1.1073    raeburn  14651: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14652: authenticate user from domain's lib servers (first use the current
                   14653: one). C<$upass> should be the users password.
1.1073    raeburn  14654: $checkdefauth is optional (value is 1 if a check should be made to
                   14655:    authenticate user using default authentication method, and allow
                   14656:    account creation if username does not have account in the domain).
                   14657: $clientcancheckhost is optional (value is 1 if checking whether the
                   14658:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14659: 
                   14660: =item *
1.394     bowersj2 14661: X<homeserver()>
                   14662: B<homeserver($uname,$udom)>: find the server which has
                   14663: the user's directory and files (there must be only one), this caches
                   14664: the answer, and also caches if there is a borken connection.
1.191     harris41 14665: 
                   14666: =item *
1.394     bowersj2 14667: X<idget()>
1.1300    raeburn  14668: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14669: a list of student/employee IDs or clicker IDs
                   14670: (student/employee IDs are a unique resource in a domain, there must be 
                   14671: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14672: clickerIDs are not necessarily unique, as students might share clickers.
                   14673: (returns hash: id=>name,id=>name)
1.191     harris41 14674: 
                   14675: =item *
1.394     bowersj2 14676: X<idrget()>
                   14677: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14678: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14679: 
                   14680: =item *
1.394     bowersj2 14681: X<idput()>
1.1300    raeburn  14682: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14683: names and associated student/employee IDs or clicker IDs.
                   14684: 
                   14685: =item *
                   14686: X<iddel()>
                   14687: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14688: student/employee ID or clicker ID username look-ups from domain.
                   14689: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14690: If no $uhome is provided, it will be determined usig &homeserver()
                   14691: for each user.  If no $namespace is provided, the default is ids.
                   14692: 
                   14693: =item *
                   14694: X<updateclickers()>
                   14695: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14696: clicker ID-to-username look-ups in clickers.db on library server.
                   14697: Permitted actions are add or del (i.e., add or delete). The 
                   14698: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14699: value is an escaped comma-separated list of usernames (for whom the
                   14700: library server is the homeserver), who registered that particular ID.
                   14701: If $critical is true, the update will be sent via &critical, otherwise
                   14702: &reply() will be used.
1.191     harris41 14703: 
                   14704: =item *
1.394     bowersj2 14705: X<rolesinit()>
1.1169    droeschl 14706: B<rolesinit($udom,$username)>: get user privileges.
                   14707: returns user role, first access and timer interval hashes
1.243     albertel 14708: 
                   14709: =item *
1.1171    droeschl 14710: X<privileged()>
                   14711: B<privileged($username,$domain)>: returns a true if user has a
                   14712: privileged and active role (i.e. su or dc), false otherwise.
                   14713: 
                   14714: =item *
1.551     albertel 14715: X<getsection()>
                   14716: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14717: course $cname, return section name/number or '' for "not in course"
                   14718: and '-1' for "no section"
                   14719: 
                   14720: =item *
1.394     bowersj2 14721: X<userenvironment()>
                   14722: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14723: passed in @what from the requested user's environment, returns a hash
                   14724: 
1.858     raeburn  14725: =item * 
                   14726: X<userlog_query()>
1.859     albertel 14727: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14728: activity.log file. %filters defines filters applied when parsing the
                   14729: log file. These can be start or end timestamps, or the type of action
                   14730: - log to look for Login or Logout events, check for Checkin or
                   14731: Checkout, role for role selection. The response is in the form
                   14732: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14733: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14734: 
1.243     albertel 14735: =back
                   14736: 
                   14737: =head2 User Roles
                   14738: 
                   14739: =over 4
                   14740: 
                   14741: =item *
                   14742: 
1.1284    raeburn  14743: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14744: returns codes for allowed actions.
                   14745: 
                   14746: The first argument is required, all others are optional.
                   14747: 
                   14748: $priv is the privilege being checked.
                   14749: $uri contains additional information about what is being checked for access (e.g.,
                   14750: URL, course ID etc.). 
                   14751: $symb is the unique resource instance identifier in a course; if needed,
                   14752: but not provided, it will be retrieved via a call to &symbread(). 
                   14753: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14754: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14755: files).
                   14756: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14757: prevents recursive calls to &allowed.
                   14758: 
1.243     albertel 14759:  F: full access
                   14760:  U,I,K: authentication modes (cxx only)
                   14761:  '': forbidden
                   14762:  1: user needs to choose course
                   14763:  2: browse allowed
1.766     albertel 14764:  A: passphrase authentication needed
1.1284    raeburn  14765:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14766: 
                   14767: =item *
                   14768: 
1.1192    raeburn  14769: constructaccess($url,$setpriv) : check for access to construction space URL
                   14770: 
                   14771: See if the owner domain and name in the URL match those in the
                   14772: expected environment.  If so, return three element list
                   14773: ($ownername,$ownerdomain,$ownerhome).
                   14774: 
                   14775: Otherwise return the null string.
                   14776: 
                   14777: If second argument 'setpriv' is true, it assigns the privileges,
                   14778: and returns the same three element list, unless the owner has
                   14779: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14780: in which case the null string is returned.
                   14781: 
                   14782: =item *
                   14783: 
1.1326    raeburn  14784: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14785: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14786: for system, domain, and course level. $uname and $udom are optional (current
                   14787: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14788: 
                   14789: =item *
                   14790: 
1.988     raeburn  14791: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14792: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14793: $type is Course (default) or Community.
1.988     raeburn  14794: If $forcedefault evaluates to true, text returned will be default 
                   14795: text for $type. Otherwise, if this is a course, the text returned 
                   14796: will be a custom name for the role (if defined in the course's 
                   14797: environment).  If no custom name is defined the default is returned.
                   14798:    
1.832     raeburn  14799: =item *
                   14800: 
1.1219    raeburn  14801: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14802: All arguments are optional. Returns a hash of a roles, either for
                   14803: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14804: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14805: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14806: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14807: For each key, value is set to colon-separated start and end times for
                   14808: the role.  If no username and domain are specified, will default to
1.934     raeburn  14809: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14810: of role statuses (active, future or previous), roles 
                   14811: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14812: to restrict the list of roles reported. If no array ref is 
                   14813: provided for types, will default to return only active roles.
1.834     albertel 14814: 
1.1195    raeburn  14815: =item *
                   14816: 
                   14817: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14818: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14819: 
                   14820: Additional optional arguments are: $type (if role checking is to be restricted 
                   14821: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14822: available roles) or future (roles available in the future), and
                   14823: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14824: have active Domain Coordinator role in course's domain or in additional
                   14825: domains (specified in 'Domains to check for privileged users' in course
                   14826: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14827: 
                   14828: =item *
                   14829: 
                   14830: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14831: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14832: $possdomains and $possroles are optional array refs -- to domains to check and
                   14833: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14834: users' roles.db to check for a dc or su role in any domain. This can be
                   14835: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14836: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14837: this then allows &privileged_by_domain() to be used, which caches the identity
                   14838: of privileged users, eliminating the need for repeated calls to &dump().
                   14839: 
                   14840: =item *
                   14841: 
                   14842: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14843: where the outer hash keys are domains specified in the $possdomains array ref,
                   14844: next inner hash keys are privileged roles specified in the $roles array ref,
                   14845: and the innermost hash contains key = value pairs for username:domain = end:start
                   14846: for active or future "privileged" users with that role in that domain. To avoid
                   14847: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14848: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14849: 
1.243     albertel 14850: =back
                   14851: 
                   14852: =head2 User Modification
                   14853: 
                   14854: =over 4
                   14855: 
                   14856: =item *
                   14857: 
1.957     raeburn  14858: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14859: user for the level given by URL.  Optional start and end dates (leave empty
                   14860: string or zero for "no date")
1.191     harris41 14861: 
                   14862: =item *
                   14863: 
1.243     albertel 14864: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14865: change a users, password, possible return values are: ok,
                   14866: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14867: refused
1.191     harris41 14868: 
                   14869: =item *
                   14870: 
1.243     albertel 14871: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14872: 
                   14873: =item *
                   14874: 
1.1058    raeburn  14875: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14876:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14877: 
                   14878: will update user information (firstname,middlename,lastname,generation,
                   14879: permanentemail), and if forceid is true, student/employee ID also.
                   14880: A user's institutional affiliation(s) can also be updated.
                   14881: User information fields will not be overwritten with empty entries 
                   14882: unless the field is included in the $candelete array reference.
                   14883: This array is included when a single user is modified via "Manage Users",
                   14884: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14885: 
                   14886: =item *
                   14887: 
1.286     matthew  14888: modifystudent
                   14889: 
1.957     raeburn  14890: modify a student's enrollment and identification information.
1.1235    raeburn  14891: The course id is resolved based on the current user's environment.  
                   14892: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14893: associated with a course.
                   14894: 
1.297     matthew  14895: This call is essentially a wrapper for lonnet::modifyuser and
                   14896: lonnet::modify_student_enrollment
1.286     matthew  14897: 
                   14898: Inputs: 
                   14899: 
                   14900: =over 4
                   14901: 
1.957     raeburn  14902: =item B<$udom> Student's loncapa domain
1.286     matthew  14903: 
1.957     raeburn  14904: =item B<$uname> Student's loncapa login name
1.286     matthew  14905: 
1.964     bisitz   14906: =item B<$uid> Student/Employee ID
1.286     matthew  14907: 
1.957     raeburn  14908: =item B<$umode> Student's authentication mode
1.286     matthew  14909: 
1.957     raeburn  14910: =item B<$upass> Student's password
1.286     matthew  14911: 
1.957     raeburn  14912: =item B<$first> Student's first name
1.286     matthew  14913: 
1.957     raeburn  14914: =item B<$middle> Student's middle name
1.286     matthew  14915: 
1.957     raeburn  14916: =item B<$last> Student's last name
1.286     matthew  14917: 
1.957     raeburn  14918: =item B<$gene> Student's generation
1.286     matthew  14919: 
1.957     raeburn  14920: =item B<$usec> Student's section in course
1.286     matthew  14921: 
                   14922: =item B<$end> Unix time of the roles expiration
                   14923: 
                   14924: =item B<$start> Unix time of the roles start date
                   14925: 
                   14926: =item B<$forceid> If defined, allow $uid to be changed
                   14927: 
                   14928: =item B<$desiredhome> server to use as home server for student
                   14929: 
1.957     raeburn  14930: =item B<$email> Student's permanent e-mail address
                   14931: 
                   14932: =item B<$type> Type of enrollment (auto or manual)
                   14933: 
1.963     raeburn  14934: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14935: 
                   14936: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14937: 
1.963     raeburn  14938: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14939: 
1.963     raeburn  14940: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14941: 
1.1216    raeburn  14942: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14943: 
                   14944: =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  14945: 
1.286     matthew  14946: =back
1.297     matthew  14947: 
                   14948: =item *
                   14949: 
                   14950: modify_student_enrollment
                   14951: 
1.1235    raeburn  14952: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14953: 'role.request.course' must be defined for this function to proceed.
                   14954: 
                   14955: Inputs:
                   14956: 
                   14957: =over 4
                   14958: 
1.1235    raeburn  14959: =item $udom, student's domain
1.297     matthew  14960: 
1.1235    raeburn  14961: =item $uname, student's name
1.297     matthew  14962: 
1.1235    raeburn  14963: =item $uid, student's user id
1.297     matthew  14964: 
1.1235    raeburn  14965: =item $first, student's first name
1.297     matthew  14966: 
                   14967: =item $middle
                   14968: 
                   14969: =item $last
                   14970: 
                   14971: =item $gene
                   14972: 
                   14973: =item $usec
                   14974: 
                   14975: =item $end
                   14976: 
                   14977: =item $start
                   14978: 
1.957     raeburn  14979: =item $type
                   14980: 
                   14981: =item $locktype
                   14982: 
                   14983: =item $cid
                   14984: 
                   14985: =item $selfenroll
                   14986: 
                   14987: =item $context
                   14988: 
1.1216    raeburn  14989: =item $credits, number of credits student will earn from this class
                   14990: 
1.1314    raeburn  14991: =item $instsec, institutional course section code for student
                   14992: 
1.297     matthew  14993: =back
                   14994: 
1.191     harris41 14995: 
                   14996: =item *
                   14997: 
1.243     albertel 14998: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14999: custom role; give a custom role to a user for the level given by URL.  Specify
                   15000: name and domain of role author, and role name
1.191     harris41 15001: 
                   15002: =item *
                   15003: 
1.243     albertel 15004: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15005: 
                   15006: =item *
                   15007: 
1.243     albertel 15008: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15009: 
                   15010: =back
                   15011: 
                   15012: =head2 Course Infomation
                   15013: 
                   15014: =over 4
1.191     harris41 15015: 
                   15016: =item *
                   15017: 
1.1118    foxr     15018: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15019: specified course id, including all environment settings for the
                   15020: course, the description of the course will be in the hash under the
                   15021: key 'description'
1.191     harris41 15022: 
1.1118    foxr     15023: $options is an optional parameter that if supplied is a hash reference that controls
                   15024: what how this function works.  It has the following key/values:
                   15025: 
                   15026: =over 4
                   15027: 
                   15028: =item freshen_cache
                   15029: 
                   15030: If defined, and the environment cache for the course is valid, it is 
                   15031: returned in the returned hash.
                   15032: 
                   15033: =item one_time
                   15034: 
                   15035: If defined, the last cache time is set to _now_
                   15036: 
                   15037: =item user
                   15038: 
                   15039: If defined, the supplied username is used instead of the current user.
                   15040: 
                   15041: 
                   15042: =back
                   15043: 
1.191     harris41 15044: =item *
                   15045: 
1.624     albertel 15046: resdata($name,$domain,$type,@which) : request for current parameter
                   15047: setting for a specific $type, where $type is either 'course' or 'user',
                   15048: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15049: answers for 10 minutes.
1.243     albertel 15050: 
1.877     foxr     15051: =item *
                   15052: 
                   15053: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15054: data base, returning a hash that is keyed by the resource name and has
                   15055: values that are the resource value.  I believe that the timestamps and
                   15056: versions are also returned.
                   15057: 
1.1236    raeburn  15058: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15059: supplemental content area. This routine caches the number of files for 
                   15060: 10 minutes.
                   15061: 
1.243     albertel 15062: =back
                   15063: 
                   15064: =head2 Course Modification
                   15065: 
                   15066: =over 4
1.191     harris41 15067: 
                   15068: =item *
                   15069: 
1.243     albertel 15070: writecoursepref($courseid,%prefs) : write preferences (environment
                   15071: database) for a course
1.191     harris41 15072: 
                   15073: =item *
                   15074: 
1.1011    raeburn  15075: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15076: 
                   15077: =item *
                   15078: 
1.1038    raeburn  15079: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15080: 
1.1167    droeschl 15081: =item *
                   15082: 
                   15083: is_course($courseid), is_course($cdom, $cnum)
                   15084: 
                   15085: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15086: two component version $cdom, $cnum. It checks if the specified course exists.
                   15087: 
                   15088: Returns:
                   15089:     undef if the course doesn't exist, otherwise
                   15090:     in scalar context the combined courseid.
                   15091:     in list context the two components of the course identifier, domain and 
                   15092:     courseid.    
                   15093: 
1.243     albertel 15094: =back
                   15095: 
                   15096: =head2 Resource Subroutines
                   15097: 
                   15098: =over 4
1.191     harris41 15099: 
                   15100: =item *
                   15101: 
1.243     albertel 15102: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15103: 
                   15104: =item *
                   15105: 
1.243     albertel 15106: repcopy($filename) : subscribes to the requested file, and attempts to
                   15107: replicate from the owning library server, Might return
1.607     raeburn  15108: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15109: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15110: resource. Expects the local filesystem pathname
                   15111: (/home/httpd/html/res/....)
                   15112: 
                   15113: =back
                   15114: 
                   15115: =head2 Resource Information
                   15116: 
                   15117: =over 4
1.191     harris41 15118: 
                   15119: =item *
                   15120: 
1.1228    raeburn  15121: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15122: and returns the value of a variety of different possible values,
                   15123: $varname should be a request string, and the other parameters can be
                   15124: used to specify who and what one is asking about. Ordinarily, $cid 
                   15125: does not need to be specified, as it is retrived from 
                   15126: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15127: within lonuserstate::loadmap() when initializing a course, before
                   15128: $env{'request.course.id'} has been set, so it needs to be provided
                   15129: in that one case.
1.243     albertel 15130: 
                   15131: Possible values for $varname are environment.lastname (or other item
                   15132: from the envirnment hash), user.name (or someother aspect about the
                   15133: user), resource.0.maxtries (or some other part and parameter of a
                   15134: resource)
1.204     albertel 15135: 
                   15136: =item *
                   15137: 
1.243     albertel 15138: directcondval($number) : get current value of a condition; reads from a state
                   15139: string
1.204     albertel 15140: 
                   15141: =item *
                   15142: 
1.243     albertel 15143: condval($condidx) : value of condition index based on state
1.204     albertel 15144: 
                   15145: =item *
                   15146: 
1.1362    raeburn  15147: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15148: resource's metadata, $what should be either a specific key, or either
                   15149: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15150: packages that this resource currently uses, the last 3 arguments are 
                   15151: only used internally for recursive metadata.
                   15152: 
                   15153: the toolsymb is only used where the uri is for an external tool (for which
                   15154: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15155: 
1.1371    raeburn  15156: this function automatically caches all requests except any made recursively
                   15157: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15158: defined).
1.191     harris41 15159: 
                   15160: =item *
                   15161: 
1.243     albertel 15162: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15163: network of library servers; returns file handle of where SQL and regex results
                   15164: will be stored for query
1.191     harris41 15165: 
                   15166: =item *
                   15167: 
1.1282    raeburn  15168: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15169: return symbolic list entry (all arguments optional). 
                   15170: 
                   15171: Args: filename is the filename (including path) for the file for which a symb 
                   15172: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15173: to check access status if more than one resource was found in the bighash 
                   15174: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15175: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15176: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15177: cause possible symbs to be checked to determine if they are subject to content
                   15178: blocking, if so they will not be included as possible symbs; possibles is a
                   15179: ref to a hash, which, as a side effect, will be populated with all possible 
                   15180: symbs (content blocking not tested).
                   15181:  
1.243     albertel 15182: returns the data handle
1.191     harris41 15183: 
                   15184: =item *
                   15185: 
1.1190    raeburn  15186: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15187: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15188: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15189: on failure, user must be in a course, as it assumes the existence of
                   15190: the course initial hash, and uses $env('request.course.id'}.  The third
                   15191: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15192: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15193: encrypted; otherwise it will be null.  
1.191     harris41 15194: 
                   15195: =item *
                   15196: 
1.243     albertel 15197: symbclean($symb) : removes versions numbers from a symb, returns the
                   15198: cleaned symb
1.191     harris41 15199: 
                   15200: =item *
                   15201: 
1.243     albertel 15202: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15203: course map, user must be in a course for it to work.
1.191     harris41 15204: 
                   15205: =item *
                   15206: 
1.243     albertel 15207: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15208: 
                   15209: =item *
                   15210: 
1.243     albertel 15211: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15212: a random seed, all arguments are optional, if they aren't sent it uses the
                   15213: environment to derive them. Note: if symb isn't sent and it can't get one
                   15214: from &symbread it will use the current time as its return value
1.191     harris41 15215: 
                   15216: =item *
                   15217: 
1.243     albertel 15218: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15219: unfakeable, receipt
1.191     harris41 15220: 
                   15221: =item *
                   15222: 
1.620     albertel 15223: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15224: 
                   15225: =item *
                   15226: 
1.243     albertel 15227: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15228: 
                   15229: =item *
                   15230: 
1.243     albertel 15231: 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 15232: 
                   15233: =item *
                   15234: 
1.243     albertel 15235: 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 15236: 
                   15237: =item *
                   15238: 
1.243     albertel 15239: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15240: 
                   15241: =item *
                   15242: 
1.243     albertel 15243: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15244: forcing spreadsheet to reevaluate the resource scores next time.
                   15245: 
1.1195    raeburn  15246: =item * 
                   15247: 
1.1196    raeburn  15248: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15249: when viewing in course context.
1.1195    raeburn  15250: 
1.1196    raeburn  15251:  input: six args -- filename (decluttered), course number, course domain,
                   15252:                     url, symb (if registered) and group (if this is a 
                   15253:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15254: 
1.1196    raeburn  15255:  output: array of five scalars --
1.1195    raeburn  15256:          $cfile -- url for file editing if editable on current server
                   15257:          $home -- homeserver of resource (i.e., for author if published,
                   15258:                                           or course if uploaded.).
                   15259:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15260:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15261:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15262: 
                   15263: =item *
                   15264: 
                   15265: is_course_upload($file,$cnum,$cdom)
                   15266: 
                   15267: Used in course context to determine if current file was uploaded to 
                   15268: the course (i.e., would be found in /userfiles/docs on the course's 
                   15269: homeserver.
                   15270: 
                   15271:   input: 3 args -- filename (decluttered), course number and course domain.
                   15272:   output: boolean -- 1 if file was uploaded.
                   15273: 
1.243     albertel 15274: =back
                   15275: 
                   15276: =head2 Storing/Retreiving Data
                   15277: 
                   15278: =over 4
1.191     harris41 15279: 
                   15280: =item *
                   15281: 
1.1269    raeburn  15282: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15283: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15284: the remaining args aren't required and if they aren't passed or are '' they will
                   15285: be derived from the env (with the exception of $laststore, which is an 
                   15286: optional arg used when a user's submission is stored in grading).
                   15287: $laststore is $version=$timestamp, where $version is the most recent version
                   15288: number retrieved for the corresponding $symb in the $namespace db file, and
                   15289: $timestamp is the timestamp for that transaction (UNIX time).
                   15290: $laststore is currently only passed when cstore() is called by 
                   15291: structuretags::finalize_storage().
1.191     harris41 15292: 
                   15293: =item *
                   15294: 
1.1269    raeburn  15295: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15296: but uses critical subroutine
1.191     harris41 15297: 
                   15298: =item *
                   15299: 
1.243     albertel 15300: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15301: all args are optional
1.191     harris41 15302: 
                   15303: =item *
                   15304: 
1.717     albertel 15305: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15306: dumps the complete (or key matching regexp) namespace into a hash
                   15307: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15308: normally &store()ed into
                   15309: 
                   15310: $range should be either an integer '100' (give me the first 100
                   15311:                                            matching records)
                   15312:               or be  two integers sperated by a - with no spaces
                   15313:                  '30-50' (give me the 30th through the 50th matching
                   15314:                           records)
                   15315: 
                   15316: 
                   15317: =item *
                   15318: 
1.1269    raeburn  15319: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15320: replaces a &store() version of data with a replacement set of data
                   15321: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15322: reference. If $tolog is true, the transaction is logged in the courselog
                   15323: with an action=PUTSTORE.
1.717     albertel 15324: 
                   15325: =item *
                   15326: 
1.243     albertel 15327: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15328: works very similar to store/cstore, but all data is stored in a
                   15329: temporary location and can be reset using tmpreset, $storehash should
                   15330: be a hash reference, returns nothing on success
1.191     harris41 15331: 
                   15332: =item *
                   15333: 
1.243     albertel 15334: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15335: similar to restore, but all data is stored in a temporary location and
                   15336: can be reset using tmpreset. Returns a hash of values on success,
                   15337: error string otherwise.
1.191     harris41 15338: 
                   15339: =item *
                   15340: 
1.243     albertel 15341: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15342: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15343: 
                   15344: =item *
                   15345: 
1.243     albertel 15346: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15347: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15348: 
                   15349: =item *
                   15350: 
1.243     albertel 15351: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15352: namesp ($udom and $uname are optional)
1.191     harris41 15353: 
                   15354: =item *
                   15355: 
1.702     albertel 15356: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15357: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15358: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15359: 
1.702     albertel 15360: $range should be either an integer '100' (give me the first 100
                   15361:                                            matching records)
                   15362:               or be  two integers sperated by a - with no spaces
                   15363:                  '30-50' (give me the 30th through the 50th matching
                   15364:                           records)
1.449     matthew  15365: =item *
                   15366: 
                   15367: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15368: $store can be a scalar, an array reference, or if the amount to be 
                   15369: incremented is > 1, a hash reference.
                   15370: 
                   15371: ($udom and $uname are optional)
1.191     harris41 15372: 
                   15373: =item *
                   15374: 
1.243     albertel 15375: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15376: ($udom and $uname are optional)
1.191     harris41 15377: 
                   15378: =item *
                   15379: 
1.243     albertel 15380: cput($namespace,$storehash,$udom,$uname) : critical put
                   15381: ($udom and $uname are optional)
1.191     harris41 15382: 
                   15383: =item *
                   15384: 
1.748     albertel 15385: newput($namespace,$storehash,$udom,$uname) :
                   15386: 
                   15387: Attempts to store the items in the $storehash, but only if they don't
                   15388: currently exist, if this succeeds you can be certain that you have 
                   15389: successfully created a new key value pair in the $namespace db.
                   15390: 
                   15391: 
                   15392: Args:
                   15393:  $namespace: name of database to store values to
                   15394:  $storehash: hashref to store to the db
                   15395:  $udom: (optional) domain of user containing the db
                   15396:  $uname: (optional) name of user caontaining the db
                   15397: 
                   15398: Returns:
                   15399:  'ok' -> succeeded in storing all keys of $storehash
                   15400:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15401:                         least <key> already existed in the db (other
                   15402:                         requested keys may also already exist)
1.967     bisitz   15403:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15404:  'con_lost' -> unable to contact request server
                   15405:  'refused' -> action was not allowed by remote machine
                   15406: 
                   15407: 
                   15408: =item *
                   15409: 
1.243     albertel 15410: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15411: reference filled in from namesp (encrypts the return communication)
                   15412: ($udom and $uname are optional)
1.191     harris41 15413: 
                   15414: =item *
                   15415: 
1.243     albertel 15416: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15417: critical subroutine
                   15418: 
1.806     raeburn  15419: =item *
                   15420: 
1.860     raeburn  15421: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15422: array reference filled in from namespace found in domain level on either
                   15423: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15424: 
                   15425: =item *
                   15426: 
1.860     raeburn  15427: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15428: domain level either on specified domain server ($uhome) or primary domain 
                   15429: server ($udom and $uhome are optional)
1.806     raeburn  15430: 
1.943     raeburn  15431: =item * 
                   15432: 
1.1240    raeburn  15433: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15434: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15435: the target domain.
                   15436: 
                   15437: May also include additional key => value pairs for the following groups:
                   15438: 
                   15439: =over
                   15440: 
                   15441: =item
                   15442: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15443: 
                   15444: =over
                   15445: 
                   15446: =item defaultquota, authorquota
                   15447: 
                   15448: =back
                   15449: 
                   15450: =item
                   15451: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15452: portfolio for users).
                   15453: 
                   15454: =over
                   15455: 
                   15456: =item
                   15457: aboutme, blog, webdav, portfolio
                   15458: 
                   15459: =back
                   15460: 
                   15461: =item
                   15462: requestcourses: ability to request courses, and how requests are processed.
                   15463: 
                   15464: =over
                   15465: 
                   15466: =item
1.1305    raeburn  15467: official, unofficial, community, textbook, placement
1.1240    raeburn  15468: 
                   15469: =back
                   15470: 
                   15471: =item
                   15472: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15473: 
                   15474: =over
                   15475: 
                   15476: =item
1.1256    raeburn  15477: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15478: 
                   15479: =back
                   15480: 
                   15481: =item
                   15482: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15483: for course's uploaded content.
                   15484: 
                   15485: =over
                   15486: 
                   15487: =item
1.1246    raeburn  15488: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15489: communityquota, textbookquota, placementquota
1.1240    raeburn  15490: 
                   15491: =back
                   15492: 
                   15493: =item
                   15494: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15495: on your servers.
                   15496: 
                   15497: =over
                   15498: 
                   15499: =item 
                   15500: remotesessions, hostedsessions
                   15501: 
                   15502: =back
                   15503: 
                   15504: =back
                   15505: 
                   15506: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15507: utility to create a configuration.db file on a domain's primary library server 
                   15508: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15509: -- corresponding values are authentication type (internal, krb4, krb5,
                   15510: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15511: will be available. Values are retrieved from cache (if current), unless the
                   15512: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15513: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15514: 
                   15515: Typical usage:
1.943     raeburn  15516: 
1.1240    raeburn  15517: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15518: 
1.243     albertel 15519: =back
                   15520: 
                   15521: =head2 Network Status Functions
                   15522: 
                   15523: =over 4
1.191     harris41 15524: 
                   15525: =item *
                   15526: 
1.1137    raeburn  15527: dirlist() : return directory list based on URI (first arg).
                   15528: 
                   15529: Inputs: 1 required, 5 optional.
                   15530: 
                   15531: =over
                   15532: 
                   15533: =item 
                   15534: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15535: 
                   15536: =item
                   15537: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15538: 
                   15539: =item
                   15540: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15541: 
                   15542: =item
                   15543: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15544: 
                   15545: =item
                   15546: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15547: 
                   15548: =item 
                   15549: $alternateRoot - path to prepend in place of path from $uri.
                   15550: 
                   15551: =back
                   15552: 
                   15553: Returns: Array of up to two items.
                   15554: 
                   15555: =over
                   15556: 
                   15557: a reference to an array of files/subdirectories
                   15558: 
                   15559: =over
                   15560: 
                   15561: Each element in the array of files/subdirectories is a & separated list of
                   15562: item name and the result of running stat on the item.  If dirlist was requested
                   15563: for a file instead of a directory, the item name will be ''. For a directory 
                   15564: listing, if the item is a metadata file, the element will end &N&M 
                   15565: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15566: default copyright set (1).  
                   15567: 
                   15568: =back
                   15569: 
                   15570: a scalar containing error condition (if encountered).
                   15571: 
                   15572: =over
                   15573: 
                   15574: =item 
                   15575: no_host (no homeserver identified for $username:$domain).
                   15576: 
                   15577: =item 
                   15578: no_such_host (server contacted for listing not identified as valid host).
                   15579: 
                   15580: =item 
                   15581: con_lost (connection to remote server failed).
                   15582: 
                   15583: =item 
                   15584: refused (invalid $username:$domain received on lond side).
                   15585: 
                   15586: =item 
                   15587: no_such_dir (directory at specified path on lond side does not exist). 
                   15588: 
                   15589: =item 
                   15590: empty (directory at specified path on lond side is empty).
                   15591: 
                   15592: =over
                   15593: 
                   15594: This is currently not encountered because the &ls3, &ls2, 
                   15595: &ls (_handler) routines on the lond side do not filter out
                   15596: . and .. from a directory listing. 
                   15597: 
                   15598: =back
                   15599: 
                   15600: =back
                   15601: 
                   15602: =back
1.191     harris41 15603: 
                   15604: =item *
                   15605: 
1.243     albertel 15606: spareserver() : find server with least workload from spare.tab
                   15607: 
1.986     foxr     15608: 
                   15609: =item *
                   15610: 
                   15611: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15612: if there is no corresponding loncapa host.
                   15613: 
1.243     albertel 15614: =back
                   15615: 
1.986     foxr     15616: 
1.243     albertel 15617: =head2 Apache Request
                   15618: 
                   15619: =over 4
1.191     harris41 15620: 
                   15621: =item *
                   15622: 
1.243     albertel 15623: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15624: localhost, posts hash
                   15625: 
                   15626: =back
                   15627: 
                   15628: =head2 Data to String to Data
                   15629: 
                   15630: =over 4
1.191     harris41 15631: 
                   15632: =item *
                   15633: 
1.243     albertel 15634: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15635: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15636: 
                   15637: =item *
                   15638: 
1.243     albertel 15639: hashref2str($hashref) : convert a hashref into a string complete with
                   15640: escaping and '=' and '&' separators, supports elements that are
                   15641: arrayrefs and hashrefs
1.191     harris41 15642: 
                   15643: =item *
                   15644: 
1.243     albertel 15645: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15646: with escaping and '&' separators, supports elements that are arrayrefs
                   15647: and hashrefs
1.191     harris41 15648: 
                   15649: =item *
                   15650: 
1.243     albertel 15651: str2hash($string) : convert string to hash using unescaping and
                   15652: splitting on '=' and '&', supports elements that are arrayrefs and
                   15653: hashrefs
1.191     harris41 15654: 
                   15655: =item *
                   15656: 
1.243     albertel 15657: str2array($string) : convert string to hash using unescaping and
                   15658: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15659: 
                   15660: =back
                   15661: 
                   15662: =head2 Logging Routines
                   15663: 
                   15664: 
                   15665: These routines allow one to make log messages in the lonnet.log and
                   15666: lonnet.perm logfiles.
1.191     harris41 15667: 
1.1119    foxr     15668: =over 4
                   15669: 
1.191     harris41 15670: =item *
                   15671: 
1.243     albertel 15672: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15673: 
                   15674: =item *
                   15675: 
1.243     albertel 15676: logthis() : append message to the normal lonnet.log file, it gets
                   15677: preiodically rolled over and deleted.
1.191     harris41 15678: 
                   15679: =item *
                   15680: 
1.243     albertel 15681: logperm() : append a permanent message to lonnet.perm.log, this log
                   15682: file never gets deleted by any automated portion of the system, only
                   15683: messages of critical importance should go in here.
                   15684: 
1.1119    foxr     15685: 
1.243     albertel 15686: =back
                   15687: 
                   15688: =head2 General File Helper Routines
                   15689: 
                   15690: =over 4
1.191     harris41 15691: 
                   15692: =item *
                   15693: 
1.481     raeburn  15694: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15695: (a) files in /uploaded
                   15696:   (i) If a local copy of the file exists - 
                   15697:       compares modification date of local copy with last-modified date for 
                   15698:       definitive version stored on home server for course. If local copy is 
                   15699:       stale, requests a new version from the home server and stores it. 
                   15700:       If the original has been removed from the home server, then local copy 
                   15701:       is unlinked.
                   15702:   (ii) If local copy does not exist -
                   15703:       requests the file from the home server and stores it. 
                   15704:   
                   15705:   If $caller is 'uploadrep':  
                   15706:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15707:     for request for files originally uploaded via DOCS. 
                   15708:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15709:   
                   15710:   Otherwise:
                   15711:      This indicates a call from the content generation phase of the request.
                   15712:      -  returns the entire contents of the file or -1.
                   15713:      
                   15714: (b) files in /res
                   15715:    - returns the entire contents of a file or -1; 
                   15716:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15717: 
1.712     albertel 15718: 
                   15719: =item *
                   15720: 
                   15721: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15722:                   reference
                   15723: 
                   15724: returns either a stat() list of data about the file or an empty list
                   15725: if the file doesn't exist or couldn't find out about it (connection
                   15726: problems or user unknown)
                   15727: 
1.191     harris41 15728: =item *
                   15729: 
1.243     albertel 15730: filelocation($dir,$file) : returns file system location of a file
                   15731: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15732: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15733: and a file of ../bob will become /a/bob)
1.191     harris41 15734: 
                   15735: =item *
                   15736: 
                   15737: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15738: filelocation except for hrefs
                   15739: 
                   15740: =item *
                   15741: 
1.1261    raeburn  15742: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15743: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15744: 
1.243     albertel 15745: =back
                   15746: 
1.608     albertel 15747: =head2 Usererfile file routines (/uploaded*)
                   15748: 
                   15749: =over 4
                   15750: 
                   15751: =item *
                   15752: 
                   15753: userfileupload(): main rotine for putting a file in a user or course's
                   15754:                   filespace, arguments are,
                   15755: 
1.620     albertel 15756:  formname - required - this is the name of the element in $env where the
1.608     albertel 15757:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15758:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15759:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15760:  context - if coursedoc, store the file in the course of the active role
                   15761:              of the current user; 
                   15762:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15763:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15764:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15765:          if undefined, it will be placed in "unknown"
                   15766: 
                   15767:  (This routine calls clean_filename() to remove any dangerous
                   15768:  characters from the filename, and then calls finuserfileupload() to
                   15769:  complete the transaction)
                   15770: 
                   15771:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15772:  and /adm/notfound.html if unsuccessful
                   15773: 
                   15774: =item *
                   15775: 
                   15776: clean_filename(): routine for cleaing a filename up for storage in
                   15777:                  userfile space, argument is:
                   15778: 
                   15779:  filename - proposed filename
                   15780: 
                   15781: returns: the new clean filename
                   15782: 
                   15783: =item *
                   15784: 
1.1090    raeburn  15785: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15786: userspace, probably shouldn't be called directly
                   15787: 
                   15788:   docuname: username or courseid of destination for the file
                   15789:   docudom: domain of user/course of destination for the file
                   15790:   formname: same as for userfileupload()
1.1090    raeburn  15791:   fname: filename (including subdirectories) for the file
                   15792:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15793:   allfiles: reference to hash used to store objects found by parser
                   15794:   codebase: reference to hash used for codebases of java objects found by parser
                   15795:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15796:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15797:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15798:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15799:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15800:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15801:   mimetype: reference to scalar to accommodate mime type determined
                   15802:             from File::MMagic if $parser = parse.
1.608     albertel 15803: 
                   15804:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15805:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15806:  was 'overwrite').
                   15807:  
1.608     albertel 15808: 
                   15809: =item *
                   15810: 
                   15811: renameuserfile(): renames an existing userfile to a new name
                   15812: 
                   15813:   Args:
                   15814:    docuname: username or courseid of destination for the file
                   15815:    docudom: domain of user/course of destination for the file
                   15816:    old: current file name (including any subdirs under userfiles)
                   15817:    new: desired file name (including any subdirs under userfiles)
                   15818: 
                   15819: =item *
                   15820: 
                   15821: mkdiruserfile(): creates a directory is a userfiles dir
                   15822: 
                   15823:   Args:
                   15824:    docuname: username or courseid of destination for the file
                   15825:    docudom: domain of user/course of destination for the file
                   15826:    dir: dir to create (including any subdirs under userfiles)
                   15827: 
                   15828: =item *
                   15829: 
                   15830: removeuserfile(): removes a file that exists in userfiles
                   15831: 
                   15832:   Args:
                   15833:    docuname: username or courseid of destination for the file
                   15834:    docudom: domain of user/course of destination for the file
                   15835:    fname: filname to delete (including any subdirs under userfiles)
                   15836: 
                   15837: =item *
                   15838: 
                   15839: removeuploadedurl(): convience function for removeuserfile()
                   15840: 
                   15841:   Args:
                   15842:    url:  a full /uploaded/... url to delete
                   15843: 
1.747     albertel 15844: =item * 
                   15845: 
                   15846: get_portfile_permissions():
                   15847:   Args:
                   15848:     domain: domain of user or course contain the portfolio files
                   15849:     user: name of user or num of course contain the portfolio files
                   15850:   Returns:
                   15851:     hashref of a dump of the proper file_permissions.db
                   15852:    
                   15853: 
                   15854: =item * 
                   15855: 
                   15856: get_access_controls():
                   15857: 
                   15858: Args:
                   15859:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15860:   group: (optional) the group you want the files associated with
                   15861:   file: (optional) the file you want access info on
                   15862: 
                   15863: Returns:
1.749     raeburn  15864:     a hash (keys are file names) of hashes containing
                   15865:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15866:         values are XML containing access control settings (see below) 
1.747     albertel 15867: 
                   15868: Internal notes:
                   15869: 
1.749     raeburn  15870:  access controls are stored in file_permissions.db as key=value pairs.
                   15871:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15872:         where scope -> public,guest,course,group,domains or users.
                   15873:               end -> UNIX time for end of access (0 -> no end date)
                   15874:               start -> UNIX time for start of access
                   15875: 
                   15876:     value -> XML description of access control
                   15877:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15878:             <start></start>
                   15879:             <end></end>
                   15880: 
                   15881:             <password></password>  for scope type = guest
                   15882: 
                   15883:             <domain></domain>     for scope type = course or group
                   15884:             <number></number>
                   15885:             <roles id="">
                   15886:              <role></role>
                   15887:              <access></access>
                   15888:              <section></section>
                   15889:              <group></group>
                   15890:             </roles>
                   15891: 
                   15892:             <dom></dom>         for scope type = domains
                   15893: 
                   15894:             <users>             for scope type = users
                   15895:              <user>
                   15896:               <uname></uname>
                   15897:               <udom></udom>
                   15898:              </user>
                   15899:             </users>
                   15900:            </scope> 
                   15901:               
                   15902:  Access data is also aggregated for each file in an additional key=value pair:
                   15903:  key -> path to file/file_name\0accesscontrol 
                   15904:  value -> reference to hash
                   15905:           hash contains key = value pairs
                   15906:           where key = uniqueID:scope_end_start
                   15907:                 value = UNIX time record was last updated
                   15908: 
                   15909:           Used to improve speed of look-ups of access controls for each file.  
                   15910:  
                   15911:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15912: 
1.1198    raeburn  15913: =item *
                   15914: 
1.749     raeburn  15915: modify_access_controls():
                   15916: 
                   15917: Modifies access controls for a portfolio file
                   15918: Args
                   15919: 1. file name
                   15920: 2. reference to hash of required changes,
                   15921: 3. domain
                   15922: 4. username
                   15923:   where domain,username are the domain of the portfolio owner 
                   15924:   (either a user or a course) 
                   15925: 
                   15926: Returns:
                   15927: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15928: 2. result of deletions ('ok' or 'error', with error message).
                   15929: 3. reference to hash of any new or updated access controls.
                   15930: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15931:    key = integer (inbound ID)
1.1198    raeburn  15932:    value = uniqueID
                   15933: 
                   15934: =item *
                   15935: 
                   15936: get_timebased_id():
                   15937: 
                   15938: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15939: course via the Course Editor (e.g., folders, composite pages, 
                   15940: group bulletin boards).
                   15941: 
                   15942: Args: (first three required; six others optional)
                   15943: 
                   15944: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15945:    docssequence, or name of group
                   15946: 
                   15947: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15948:    e.g., num, boardids
                   15949: 
                   15950: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15951:    file will be named nohist_namespace.db
                   15952: 
                   15953: 4. cdom: domain of course; default is current course domain from %env
                   15954: 
                   15955: 5. cnum: course number; default is current course number from %env
                   15956: 
                   15957: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15958:    unix timestamp to form the suffix, if the plain timestamp is already
                   15959:    in use.  Default is to not do this, but simply increment the unix 
                   15960:    timestamp by 1 until a unique key is obtained.
                   15961: 
                   15962: 7. who: holder of locking key; defaults to user:domain for user.
                   15963: 
                   15964: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15965:    retrying); default is 3.
                   15966: 
                   15967: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15968: 
                   15969: Returns:
                   15970: 
                   15971: 1. suffix obtained (numeric)
                   15972: 
                   15973: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15974: 
                   15975: 3. error: contains (localized) error message if an error occurred.
                   15976: 
1.747     albertel 15977: 
1.608     albertel 15978: =back
                   15979: 
1.243     albertel 15980: =head2 HTTP Helper Routines
                   15981: 
                   15982: =over 4
                   15983: 
1.191     harris41 15984: =item *
                   15985: 
                   15986: escape() : unpack non-word characters into CGI-compatible hex codes
                   15987: 
                   15988: =item *
                   15989: 
                   15990: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15991: 
1.243     albertel 15992: =back
                   15993: 
                   15994: =head1 PRIVATE SUBROUTINES
                   15995: 
                   15996: =head2 Underlying communication routines (Shouldn't call)
                   15997: 
                   15998: =over 4
                   15999: 
                   16000: =item *
                   16001: 
                   16002: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16003: 
                   16004: =item *
                   16005: 
                   16006: reply() : uses subreply to send a message to remote machine, logs all failures
                   16007: 
                   16008: =item *
                   16009: 
                   16010: critical() : passes a critical message to another server; if cannot
                   16011: get through then place message in connection buffer directory and
                   16012: returns con_delayed, if incapable of saving message, returns
                   16013: con_failed
                   16014: 
                   16015: =item *
                   16016: 
                   16017: reconlonc() : tries to reconnect lonc client processes.
                   16018: 
                   16019: =back
                   16020: 
                   16021: =head2 Resource Access Logging
                   16022: 
                   16023: =over 4
                   16024: 
                   16025: =item *
                   16026: 
                   16027: flushcourselogs() : flush (save) buffer logs and access logs
                   16028: 
                   16029: =item *
                   16030: 
                   16031: courselog($what) : save message for course in hash
                   16032: 
                   16033: =item *
                   16034: 
                   16035: courseacclog($what) : save message for course using &courselog().  Perform
                   16036: special processing for specific resource types (problems, exams, quizzes, etc).
                   16037: 
1.191     harris41 16038: =item *
                   16039: 
                   16040: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16041: as a PerlChildExitHandler
1.243     albertel 16042: 
                   16043: =back
                   16044: 
                   16045: =head2 Other
                   16046: 
                   16047: =over 4
                   16048: 
                   16049: =item *
                   16050: 
                   16051: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16052: 
                   16053: =back
                   16054: 
                   16055: =cut
1.877     foxr     16056: 

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