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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1395  ! raeburn     4: # $Id: lonnet.pm,v 1.1394 2018/12/08 15:17:25 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.672     albertel  461:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       462:                 " $cmd to $server returned $answer</font>");
                    463:     }
1.1       albertel  464:     return $answer;
                    465: }
                    466: 
                    467: # ----------------------------------------------------------- Send USR1 to lonc
                    468: 
                    469: sub reconlonc {
1.891     albertel  470:     my ($lonid) = @_;
                    471:     if ($lonid) {
1.1295    raeburn   472:         my $hostname = &hostname($lonid);
1.891     albertel  473: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    474: 	if ($hostname && -e $peerfile) {
                    475: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    476: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    477: 					     Type    => SOCK_STREAM,
                    478: 					     Timeout => 10);
                    479: 	    if ($client) {
                    480: 		print $client ("reset_retries\n");
                    481: 		my $answer=<$client>;
                    482: 		#reset just this one.
                    483: 	    }
                    484: 	}
                    485: 	return;
                    486:     }
                    487: 
1.836     www       488:     &logthis("Trying to reconnect lonc");
1.1       albertel  489:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   490:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  491: 	my $loncpid=<$fh>;
                    492:         chomp($loncpid);
                    493:         if (kill 0 => $loncpid) {
                    494: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    495:             kill USR1 => $loncpid;
                    496:             sleep 1;
1.1295    raeburn   497:         } else {
1.12      www       498: 	    &logthis(
1.672     albertel  499:                "<font color=\"blue\">WARNING:".
1.12      www       500:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  501:         }
                    502:     } else {
1.836     www       503: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  504:     }
                    505: }
                    506: 
                    507: # ------------------------------------------------------ Critical communication
1.12      www       508: 
1.1       albertel  509: sub critical {
                    510:     my ($cmd,$server)=@_;
1.838     albertel  511:     unless (&hostname($server)) {
1.672     albertel  512:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       513:                " Critical message to unknown server ($server)</font>");
                    514:         return 'no_such_host';
                    515:     }
1.1       albertel  516:     my $answer=reply($cmd,$server);
                    517:     if ($answer eq 'con_lost') {
1.1295    raeburn   518: 	&reconlonc($server);
1.589     albertel  519: 	my $answer=reply($cmd,$server);
1.1       albertel  520:         if ($answer eq 'con_lost') {
                    521:             my $now=time;
                    522:             my $middlename=$cmd;
1.5       www       523:             $middlename=substr($middlename,0,16);
1.1       albertel  524:             $middlename=~s/\W//g;
                    525:             my $dfilename=
1.305     www       526:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    527:             $dumpcount++;
1.1       albertel  528:             {
1.448     albertel  529: 		my $dfh;
1.1359    raeburn   530: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  531: 		    print $dfh "$cmd\n"; 
                    532: 		    close($dfh);
                    533: 		}
1.1       albertel  534:             }
1.1288    damieng   535:             sleep 1;
1.1       albertel  536:             my $wcmd='';
                    537:             {
1.448     albertel  538: 		my $dfh;
1.1359    raeburn   539: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  540: 		    $wcmd=<$dfh>; 
                    541: 		    close($dfh);
                    542: 		}
1.1       albertel  543:             }
                    544:             chomp($wcmd);
1.7       www       545:             if ($wcmd eq $cmd) {
1.672     albertel  546: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       547:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  548:                 &logperm("D:$server:$cmd");
                    549: 	        return 'con_delayed';
                    550:             } else {
1.672     albertel  551:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       552:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  553:                 &logperm("F:$server:$cmd");
                    554:                 return 'con_failed';
                    555:             }
                    556:         }
                    557:     }
                    558:     return $answer;
1.405     albertel  559: }
                    560: 
1.755     albertel  561: # ------------------------------------------- check if return value is an error
                    562: 
                    563: sub error {
                    564:     my ($result) = @_;
1.756     albertel  565:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  566: 	if ($2 == 2) { return undef; }
                    567: 	return $1;
                    568:     }
                    569:     return undef;
                    570: }
                    571: 
1.783     albertel  572: sub convert_and_load_session_env {
                    573:     my ($lonidsdir,$handle)=@_;
                    574:     my @profile;
                    575:     {
1.917     albertel  576: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    577: 	if (!$opened) {
1.915     albertel  578: 	    return 0;
                    579: 	}
1.783     albertel  580: 	flock($idf,LOCK_SH);
                    581: 	@profile=<$idf>;
                    582: 	close($idf);
                    583:     }
                    584:     my %temp_env;
                    585:     foreach my $line (@profile) {
1.786     albertel  586: 	if ($line !~ m/=/) {
                    587: 	    return 0;
                    588: 	}
1.783     albertel  589: 	chomp($line);
                    590: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    591: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    592:     }
                    593:     unlink("$lonidsdir/$handle.id");
                    594:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    595: 	    0640)) {
                    596: 	%disk_env = %temp_env;
                    597: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    598: 	untie(%disk_env);
                    599:     }
1.786     albertel  600:     return 1;
1.783     albertel  601: }
                    602: 
1.374     www       603: # ------------------------------------------- Transfer profile into environment
1.780     albertel  604: my $env_loaded;
                    605: sub transfer_profile_to_env {
1.788     albertel  606:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    607:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       608: 
1.720     albertel  609:     if (!defined($lonidsdir)) {
                    610: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    611:     }
                    612:     if (!defined($handle)) {
                    613:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    614:     }
                    615: 
1.786     albertel  616:     my $convert;
                    617:     {
1.917     albertel  618:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    619: 	if (!$opened) {
1.915     albertel  620: 	    return;
                    621: 	}
1.786     albertel  622: 	flock($idf,LOCK_SH);
                    623: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    624: 		&GDBM_READER(),0640)) {
                    625: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    626: 	    untie(%disk_env);
                    627: 	} else {
                    628: 	    $convert = 1;
                    629: 	}
                    630:     }
                    631:     if ($convert) {
                    632: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    633: 	    &logthis("Failed to load session, or convert session.");
                    634: 	}
1.374     www       635:     }
1.783     albertel  636: 
1.786     albertel  637:     my %remove;
1.783     albertel  638:     while ( my $envname = each(%env) ) {
1.433     matthew   639:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    640:             if ($time < time-300) {
1.783     albertel  641:                 $remove{$key}++;
1.433     matthew   642:             }
                    643:         }
                    644:     }
1.783     albertel  645: 
1.619     albertel  646:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  647:     $env_loaded=1;
1.783     albertel  648:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   649:         &delenv($expired_key);
1.374     www       650:     }
1.1       albertel  651: }
                    652: 
1.916     albertel  653: # ---------------------------------------------------- Check for valid session 
                    654: sub check_for_valid_session {
1.1355    raeburn   655:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  656:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   657:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    658:     if ($name eq 'lonDAV') {
                    659:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    660:     } else {
                    661:         $lonidsdir=$r->dir_config('lonIDsDir');
                    662:         if ($name eq '') {
                    663:             $name = 'lonID';
                    664:         }
                    665:     }
                    666:     if ($name eq 'lonID') {
                    667:         $secure = 'lonSID';
1.1337    raeburn   668:         $linkname = 'lonLinkID';
                    669:         $pubname = 'lonPubID';
1.1378    raeburn   670:         if (exists($cookies{$secure})) {
                    671:             $lonid=$cookies{$secure};
                    672:         } elsif (exists($cookies{$name})) {
                    673:             $lonid=$cookies{$name};
                    674:         } elsif (exists($cookies{$linkname})) {
1.1337    raeburn   675:             $lonid=$cookies{$linkname};
1.1378    raeburn   676:         } elsif (exists($cookies{$pubname})) {
                    677:             $lonid=$cookies{$pubname};
1.1337    raeburn   678:         }
1.1378    raeburn   679:     } else {
                    680:         $lonid=$cookies{$name};
1.1337    raeburn   681:     }
1.916     albertel  682:     return undef if (!$lonid);
                    683: 
                    684:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   685:     if (-l "$lonidsdir/$handle.id") {
                    686:         my $link = readlink("$lonidsdir/$handle.id");
                    687:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    688:             $handle = $1;
                    689:         }
1.1155    raeburn   690:     }
1.1355    raeburn   691:     if (!-e "$lonidsdir/$handle.id") {
                    692:         if ((ref($domref)) && ($name eq 'lonID') && 
                    693:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    694:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    695:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    696:                 $$domref = $possudom;
                    697:             }
                    698:         }
                    699:         return undef;
                    700:     }
1.916     albertel  701: 
1.917     albertel  702:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    703:     return undef if (!$opened);
1.916     albertel  704: 
                    705:     flock($idf,LOCK_SH);
                    706:     my %disk_env;
                    707:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    708: 	    &GDBM_READER(),0640)) {
                    709: 	return undef;	
                    710:     }
                    711: 
                    712:     if (!defined($disk_env{'user.name'})
                    713: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   714:         untie(%disk_env);
1.916     albertel  715: 	return undef;
                    716:     }
1.1245    raeburn   717: 
                    718:     if (ref($userhashref) eq 'HASH') {
                    719:         $userhashref->{'name'} = $disk_env{'user.name'};
                    720:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   721:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   722:         if ($userhashref->{'lti'}) {
                    723:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    724:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    725:         }
1.1212    raeburn   726:     }
1.1394    raeburn   727:     untie(%disk_env);
1.1245    raeburn   728: 
1.916     albertel  729:     return $handle;
                    730: }
                    731: 
1.830     albertel  732: sub timed_flock {
                    733:     my ($file,$lock_type) = @_;
                    734:     my $failed=0;
                    735:     eval {
                    736: 	local $SIG{__DIE__}='DEFAULT';
                    737: 	local $SIG{ALRM}=sub {
                    738: 	    $failed=1;
                    739: 	    die("failed lock");
                    740: 	};
                    741: 	alarm(13);
                    742: 	flock($file,$lock_type);
                    743: 	alarm(0);
                    744:     };
                    745:     if ($failed) {
                    746: 	return undef;
                    747:     } else {
                    748: 	return 1;
                    749:     }
                    750: }
                    751: 
1.1392    raeburn   752: sub get_sessionfile_vars {
                    753:     my ($handle,$lonidsdir,$storearr) = @_;
                    754:     my %returnhash;
                    755:     unless (ref($storearr) eq 'ARRAY') {
                    756:         return %returnhash;
                    757:     }
                    758:     if (-l "$lonidsdir/$handle.id") {
                    759:         my $link = readlink("$lonidsdir/$handle.id");
                    760:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    761:             $handle = $1;
                    762:         }
                    763:     }
                    764:     if ((-e "$lonidsdir/$handle.id") &&
                    765:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    766:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    767:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    768:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    769:                 flock($idf,LOCK_SH);
                    770:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    771:                         &GDBM_READER(),0640)) {
                    772:                     foreach my $item (@{$storearr}) {
                    773:                         $returnhash{$item} = $disk_env{$item};
                    774:                     }
                    775:                     untie(%disk_env);
                    776:                 }
                    777:             }
                    778:         }
                    779:     }
                    780:     return %returnhash;
                    781: }
                    782: 
1.5       www       783: # ---------------------------------------------------------- Append Environment
                    784: 
                    785: sub appenv {
1.949     raeburn   786:     my ($newenv,$roles) = @_;
                    787:     if (ref($newenv) eq 'HASH') {
                    788:         foreach my $key (keys(%{$newenv})) {
                    789:             my $refused = 0;
                    790: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    791:                 $refused = 1;
                    792:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   793:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   794:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    795:                         $refused = 0;
                    796:                     }
                    797:                 }
                    798:             }
                    799:             if ($refused) {
                    800:                 &logthis("<font color=\"blue\">WARNING: ".
                    801:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    802:                          .'</font>');
                    803: 	        delete($newenv->{$key});
                    804:             } else {
                    805:                 $env{$key}=$newenv->{$key};
                    806:             }
                    807:         }
1.1376    raeburn   808:         my $lonids = $perlvar{'lonIDsDir'};
                    809:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    810:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    811:             if ($opened
                    812: 	        && &timed_flock($env_file,LOCK_EX)
                    813: 	        &&
                    814: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    815: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    816: 	        while (my ($key,$value) = each(%{$newenv})) {
                    817: 	            $disk_env{$key} = $value;
                    818: 	        }
                    819: 	        untie(%disk_env);
                    820:             }
1.35      www       821:         }
1.191     harris41  822:     }
1.56      www       823:     return 'ok';
                    824: }
                    825: # ----------------------------------------------------- Delete from Environment
                    826: 
                    827: sub delenv {
1.1104    raeburn   828:     my ($delthis,$regexp,$roles) = @_;
                    829:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    830:         my $refused = 1;
                    831:         if (ref($roles) eq 'ARRAY') {
                    832:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    833:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    834:                 $refused = 0;
                    835:             }
                    836:         }
                    837:         if ($refused) {
                    838:             &logthis("<font color=\"blue\">WARNING: ".
                    839:                      "Attempt to delete from environment ".$delthis);
                    840:             return 'error';
                    841:         }
1.56      www       842:     }
1.917     albertel  843:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    844:     if ($opened
1.915     albertel  845: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  846: 	&&
                    847: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    848: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  849: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   850: 	    if ($regexp) {
                    851:                 if ($key=~/^$delthis/) {
                    852:                     delete($env{$key});
                    853:                     delete($disk_env{$key});
                    854:                 } 
                    855:             } else {
                    856:                 if ($key=~/^\Q$delthis\E/) {
                    857: 		    delete($env{$key});
                    858: 		    delete($disk_env{$key});
                    859: 	        }
                    860:             }
1.448     albertel  861: 	}
1.783     albertel  862: 	untie(%disk_env);
1.5       www       863:     }
                    864:     return 'ok';
1.369     albertel  865: }
                    866: 
1.790     albertel  867: sub get_env_multiple {
                    868:     my ($name) = @_;
                    869:     my @values;
                    870:     if (defined($env{$name})) {
                    871:         # exists is it an array
                    872:         if (ref($env{$name})) {
                    873:             @values=@{ $env{$name} };
                    874:         } else {
                    875:             $values[0]=$env{$name};
                    876:         }
                    877:     }
                    878:     return(@values);
                    879: }
                    880: 
1.958     www       881: # ------------------------------------------------------------------- Locking
                    882: 
                    883: sub set_lock {
                    884:     my ($text)=@_;
                    885:     $locknum++;
                    886:     my $id=$$.'-'.$locknum;
                    887:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    888:              'session.lock.'.$id => $text});
                    889:     return $id;
                    890: }
                    891: 
                    892: sub get_locks {
                    893:     my $num=0;
                    894:     my %texts=();
                    895:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    896:        if ($lock=~/\w/) {
                    897:           $num++;
                    898:           $texts{$lock}=$env{'session.lock.'.$lock};
                    899:        }
                    900:    }
                    901:    return ($num,%texts);
                    902: }
                    903: 
                    904: sub remove_lock {
                    905:     my ($id)=@_;
                    906:     my $newlocks='';
                    907:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    908:        if (($lock=~/\w/) && ($lock ne $id)) {
                    909:           $newlocks.=','.$lock;
                    910:        }
                    911:     }
                    912:     &appenv({'session.locks' => $newlocks});
                    913:     &delenv('session.lock.'.$id);
                    914: }
                    915: 
                    916: sub remove_all_locks {
                    917:     my $activelocks=$env{'session.locks'};
                    918:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    919:        if ($lock=~/\w/) {
                    920:           &remove_lock($lock);
                    921:        }
                    922:     }
                    923: }
                    924: 
                    925: 
1.369     albertel  926: # ------------------------------------------ Find out current server userload
                    927: sub userload {
                    928:     my $numusers=0;
                    929:     {
                    930: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    931: 	my $filename;
                    932: 	my $curtime=time;
                    933: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  934: 	    next if ($filename eq '.' || $filename eq '..');
                    935: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   936:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  937: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  938: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  939: 	}
                    940: 	closedir(LONIDS);
                    941:     }
                    942:     my $userloadpercent=0;
                    943:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    944:     if ($maxuserload) {
1.371     albertel  945: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  946:     }
1.372     albertel  947:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  948:     return $userloadpercent;
1.283     www       949: }
                    950: 
1.1       albertel  951: # ------------------------------ Find server with least workload from spare.tab
1.11      www       952: 
1.1       albertel  953: sub spareserver {
1.1083    raeburn   954:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  955:     my $spare_server;
1.370     albertel  956:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  957:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    958:                                                      :  $userloadpercent;
1.1083    raeburn   959:     my ($uint_dom,$remotesessions);
                    960:     if (($udom ne '') && (&domain($udom) ne '')) {
                    961:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    962:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    963:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    964:         $remotesessions = $udomdefaults{'remotesessions'};
                    965:     }
1.1123    raeburn   966:     my $spareshash = &this_host_spares($udom);
                    967:     if (ref($spareshash) eq 'HASH') {
                    968:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    969:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   970:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    971:                                              $try_server));
1.1123    raeburn   972: 	        ($spare_server, $lowest_load) =
                    973: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    974:             }
1.1083    raeburn   975:         }
1.784     albertel  976: 
1.1123    raeburn   977:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    978: 
                    979:         if (!$found_server) {
                    980:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    981: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   982:                     next unless (&spare_can_host($udom,$uint_dom,
                    983:                                                  $remotesessions,$try_server));
1.1123    raeburn   984: 	            ($spare_server, $lowest_load) =
                    985: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    986:                 }
                    987: 	    }
                    988:         }
1.784     albertel  989:     }
                    990: 
                    991:     if (!$want_server_name) {
1.968     raeburn   992:         my $protocol = 'http';
                    993:         if ($protocol{$spare_server} eq 'https') {
                    994:             $protocol = $protocol{$spare_server};
                    995:         }
1.1001    raeburn   996:         if (defined($spare_server)) {
                    997:             my $hostname = &hostname($spare_server);
1.1083    raeburn   998:             if (defined($hostname)) {
1.1001    raeburn   999: 	        $spare_server = $protocol.'://'.$hostname;
                   1000:             }
                   1001:         }
1.784     albertel 1002:     }
                   1003:     return $spare_server;
                   1004: }
                   1005: 
                   1006: sub compare_server_load {
1.1253    raeburn  1007:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1008: 
                   1009:     if ($required) {
                   1010:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1011:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1012:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1013:         if (($major eq '' && $minor eq '') ||
                   1014:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1015:             return ($spare_server,$lowest_load);
                   1016:         }
                   1017:     }
1.784     albertel 1018: 
                   1019:     my $loadans     = &reply('load',    $try_server);
                   1020:     my $userloadans = &reply('userload',$try_server);
                   1021: 
                   1022:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1023: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1024:     }
                   1025: 
                   1026:     my $load;
                   1027:     if ($loadans =~ /\d/) {
                   1028: 	if ($userloadans =~ /\d/) {
                   1029: 	    #both are numbers, pick the bigger one
                   1030: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1031: 		                              : $userloadans;
1.411     albertel 1032: 	} else {
1.784     albertel 1033: 	    $load = $loadans;
1.411     albertel 1034: 	}
1.784     albertel 1035:     } else {
                   1036: 	$load = $userloadans;
                   1037:     }
                   1038: 
                   1039:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1040: 	$spare_server = $try_server;
                   1041: 	$lowest_load  = $load;
1.370     albertel 1042:     }
1.784     albertel 1043:     return ($spare_server,$lowest_load);
1.202     matthew  1044: }
1.914     albertel 1045: 
                   1046: # --------------------------- ask offload servers if user already has a session
                   1047: sub find_existing_session {
                   1048:     my ($udom,$uname) = @_;
1.1123    raeburn  1049:     my $spareshash = &this_host_spares($udom);
                   1050:     if (ref($spareshash) eq 'HASH') {
                   1051:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1052:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1053:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1054:             }
                   1055:         }
                   1056:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1057:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1058:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1059:             }
                   1060:         }
1.914     albertel 1061:     }
                   1062:     return;
                   1063: }
                   1064: 
1.1389    raeburn  1065: # check if user's browser sent load balancer cookie and server still has session
                   1066: # and is not overloaded.
                   1067: sub check_for_balancer_cookie {
                   1068:     my ($r,$update_mtime) = @_;
                   1069:     my ($otherserver,$cookie);
                   1070:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1071:     if (exists($cookies{'balanceID'})) {
                   1072:         my $balid = $cookies{'balanceID'};
                   1073:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1074:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1075:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1076:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1077:                 my ($possudom,$possuname) = ($1,$2);
                   1078:                 my $has_session = 0;
                   1079:                 if ((&domain($possudom) ne '') &&
                   1080:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1081:                     my $try_server;
                   1082:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1083:                     if ($opened) {
                   1084:                         flock($idf,LOCK_SH);
                   1085:                         while (my $line = <$idf>) {
                   1086:                             chomp($line);
                   1087:                             if (&hostname($line) ne '') {
                   1088:                                 $try_server = $line;
                   1089:                                 last;
                   1090:                             }
                   1091:                         }
                   1092:                         close($idf);
                   1093:                         if (($try_server) &&
                   1094:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1095:                             my $lowest_load = 30000;
                   1096:                             ($otherserver,$lowest_load) =
                   1097:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1098:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1099:                                 $has_session = 1;
                   1100:                             } else {
                   1101:                                 undef($otherserver);
                   1102:                             }
                   1103:                         }
                   1104:                     }
                   1105:                 }
                   1106:                 if ($has_session) {
                   1107:                     if ($update_mtime) {
                   1108:                         my $atime = my $mtime = time;
                   1109:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1110:                     }
                   1111:                 } else {
                   1112:                     unlink("$balancedir/$cookie.id");
                   1113:                 }
                   1114:             }
                   1115:         }
                   1116:     }
                   1117:     return ($otherserver,$cookie);
                   1118: }
                   1119: 
                   1120: sub delbalcookie {
                   1121:     my ($cookie,$balancer) =@_;
                   1122:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1123:         my ($udom,$uname) = ($1,$2);
                   1124:         my $uprimary_id = &domain($udom,'primary');
                   1125:         my $uintdom = &internet_dom($uprimary_id);
                   1126:         my $intdom = &internet_dom($balancer);
                   1127:         my $serverhomedom = &host_domain($balancer);
                   1128:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1129:             return &reply("delbalcookie:$cookie",$balancer);
                   1130:         }
                   1131:     }
                   1132: }
                   1133: 
1.914     albertel 1134: # -------------------------------- ask if server already has a session for user
                   1135: sub has_user_session {
                   1136:     my ($lonid,$udom,$uname) = @_;
                   1137:     my $result = &reply(join(':','userhassession',
                   1138: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1139:     return 1 if ($result eq 'ok');
                   1140: 
                   1141:     return 0;
                   1142: }
                   1143: 
1.1076    raeburn  1144: # --------- determine least loaded server in a user's domain which allows login
                   1145: 
                   1146: sub choose_server {
1.1259    raeburn  1147:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1148:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1149:     my %servers = &get_servers($udom);
1.1076    raeburn  1150:     my $lowest_load = 30000;
1.1259    raeburn  1151:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1152:     if ($skiploadbal) {
                   1153:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1154:         unless (defined($cached)) {
                   1155:             my $cachetime = 60*60*24;
                   1156:             my %domconfig =
                   1157:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1158:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1159:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1160:                                            $cachetime);
                   1161:             }
                   1162:         }
                   1163:     }
1.1076    raeburn  1164:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1165:         if ($skiploadbal) {
                   1166:             if (ref($balancers) eq 'HASH') {
                   1167:                 next if (exists($balancers->{$lonhost}));
                   1168:             }
1.1389    raeburn  1169:         }
1.1115    raeburn  1170:         my $loginvia;
                   1171:         if ($checkloginvia) {
                   1172:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1173:             if ($loginvia) {
                   1174:                 my ($server,$path) = split(/:/,$loginvia);
                   1175:                 ($login_host, $lowest_load) =
1.1253    raeburn  1176:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1177:                 if ($login_host eq $server) {
                   1178:                     $portal_path = $path;
1.1151    raeburn  1179:                     $isredirect = 1;
1.1116    raeburn  1180:                 }
                   1181:             } else {
                   1182:                 ($login_host, $lowest_load) =
1.1253    raeburn  1183:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1184:                 if ($login_host eq $lonhost) {
                   1185:                     $portal_path = '';
1.1151    raeburn  1186:                     $isredirect = ''; 
1.1116    raeburn  1187:                 }
                   1188:             }
                   1189:         } else {
1.1076    raeburn  1190:             ($login_host, $lowest_load) =
1.1253    raeburn  1191:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1192:         }
                   1193:     }
                   1194:     if ($login_host ne '') {
1.1116    raeburn  1195:         $hostname = &hostname($login_host);
1.1076    raeburn  1196:     }
1.1331    raeburn  1197:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1198: }
                   1199: 
1.202     matthew  1200: # --------------------------------------------- Try to change a user's password
                   1201: 
                   1202: sub changepass {
1.799     raeburn  1203:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1204:     $currentpass = &escape($currentpass);
                   1205:     $newpass     = &escape($newpass);
1.1030    raeburn  1206:     my $lonhost = $perlvar{'lonHostID'};
                   1207:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1208: 		       $server);
                   1209:     if (! $answer) {
                   1210: 	&logthis("No reply on password change request to $server ".
                   1211: 		 "by $uname in domain $udom.");
                   1212:     } elsif ($answer =~ "^ok") {
                   1213:         &logthis("$uname in $udom successfully changed their password ".
                   1214: 		 "on $server.");
                   1215:     } elsif ($answer =~ "^pwchange_failure") {
                   1216: 	&logthis("$uname in $udom was unable to change their password ".
                   1217: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1218: 		 "or pwchange");
                   1219:     } elsif ($answer =~ "^non_authorized") {
                   1220:         &logthis("$uname in $udom did not get their password correct when ".
                   1221: 		 "attempting to change it on $server.");
                   1222:     } elsif ($answer =~ "^auth_mode_error") {
                   1223:         &logthis("$uname in $udom attempted to change their password despite ".
                   1224: 		 "not being locally or internally authenticated on $server.");
                   1225:     } elsif ($answer =~ "^unknown_user") {
                   1226:         &logthis("$uname in $udom attempted to change their password ".
                   1227: 		 "on $server but were unable to because $server is not ".
                   1228: 		 "their home server.");
                   1229:     } elsif ($answer =~ "^refused") {
                   1230: 	&logthis("$server refused to change $uname in $udom password because ".
                   1231: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1232:     } elsif ($answer =~ "invalid_client") {
                   1233:         &logthis("$server refused to change $uname in $udom password because ".
                   1234:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1235:     }
                   1236:     return $answer;
1.1       albertel 1237: }
                   1238: 
1.169     harris41 1239: # ----------------------- Try to determine user's current authentication scheme
                   1240: 
                   1241: sub queryauthenticate {
                   1242:     my ($uname,$udom)=@_;
1.456     albertel 1243:     my $uhome=&homeserver($uname,$udom);
                   1244:     if (!$uhome) {
                   1245: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1246: 	return 'no_host';
                   1247:     }
                   1248:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1249:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1250: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1251:     }
1.456     albertel 1252:     return $answer;
1.169     harris41 1253: }
                   1254: 
1.1       albertel 1255: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1256: 
1.1       albertel 1257: sub authenticate {
1.1073    raeburn  1258:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1259:     $upass=&escape($upass);
                   1260:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1261:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1262:     my $newhome;
1.836     www      1263:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1264: # Maybe the machine was offline and only re-appeared again recently?
                   1265:         &reconlonc();
                   1266: # One more
1.952     raeburn  1267: 	$uhome=&homeserver($uname,$udom,1);
                   1268:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1269:             if (defined(&domain($udom,'primary'))) {
                   1270:                 $newhome=&domain($udom,'primary');
                   1271:             }
                   1272:             if ($newhome ne '') {
                   1273:                 $uhome = $newhome;
                   1274:             }
                   1275:         }
1.836     www      1276: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1277: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1278: 	    return 'no_host';
                   1279:         }
1.1       albertel 1280:     }
1.1073    raeburn  1281:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1282:     if ($answer eq 'authorized') {
1.952     raeburn  1283:         if ($newhome) {
                   1284:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1285:             return 'no_account_on_host'; 
                   1286:         } else {
                   1287:             &logthis("User $uname at $udom authorized by $uhome");
                   1288:             return $uhome;
                   1289:         }
1.471     albertel 1290:     }
                   1291:     if ($answer eq 'non_authorized') {
                   1292: 	&logthis("User $uname at $udom rejected by $uhome");
                   1293: 	return 'no_host'; 
1.9       www      1294:     }
1.471     albertel 1295:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1296:     return 'no_host';
                   1297: }
                   1298: 
1.1073    raeburn  1299: sub can_host_session {
1.1074    raeburn  1300:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1301:     my $canhost = 1;
1.1074    raeburn  1302:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1303:     if (ref($remotesessions) eq 'HASH') {
                   1304:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1305:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1306:                 $canhost = 0;
                   1307:             } else {
                   1308:                 $canhost = 1;
                   1309:             }
                   1310:         }
                   1311:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1312:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1313:                 $canhost = 1;
                   1314:             } else {
                   1315:                 $canhost = 0;
                   1316:             }
                   1317:         }
                   1318:         if ($canhost) {
                   1319:             if ($remotesessions->{'version'} ne '') {
                   1320:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1321:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1322:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1323:                         my $major = $1;
                   1324:                         my $minor = $2;
                   1325:                         if (($major < $reqmajor ) ||
                   1326:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1327:                             $canhost = 0;
                   1328:                         }
                   1329:                     } else {
                   1330:                         $canhost = 0;
                   1331:                     }
                   1332:                 }
                   1333:             }
                   1334:         }
                   1335:     }
                   1336:     if ($canhost) {
                   1337:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1338:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1339:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1340:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1341:                 if (($uint_dom ne '') && 
                   1342:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1343:                     $canhost = 0;
                   1344:                 } else {
                   1345:                     $canhost = 1;
                   1346:                 }
                   1347:             }
                   1348:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1349:                 if (($uint_dom ne '') && 
                   1350:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1351:                     $canhost = 1;
                   1352:                 } else {
                   1353:                     $canhost = 0;
                   1354:                 }
                   1355:             }
                   1356:         }
                   1357:     }
                   1358:     return $canhost;
                   1359: }
                   1360: 
1.1083    raeburn  1361: sub spare_can_host {
                   1362:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1363:     my $canhost=1;
1.1279    raeburn  1364:     my $try_server_hostname = &hostname($try_server);
                   1365:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1366:     my $serverhomedom = &host_domain($serverhomeID);
                   1367:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1368:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1369:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1370:             $canhost = 0;
                   1371:         }
                   1372:     }
                   1373:     if (($canhost) && ($uint_dom)) {
                   1374:         my @intdoms;
                   1375:         my $internet_names = &get_internet_names($try_server);
                   1376:         if (ref($internet_names) eq 'ARRAY') {
                   1377:             @intdoms = @{$internet_names};
                   1378:         }
                   1379:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1380:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1381:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1382:                                          $remotesessions,
                   1383:                                          $defdomdefaults{'hostedsessions'});
                   1384:         }
1.1083    raeburn  1385:     }
                   1386:     return $canhost;
                   1387: }
                   1388: 
1.1123    raeburn  1389: sub this_host_spares {
                   1390:     my ($dom) = @_;
1.1126    raeburn  1391:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1392:     my @hosts = &current_machine_ids();
                   1393:     foreach my $lonhost (@hosts) {
                   1394:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1395:             $dom_in_use = $dom;
                   1396:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1397:             last;
                   1398:         }
                   1399:     }
1.1126    raeburn  1400:     if ($dom_in_use ne '') {
                   1401:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1402:     }
                   1403:     if (ref($result) ne 'HASH') {
                   1404:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1405:         $dom_in_use = &host_domain($lonhost_in_use);
                   1406:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1407:         if (ref($result) ne 'HASH') {
                   1408:             $result = \%spareid;
                   1409:         }
                   1410:     }
                   1411:     return $result;
                   1412: }
                   1413: 
                   1414: sub spares_for_offload  {
                   1415:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1416:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1417:     if (defined($cached)) {
                   1418:         return $result;
                   1419:     } else {
1.1126    raeburn  1420:         my $cachetime = 60*60*24;
                   1421:         my %domconfig =
                   1422:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1423:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1424:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1425:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1426:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1427:                 }
                   1428:             }
                   1429:         }
                   1430:     }
1.1126    raeburn  1431:     return;
1.1123    raeburn  1432: }
                   1433: 
1.1129    raeburn  1434: sub get_lonbalancer_config {
                   1435:     my ($servers) = @_;
                   1436:     my ($currbalancer,$currtargets);
                   1437:     if (ref($servers) eq 'HASH') {
                   1438:         foreach my $server (keys(%{$servers})) {
                   1439:             my %what = (
                   1440:                          spareid => 1,
                   1441:                          perlvar => 1,
                   1442:                        );
                   1443:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1444:             if ($result eq 'ok') {
                   1445:                 if (ref($returnhash) eq 'HASH') {
                   1446:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1447:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1448:                             $currbalancer = $server;
                   1449:                             $currtargets = {};
                   1450:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1451:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1452:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1453:                                 }
                   1454:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1455:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1456:                                 }
                   1457:                             }
                   1458:                             last;
                   1459:                         }
                   1460:                     }
                   1461:                 }
                   1462:             }
                   1463:         }
                   1464:     }
                   1465:     return ($currbalancer,$currtargets);
                   1466: }
                   1467: 
                   1468: sub check_loadbalancing {
1.1331    raeburn  1469:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1470:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1471:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1472:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1473:     my @hosts = &current_machine_ids();
1.1129    raeburn  1474:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1475:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1476:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1477:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1478:     my $domneedscache;
1.1129    raeburn  1479:     my $cachetime = 60*60*24;
                   1480: 
                   1481:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1482:         $dom_in_use = $udom;
                   1483:         $homeintdom = 1;
                   1484:     } else {
                   1485:         $dom_in_use = $serverhomedom;
                   1486:     }
                   1487:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1488:     unless (defined($cached)) {
                   1489:         my %domconfig =
                   1490:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1491:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1492:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1493:         } else {
                   1494:             $domneedscache = $dom_in_use;
1.1129    raeburn  1495:         }
                   1496:     }
                   1497:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1498:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1499:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1500:         if ($is_balancer) {
                   1501:             if (ref($currrules) eq 'HASH') {
                   1502:                 if ($homeintdom) {
                   1503:                     if ($uname ne '') {
                   1504:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1505:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1506:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1507:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1508:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1509:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1510:                             }
                   1511:                         }
                   1512:                         if ($rule_in_effect eq '') {
                   1513:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1514:                             if ($userenv{'inststatus'} ne '') {
                   1515:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1516:                                 my ($othertitle,$usertypes,$types) =
                   1517:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1518:                                 if (ref($types) eq 'ARRAY') {
                   1519:                                     foreach my $type (@{$types}) {
                   1520:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1521:                                             if (exists($currrules->{$type})) {
                   1522:                                                 $rule_in_effect = $currrules->{$type};
                   1523:                                             }
                   1524:                                         }
                   1525:                                     }
                   1526:                                 }
                   1527:                             } else {
                   1528:                                 if (exists($currrules->{'default'})) {
                   1529:                                     $rule_in_effect = $currrules->{'default'};
                   1530:                                 }
                   1531:                             }
                   1532:                         }
                   1533:                     } else {
                   1534:                         if (exists($currrules->{'default'})) {
                   1535:                             $rule_in_effect = $currrules->{'default'};
                   1536:                         }
                   1537:                     }
                   1538:                 } else {
                   1539:                     if ($currrules->{'_LC_external'} ne '') {
                   1540:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1541:                     }
                   1542:                 }
                   1543:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1544:                                                        $uname,$udom);
                   1545:             }
                   1546:         }
                   1547:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1548:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1549:         unless (defined($cached)) {
                   1550:             my %domconfig =
                   1551:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1552:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1553:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1554:             } else {
                   1555:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1556:             }
                   1557:         }
                   1558:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1559:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1560:                 &check_balancer_result($result,@hosts);
                   1561:             if ($is_balancer) {
1.1129    raeburn  1562:                 if (ref($currrules) eq 'HASH') {
                   1563:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1564:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1565:                     }
                   1566:                 }
                   1567:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1568:                                                        $uname,$udom);
                   1569:             }
                   1570:         } else {
                   1571:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1572:                 $is_balancer = 1;
                   1573:                 $offloadto = &this_host_spares($dom_in_use);
                   1574:             }
1.1307    raeburn  1575:             unless (defined($cached)) {
                   1576:                 $domneedscache = $serverhomedom;
                   1577:             }
1.1129    raeburn  1578:         }
                   1579:     } else {
                   1580:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1581:             $is_balancer = 1;
                   1582:             $offloadto = &this_host_spares($dom_in_use);
                   1583:         }
1.1307    raeburn  1584:         unless (defined($cached)) {
                   1585:             $domneedscache = $serverhomedom;
                   1586:         }
                   1587:     }
                   1588:     if ($domneedscache) {
                   1589:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1590:     }
1.1176    raeburn  1591:     if ($is_balancer) {
                   1592:         my $lowest_load = 30000;
                   1593:         if (ref($offloadto) eq 'HASH') {
                   1594:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1595:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1596:                     ($otherserver,$lowest_load) =
                   1597:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1598:                 }
1.1129    raeburn  1599:             }
1.1176    raeburn  1600:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1601: 
1.1176    raeburn  1602:             if (!$found_server) {
                   1603:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1604:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1605:                         ($otherserver,$lowest_load) =
                   1606:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1607:                     }
                   1608:                 }
                   1609:             }
                   1610:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1611:             if (@{$offloadto} == 1) {
                   1612:                 $otherserver = $offloadto->[0];
                   1613:             } elsif (@{$offloadto} > 1) {
                   1614:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1615:                     ($otherserver,$lowest_load) =
                   1616:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1617:                 }
                   1618:             }
                   1619:         }
1.1331    raeburn  1620:         unless ($caller eq 'login') {
                   1621:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1622:                 $is_balancer = 0;
                   1623:                 if ($uname ne '' && $udom ne '') {
                   1624:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1625:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1626:                                  'user.loadbalcheck.time' => time});
                   1627:                     }
1.1176    raeburn  1628:                 }
1.1129    raeburn  1629:             }
                   1630:         }
1.1389    raeburn  1631:         unless ($homeintdom) {
                   1632:             undef($setcookie);
                   1633:         }
1.1129    raeburn  1634:     }
1.1391    raeburn  1635:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1636: }
                   1637: 
1.1191    raeburn  1638: sub check_balancer_result {
                   1639:     my ($result,@hosts) = @_;
1.1391    raeburn  1640:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1641:     if (ref($result) eq 'HASH') {
                   1642:         if ($result->{'lonhost'} ne '') {
                   1643:             my $currbalancer = $result->{'lonhost'};
                   1644:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1645:                 $is_balancer = 1;
                   1646:                 $currtargets = $result->{'targets'};
                   1647:                 $currrules = $result->{'rules'};
                   1648:             }
1.1391    raeburn  1649:             $dom_balancers = $currbalancer;
1.1191    raeburn  1650:         } else {
1.1391    raeburn  1651:             if (keys(%{$result})) {
                   1652:                 foreach my $key (keys(%{$result})) {
                   1653:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1654:                         (ref($result->{$key}) eq 'HASH')) {
                   1655:                         $is_balancer = 1;
                   1656:                         $currrules = $result->{$key}{'rules'};
                   1657:                         $currtargets = $result->{$key}{'targets'};
                   1658:                         $setcookie = $result->{$key}{'cookie'};
                   1659:                         last;
                   1660:                     }
1.1191    raeburn  1661:                 }
1.1391    raeburn  1662:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1663:             }
                   1664:         }
                   1665:     }
1.1391    raeburn  1666:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1667: }
                   1668: 
1.1129    raeburn  1669: sub get_loadbalancer_targets {
                   1670:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1671:     my $offloadto;
1.1175    raeburn  1672:     if ($rule_in_effect eq 'none') {
                   1673:         return [$perlvar{'lonHostID'}];
                   1674:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1675:         $offloadto = $currtargets;
                   1676:     } else {
                   1677:         if ($rule_in_effect eq 'homeserver') {
                   1678:             my $homeserver = &homeserver($uname,$udom);
                   1679:             if ($homeserver ne 'no_host') {
                   1680:                 $offloadto = [$homeserver];
                   1681:             }
                   1682:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1683:             my %domconfig =
                   1684:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1685:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1686:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1687:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1688:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1689:                     }
                   1690:                 }
                   1691:             } else {
1.1178    raeburn  1692:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1693:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1694:                 if (&hostname($remotebalancer) ne '') {
                   1695:                     $offloadto = [$remotebalancer];
                   1696:                 }
                   1697:             }
                   1698:         } elsif (&hostname($rule_in_effect) ne '') {
                   1699:             $offloadto = [$rule_in_effect];
                   1700:         }
                   1701:     }
                   1702:     return $offloadto;
                   1703: }
                   1704: 
1.1127    raeburn  1705: sub internet_dom_servers {
                   1706:     my ($dom) = @_;
                   1707:     my (%uniqservers,%servers);
                   1708:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1709:     my @machinedoms = &machine_domains($primaryserver);
                   1710:     foreach my $mdom (@machinedoms) {
                   1711:         my %currservers = %servers;
                   1712:         my %server = &get_servers($mdom);
                   1713:         %servers = (%currservers,%server);
                   1714:     }
                   1715:     my %by_hostname;
                   1716:     foreach my $id (keys(%servers)) {
                   1717:         push(@{$by_hostname{$servers{$id}}},$id);
                   1718:     }
                   1719:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1720:         if (@{$by_hostname{$hostname}} > 1) {
                   1721:             my $match = 0;
                   1722:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1723:                 if (&host_domain($id) eq $dom) {
                   1724:                     $uniqservers{$id} = $hostname;
                   1725:                     $match = 1;
                   1726:                 }
                   1727:             }
                   1728:             unless ($match) {
                   1729:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1730:             }
                   1731:         } else {
                   1732:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1733:         }
                   1734:     }
                   1735:     return %uniqservers;
                   1736: }
                   1737: 
1.1347    raeburn  1738: sub trusted_domains {
                   1739:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1740:     my ($trusted,$untrusted);
1.1347    raeburn  1741:     if (&domain($calldom) eq '') {
1.1349    raeburn  1742:         return ($trusted,$untrusted);
1.1347    raeburn  1743:     }
1.1395  ! raeburn  1744:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1745:         return ($trusted,$untrusted);
1.1347    raeburn  1746:     }
                   1747:     my $callprimary = &domain($calldom,'primary');
                   1748:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1749:     if ($intcalldom eq '') {
1.1349    raeburn  1750:         return ($trusted,$untrusted);
1.1347    raeburn  1751:     }
                   1752: 
                   1753:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1754:     unless (defined($cached)) {
                   1755:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1756:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1757:         $trustconfig = $domconfig{'trust'};
                   1758:     }
                   1759:     if (ref($trustconfig)) {
                   1760:         my (%possexc,%possinc,@allexc,@allinc); 
                   1761:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1762:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1763:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1764:             }
                   1765:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395  ! raeburn  1766:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1767:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1768:             }
                   1769:         }
                   1770:         if (keys(%possexc)) {
                   1771:             if (keys(%possinc)) {
                   1772:                 foreach my $key (sort(keys(%possexc))) {
                   1773:                     next if ($key eq $intcalldom);
                   1774:                     unless ($possinc{$key}) {
                   1775:                         push(@allexc,$key);
                   1776:                     }
                   1777:                 }
                   1778:             } else {
                   1779:                 @allexc = sort(keys(%possexc));
                   1780:             }
                   1781:         }
                   1782:         if (keys(%possinc)) {
                   1783:             $possinc{$intcalldom} = 1;
                   1784:             @allinc = sort(keys(%possinc));
                   1785:         }
                   1786:         if ((@allexc > 0) || (@allinc > 0)) {
                   1787:             my %doms_by_intdom;
                   1788:             my %allintdoms = &all_host_intdom();
                   1789:             my %alldoms = &all_host_domain();
                   1790:             foreach my $key (%allintdoms) {
                   1791:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1792:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1793:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1794:                     }
                   1795:                 } else {
                   1796:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1797:                 }
                   1798:             }
                   1799:             foreach my $exc (@allexc) {
                   1800:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395  ! raeburn  1801:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1802:                 }
                   1803:             }
                   1804:             foreach my $inc (@allinc) {
                   1805:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395  ! raeburn  1806:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1807:                 }
                   1808:             }
                   1809:         }
                   1810:     }
1.1349    raeburn  1811:     return ($trusted,$untrusted);
1.1347    raeburn  1812: }
                   1813: 
                   1814: sub will_trust {
                   1815:     my ($cmdtype,$domain,$possdom) = @_;
                   1816:     return 1 if ($domain eq $possdom);
                   1817:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1818:     my $willtrust; 
                   1819:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1820:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1821:             $willtrust = 1;
                   1822:         }
                   1823:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1824:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1825:             $willtrust = 1;
                   1826:         }
                   1827:     } else {
                   1828:         $willtrust = 1;
                   1829:     }
                   1830:     return $willtrust;
                   1831: }
                   1832: 
1.1       albertel 1833: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1834: 
1.599     albertel 1835: my %homecache;
1.1       albertel 1836: sub homeserver {
1.230     stredwic 1837:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1838:     my $index="$uname:$udom";
1.426     albertel 1839: 
1.599     albertel 1840:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1841: 
                   1842:     my %servers = &get_servers($udom,'library');
                   1843:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1844:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1845: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1846: 
                   1847: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1848: 	if ($answer eq 'found') {
                   1849: 	    delete($badServerCache{$tryserver}); 
                   1850: 	    return $homecache{$index}=$tryserver;
                   1851: 	} elsif ($answer eq 'no_host') {
                   1852: 	    $badServerCache{$tryserver}=1;
                   1853: 	}
1.1       albertel 1854:     }    
                   1855:     return 'no_host';
1.70      www      1856: }
                   1857: 
1.1300    raeburn  1858: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1859: 
                   1860: sub idget {
1.1300    raeburn  1861:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1862:     my %returnhash=();
1.1300    raeburn  1863:     my @ids=(); 
                   1864:     if (ref($idsref) eq 'ARRAY') {
                   1865:         @ids = @{$idsref};
                   1866:     } else {
                   1867:         return %returnhash; 
                   1868:     }
                   1869:     if ($namespace eq '') {
                   1870:         $namespace = 'ids';
                   1871:     }
1.70      www      1872:     
1.841     albertel 1873:     my %servers = &get_servers($udom,'library');
                   1874:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1875: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1876: 	if ($namespace eq 'ids') {
                   1877: 	    $idlist=~tr/A-Z/a-z/;
                   1878: 	}
                   1879: 	my $reply;
                   1880: 	if ($namespace eq 'ids') {
                   1881: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1882: 	} else {
                   1883: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1884: 	}
1.841     albertel 1885: 	my @answer=();
                   1886: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1887: 	    @answer=split(/\&/,$reply);
                   1888: 	}                    ;
                   1889: 	my $i;
                   1890: 	for ($i=0;$i<=$#ids;$i++) {
                   1891: 	    if ($answer[$i]) {
1.1299    raeburn  1892: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1893: 	    }
1.841     albertel 1894: 	}
1.1300    raeburn  1895:     }
1.70      www      1896:     return %returnhash;
                   1897: }
                   1898: 
                   1899: # ------------------------------------- Find the IDs behind a list of usernames
                   1900: 
                   1901: sub idrget {
                   1902:     my ($udom,@unames)=@_;
                   1903:     my %returnhash=();
1.800     albertel 1904:     foreach my $uname (@unames) {
                   1905:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1906:     }
1.70      www      1907:     return %returnhash;
                   1908: }
                   1909: 
1.1300    raeburn  1910: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1911: 
                   1912: sub idput {
1.1300    raeburn  1913:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1914:     my %servers=();
1.1300    raeburn  1915:     my %ids=();
                   1916:     my %byid = ();
                   1917:     if (ref($idsref) eq 'HASH') {
                   1918:         %ids=%{$idsref};
                   1919:     }
                   1920:     if ($namespace eq '') {
                   1921:         $namespace = 'ids'; 
                   1922:     }
1.800     albertel 1923:     foreach my $uname (keys(%ids)) {
                   1924: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1925:         if ($uhom eq '') {
                   1926:             $uhom=&homeserver($uname,$udom);
                   1927:         }
1.70      www      1928:         if ($uhom ne 'no_host') {
1.800     albertel 1929:             my $esc_unam=&escape($uname);
1.1300    raeburn  1930:             if ($namespace eq 'ids') {
                   1931:                 my $id=&escape($ids{$uname});
                   1932:                 $id=~tr/A-Z/a-z/;
                   1933:                 my $esc_unam=&escape($uname);
                   1934:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1935:             } else {
1.1300    raeburn  1936:                 my @currids = split(/,/,$ids{$uname});
                   1937:                 foreach my $id (@currids) {
                   1938:                     $byid{$uhom}{$id} .= $uname.',';
                   1939:                 }
                   1940:             }
                   1941:         }
                   1942:     }
                   1943:     if ($namespace eq 'clickers') {
                   1944:         foreach my $server (keys(%byid)) {
                   1945:             if (ref($byid{$server}) eq 'HASH') {
                   1946:                 foreach my $id (keys(%{$byid{$server}})) {
                   1947:                     $byid{$server} =~ s/,$//;
                   1948:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1949:                 }
1.70      www      1950:             }
                   1951:         }
1.191     harris41 1952:     }
1.800     albertel 1953:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1954:         $servers{$server} =~ s/\&$//;
                   1955:         if ($namespace eq 'ids') {     
                   1956:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1957:         } else {
                   1958:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1959:         }
1.191     harris41 1960:     }
1.344     www      1961: }
                   1962: 
1.1300    raeburn  1963: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1964: 
                   1965: sub iddel {
1.1300    raeburn  1966:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1967:     my %result=();
1.1300    raeburn  1968:     my %ids=();
                   1969:     my %byid = ();
                   1970:     if (ref($idshashref) eq 'HASH') {
                   1971:         %ids=%{$idshashref};
                   1972:     } else {
1.1231    raeburn  1973:         return %result;
                   1974:     }
1.1300    raeburn  1975:     if ($namespace eq '') {
                   1976:         $namespace = 'ids';
                   1977:     }
1.1231    raeburn  1978:     my %servers=();
1.1300    raeburn  1979:     while (my ($id,$unamestr) = each(%ids)) {
                   1980:         if ($namespace eq 'ids') {
                   1981:             my $uhom = $uhome;
                   1982:             if ($uhom eq '') { 
                   1983:                 $uhom=&homeserver($unamestr,$udom);
                   1984:             }
                   1985:             if ($uhom ne 'no_host') {
                   1986:                 $servers{$uhom}.='&'.&escape($id);
                   1987:             }
                   1988:          } else {
                   1989:             my @curritems = split(/,/,$ids{$id});
                   1990:             foreach my $uname (@curritems) {
                   1991:                 my $uhom = $uhome;
                   1992:                 if ($uhom eq '') {
                   1993:                     $uhom=&homeserver($uname,$udom);
                   1994:                 }
                   1995:                 if ($uhom ne 'no_host') { 
                   1996:                     $byid{$uhom}{$id} .= $uname.',';
                   1997:                 }
                   1998:             }
1.1231    raeburn  1999:         }
1.1300    raeburn  2000:     }
                   2001:     if ($namespace eq 'clickers') {
                   2002:         foreach my $server (keys(%byid)) {
                   2003:             if (ref($byid{$server}) eq 'HASH') {
                   2004:                 foreach my $id (keys(%{$byid{$server}})) {
                   2005:                     $byid{$server}{$id} =~ s/,$//;
                   2006:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2007:                 }
1.1231    raeburn  2008:             }
                   2009:         }
                   2010:     }
                   2011:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2012:         $servers{$server} =~ s/\&$//;
                   2013:         if ($namespace eq 'ids') {
                   2014:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2015:         } elsif ($namespace eq 'clickers') {
                   2016:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2017:         }
1.1231    raeburn  2018:     }
                   2019:     return %result;
                   2020: }
                   2021: 
1.1300    raeburn  2022: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2023: 
                   2024: sub updateclickers {
                   2025:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2026:     my %clickers;
                   2027:     if (ref($idshashref) eq 'HASH') {
                   2028:         %clickers=%{$idshashref};
                   2029:     } else {
                   2030:         return;
                   2031:     }
                   2032:     my $items='';
                   2033:     foreach my $item (keys(%clickers)) {
                   2034:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2035:     }
                   2036:     $items=~s/\&$//;
                   2037:     my $request = "updateclickers:$udom:$action:$items";
                   2038:     if ($critical) {
                   2039:         return &critical($request,$uhome);
                   2040:     } else {
                   2041:         return &reply($request,$uhome);
                   2042:     }
                   2043: }
                   2044: 
1.1023    raeburn  2045: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2046: sub dump_dom {
1.1165    droeschl 2047:     my ($namespace, $udom, $regexp) = @_;
                   2048: 
                   2049:     $udom ||= $env{'user.domain'};
                   2050: 
                   2051:     return () unless $udom;
                   2052: 
                   2053:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2054: }
                   2055: 
1.1023    raeburn  2056: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2057: 
                   2058: sub get_dom {
1.860     raeburn  2059:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2060:     return if ($udom eq 'public');
1.806     raeburn  2061:     my $items='';
                   2062:     foreach my $item (@$storearr) {
                   2063:         $items.=&escape($item).'&';
                   2064:     }
                   2065:     $items=~s/\&$//;
1.860     raeburn  2066:     if (!$udom) {
                   2067:         $udom=$env{'user.domain'};
1.1267    raeburn  2068:         return if ($udom eq 'public');
1.860     raeburn  2069:         if (defined(&domain($udom,'primary'))) {
                   2070:             $uhome=&domain($udom,'primary');
                   2071:         } else {
1.874     albertel 2072:             undef($uhome);
1.860     raeburn  2073:         }
                   2074:     } else {
                   2075:         if (!$uhome) {
                   2076:             if (defined(&domain($udom,'primary'))) {
                   2077:                 $uhome=&domain($udom,'primary');
                   2078:             }
                   2079:         }
                   2080:     }
                   2081:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2082:         my $rep;
                   2083:         if ($namespace =~ /^enc/) {
                   2084:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2085:         } else {
                   2086:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2087:         }
1.866     raeburn  2088:         my %returnhash;
1.875     albertel 2089:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2090:             return %returnhash;
                   2091:         }
1.806     raeburn  2092:         my @pairs=split(/\&/,$rep);
                   2093:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2094:             return @pairs;
                   2095:         }
                   2096:         my $i=0;
                   2097:         foreach my $item (@$storearr) {
                   2098:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2099:             $i++;
                   2100:         }
                   2101:         return %returnhash;
                   2102:     } else {
1.880     banghart 2103:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2104:     }
                   2105: }
                   2106: 
                   2107: # -------------------------------------------- put items in domain db files 
                   2108: 
                   2109: sub put_dom {
1.860     raeburn  2110:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2111:     if (!$udom) {
                   2112:         $udom=$env{'user.domain'};
                   2113:         if (defined(&domain($udom,'primary'))) {
                   2114:             $uhome=&domain($udom,'primary');
                   2115:         } else {
1.874     albertel 2116:             undef($uhome);
1.860     raeburn  2117:         }
                   2118:     } else {
                   2119:         if (!$uhome) {
                   2120:             if (defined(&domain($udom,'primary'))) {
                   2121:                 $uhome=&domain($udom,'primary');
                   2122:             }
                   2123:         }
                   2124:     } 
                   2125:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2126:         my $items='';
                   2127:         foreach my $item (keys(%$storehash)) {
                   2128:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2129:         }
                   2130:         $items=~s/\&$//;
1.1344    raeburn  2131:         if ($namespace =~ /^enc/) {
                   2132:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2133:         } else {
                   2134:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2135:         }
1.806     raeburn  2136:     } else {
1.860     raeburn  2137:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2138:     }
                   2139: }
                   2140: 
1.1023    raeburn  2141: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2142: sub newput_dom {
1.1023    raeburn  2143:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2144:     my $result;
                   2145:     if (!$udom) {
                   2146:         $udom=$env{'user.domain'};
                   2147:     }
1.1023    raeburn  2148:     if ($udom) {
                   2149:         my $uname = &get_domainconfiguser($udom);
                   2150:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2151:     }
                   2152:     return $result;
                   2153: }
                   2154: 
1.1023    raeburn  2155: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2156: sub del_dom {
1.1023    raeburn  2157:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2158:     if (ref($storearr) eq 'ARRAY') {
                   2159:         if (!$udom) {
                   2160:             $udom=$env{'user.domain'};
                   2161:         }
1.1023    raeburn  2162:         if ($udom) {
                   2163:             my $uname = &get_domainconfiguser($udom); 
                   2164:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2165:         }
                   2166:     }
                   2167: }
                   2168: 
1.1023    raeburn  2169: # ----------------------------------construct domainconfig user for a domain 
                   2170: sub get_domainconfiguser {
                   2171:     my ($udom) = @_;
                   2172:     return $udom.'-domainconfig';
                   2173: }
                   2174: 
1.837     raeburn  2175: sub retrieve_inst_usertypes {
                   2176:     my ($udom) = @_;
                   2177:     my (%returnhash,@order);
1.989     raeburn  2178:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2179:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2180:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2181:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2182:     } else {
                   2183:         if (defined(&domain($udom,'primary'))) {
                   2184:             my $uhome=&domain($udom,'primary');
                   2185:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2186:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2187:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2188:                 return (\%returnhash,\@order);
                   2189:             }
                   2190:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2191:             my @pairs=split(/\&/,$hashitems);
                   2192:             foreach my $item (@pairs) {
                   2193:                 my ($key,$value)=split(/=/,$item,2);
                   2194:                 $key = &unescape($key);
                   2195:                 next if ($key =~ /^error: 2 /);
                   2196:                 $returnhash{$key}=&thaw_unescape($value);
                   2197:             }
                   2198:             my @esc_order = split(/\&/,$orderitems);
                   2199:             foreach my $item (@esc_order) {
                   2200:                 push(@order,&unescape($item));
                   2201:             }
                   2202:         } else {
1.1256    raeburn  2203:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2204:         }
1.1256    raeburn  2205:         return (\%returnhash,\@order);
1.837     raeburn  2206:     }
                   2207: }
                   2208: 
1.868     raeburn  2209: sub is_domainimage {
                   2210:     my ($url) = @_;
1.1306    raeburn  2211:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2212:         if (&domain($1) ne '') {
                   2213:             return '1';
                   2214:         }
                   2215:     }
                   2216:     return;
                   2217: }
                   2218: 
1.899     raeburn  2219: sub inst_directory_query {
                   2220:     my ($srch) = @_;
                   2221:     my $udom = $srch->{'srchdomain'};
                   2222:     my %results;
                   2223:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2224:     my $outcome;
1.899     raeburn  2225:     if ($homeserver ne '') {
1.1357    raeburn  2226:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2227:             if ($srch->{'srchby'} eq 'email') {
                   2228:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2229:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2230:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2231:                     (($major == 2) && ($minor < 12))) {
                   2232:                     return;
                   2233:                 }
                   2234:             }
                   2235:         }
1.904     albertel 2236: 	my $queryid=&reply("querysend:instdirsearch:".
                   2237: 			   &escape($srch->{'srchby'}).':'.
                   2238: 			   &escape($srch->{'srchterm'}).':'.
                   2239: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2240: 	my $host=&hostname($homeserver);
                   2241: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2242: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2243: 	    return;
                   2244: 	}
                   2245: 	my $response = &get_query_reply($queryid);
                   2246: 	my $maxtries = 5;
                   2247: 	my $tries = 1;
                   2248: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2249: 	    $response = &get_query_reply($queryid);
                   2250: 	    $tries ++;
                   2251: 	}
                   2252: 
                   2253:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2254:             if ($response eq 'unavailable') {
                   2255:                 $outcome = $response;
                   2256:             } else {
                   2257:                 $outcome = 'ok';
                   2258:                 my @matches = split(/\n/,$response);
                   2259:                 foreach my $match (@matches) {
                   2260:                     my ($key,$value) = split(/=/,$match);
                   2261:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2262:                 }
1.899     raeburn  2263:             }
                   2264:         }
                   2265:     }
1.909     raeburn  2266:     return ($outcome,%results);
1.899     raeburn  2267: }
                   2268: 
                   2269: sub usersearch {
                   2270:     my ($srch) = @_;
                   2271:     my $dom = $srch->{'srchdomain'};
                   2272:     my %results;
                   2273:     my %libserv = &all_library();
                   2274:     my $query = 'usersearch';
                   2275:     foreach my $tryserver (keys(%libserv)) {
                   2276:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2277:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2278:                 if ($srch->{'srchby'} eq 'email') {
                   2279:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2280:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2281:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2282:                              (($major == 2) && ($minor < 12)));
                   2283:                 }
                   2284:             }
1.899     raeburn  2285:             my $host=&hostname($tryserver);
                   2286:             my $queryid=
1.911     raeburn  2287:                 &reply("querysend:".&escape($query).':'.
                   2288:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2289:                        &escape($srch->{'srchtype'}).':'.
                   2290:                        &escape($srch->{'srchterm'}),$tryserver);
                   2291:             if ($queryid !~/^\Q$host\E\_/) {
                   2292:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2293:                 next;
1.899     raeburn  2294:             }
                   2295:             my $reply = &get_query_reply($queryid);
                   2296:             my $maxtries = 1;
                   2297:             my $tries = 1;
                   2298:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2299:                 $reply = &get_query_reply($queryid);
                   2300:                 $tries ++;
                   2301:             }
                   2302:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2303:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2304:             } else {
1.911     raeburn  2305:                 my @matches;
                   2306:                 if ($reply =~ /\n/) {
                   2307:                     @matches = split(/\n/,$reply);
                   2308:                 } else {
                   2309:                     @matches = split(/\&/,$reply);
                   2310:                 }
1.899     raeburn  2311:                 foreach my $match (@matches) {
                   2312:                     my ($uname,$udom,%userhash);
1.911     raeburn  2313:                     foreach my $entry (split(/:/,$match)) {
                   2314:                         my ($key,$value) =
                   2315:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2316:                         $userhash{$key} = $value;
                   2317:                         if ($key eq 'username') {
                   2318:                             $uname = $value;
                   2319:                         } elsif ($key eq 'domain') {
                   2320:                             $udom = $value;
1.911     raeburn  2321:                         }
1.899     raeburn  2322:                     }
                   2323:                     $results{$uname.':'.$udom} = \%userhash;
                   2324:                 }
                   2325:             }
                   2326:         }
                   2327:     }
                   2328:     return %results;
                   2329: }
                   2330: 
1.912     raeburn  2331: sub get_instuser {
                   2332:     my ($udom,$uname,$id) = @_;
                   2333:     my $homeserver = &domain($udom,'primary');
                   2334:     my ($outcome,%results);
                   2335:     if ($homeserver ne '') {
                   2336:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2337:                            &escape($id).':'.&escape($udom),$homeserver);
                   2338:         my $host=&hostname($homeserver);
                   2339:         if ($queryid !~/^\Q$host\E\_/) {
                   2340:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2341:             return;
                   2342:         }
                   2343:         my $response = &get_query_reply($queryid);
                   2344:         my $maxtries = 5;
                   2345:         my $tries = 1;
                   2346:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2347:             $response = &get_query_reply($queryid);
                   2348:             $tries ++;
                   2349:         }
                   2350:         if (!&error($response) && $response ne 'refused') {
                   2351:             if ($response eq 'unavailable') {
                   2352:                 $outcome = $response;
                   2353:             } else {
                   2354:                 $outcome = 'ok';
                   2355:                 my @matches = split(/\n/,$response);
                   2356:                 foreach my $match (@matches) {
                   2357:                     my ($key,$value) = split(/=/,$match);
                   2358:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2359:                 }
                   2360:             }
                   2361:         }
                   2362:     }
                   2363:     my %userinfo;
                   2364:     if (ref($results{$uname}) eq 'HASH') {
                   2365:         %userinfo = %{$results{$uname}};
                   2366:     } 
                   2367:     return ($outcome,%userinfo);
                   2368: }
                   2369: 
1.1290    raeburn  2370: sub get_multiple_instusers {
                   2371:     my ($udom,$users,$caller) = @_;
                   2372:     my ($outcome,$results);
                   2373:     if (ref($users) eq 'HASH') {
                   2374:         my $count = keys(%{$users}); 
                   2375:         my $requested = &freeze_escape($users);
                   2376:         my $homeserver = &domain($udom,'primary');
                   2377:         if ($homeserver ne '') {
                   2378:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2379:             my $host=&hostname($homeserver);
                   2380:             if ($queryid !~/^\Q$host\E\_/) {
                   2381:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2382:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2383:                 return ($outcome,$results);
                   2384:             }
                   2385:             my $response = &get_query_reply($queryid);
                   2386:             my $maxtries = 5;
                   2387:             if ($count > 100) {
                   2388:                 $maxtries = 1+int($count/20);
                   2389:             }
                   2390:             my $tries = 1;
                   2391:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2392:                 $response = &get_query_reply($queryid);
                   2393:                 $tries ++;
                   2394:             }
                   2395:             if ($response eq '') {
                   2396:                 $results = {};
                   2397:                 foreach my $key (keys(%{$users})) {
                   2398:                     my ($uname,$id);
                   2399:                     if ($caller eq 'id') {
                   2400:                         $id = $key;
                   2401:                     } else {
                   2402:                         $uname = $key;
                   2403:                     }
                   2404:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2405:                     $outcome = $resp;
1.1290    raeburn  2406:                     if ($resp eq 'ok') {
                   2407:                         %{$results} = (%{$results}, %info);
                   2408:                     } else {
                   2409:                         last;
                   2410:                     }
                   2411:                 }
                   2412:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2413:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2414:                     $outcome = $response;
                   2415:                 } else {
1.1291    raeburn  2416:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2417:                     if ($outcome eq 'ok') {
                   2418:                         $results = &thaw_unescape($userdata); 
                   2419:                     }
                   2420:                 }
                   2421:             }
                   2422:         }
                   2423:     }
                   2424:     return ($outcome,$results);
                   2425: }
                   2426: 
1.912     raeburn  2427: sub inst_rulecheck {
1.923     raeburn  2428:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2429:     my %returnhash;
                   2430:     if ($udom ne '') {
                   2431:         if (ref($rules) eq 'ARRAY') {
                   2432:             @{$rules} = map {&escape($_);} (@{$rules});
                   2433:             my $rulestr = join(':',@{$rules});
                   2434:             my $homeserver=&domain($udom,'primary');
                   2435:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2436:                 my $response;
                   2437:                 if ($item eq 'username') {                
                   2438:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2439:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2440:                                               $homeserver));
1.923     raeburn  2441:                 } elsif ($item eq 'id') {
                   2442:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2443:                                               ':'.&escape($id).':'.$rulestr,
                   2444:                                               $homeserver));
1.945     raeburn  2445:                 } elsif ($item eq 'selfcreate') {
                   2446:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2447:                                                &escape($udom).':'.&escape($uname).
                   2448:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2449:                 }
1.912     raeburn  2450:                 if ($response ne 'refused') {
                   2451:                     my @pairs=split(/\&/,$response);
                   2452:                     foreach my $item (@pairs) {
                   2453:                         my ($key,$value)=split(/=/,$item,2);
                   2454:                         $key = &unescape($key);
                   2455:                         next if ($key =~ /^error: 2 /);
                   2456:                         $returnhash{$key}=&thaw_unescape($value);
                   2457:                     }
                   2458:                 }
                   2459:             }
                   2460:         }
                   2461:     }
                   2462:     return %returnhash;
                   2463: }
                   2464: 
                   2465: sub inst_userrules {
1.923     raeburn  2466:     my ($udom,$check) = @_;
1.912     raeburn  2467:     my (%ruleshash,@ruleorder);
                   2468:     if ($udom ne '') {
                   2469:         my $homeserver=&domain($udom,'primary');
                   2470:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2471:             my $response;
                   2472:             if ($check eq 'id') {
                   2473:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2474:                                  $homeserver);
1.943     raeburn  2475:             } elsif ($check eq 'email') {
                   2476:                 $response=&reply('instemailrules:'.&escape($udom),
                   2477:                                  $homeserver);
1.923     raeburn  2478:             } else {
                   2479:                 $response=&reply('instuserrules:'.&escape($udom),
                   2480:                                  $homeserver);
                   2481:             }
1.912     raeburn  2482:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2483:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2484:                 ($response ne 'no_such_host')) {
                   2485:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2486:                 my @pairs=split(/\&/,$hashitems);
                   2487:                 foreach my $item (@pairs) {
                   2488:                     my ($key,$value)=split(/=/,$item,2);
                   2489:                     $key = &unescape($key);
                   2490:                     next if ($key =~ /^error: 2 /);
                   2491:                     $ruleshash{$key}=&thaw_unescape($value);
                   2492:                 }
                   2493:                 my @esc_order = split(/\&/,$orderitems);
                   2494:                 foreach my $item (@esc_order) {
                   2495:                     push(@ruleorder,&unescape($item));
                   2496:                 }
                   2497:             }
                   2498:         }
                   2499:     }
                   2500:     return (\%ruleshash,\@ruleorder);
                   2501: }
                   2502: 
1.976     raeburn  2503: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2504: 
                   2505: sub get_domain_defaults {
1.1240    raeburn  2506:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2507:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2508:     my $cachetime = 60*60*24;
1.1240    raeburn  2509:     unless ($ignore_cache) {
                   2510:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2511:         if (defined($cached)) {
                   2512:             if (ref($result) eq 'HASH') {
                   2513:                 return %{$result};
                   2514:             }
1.943     raeburn  2515:         }
                   2516:     }
                   2517:     my %domdefaults;
                   2518:     my %domconfig =
1.989     raeburn  2519:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2520:                                   'requestcourses','inststatus',
1.1183    raeburn  2521:                                   'coursedefaults','usersessions',
1.1258    raeburn  2522:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2523:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2524:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2525:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2526:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2527:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2528:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2529:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2530:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2531:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2532:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2533:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2534:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2535:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2536:     } else {
                   2537:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2538:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2539:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2540:     }
1.976     raeburn  2541:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2542:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2543:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2544:         } else {
                   2545:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2546:         }
1.1177    raeburn  2547:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2548:         foreach my $item (@usertools) {
                   2549:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2550:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2551:             }
                   2552:         }
1.1229    raeburn  2553:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2554:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2555:         }
1.976     raeburn  2556:     }
1.985     raeburn  2557:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2558:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2559:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2560:         }
                   2561:     }
1.1183    raeburn  2562:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2563:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2564:     }
1.989     raeburn  2565:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2566:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2567:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2568:         }
                   2569:     }
1.1047    raeburn  2570:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2571:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2572:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2573:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2574:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2575:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2576:         }
1.1254    raeburn  2577:         foreach my $type (@coursetypes) {
                   2578:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2579:                 unless ($type eq 'community') {
                   2580:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2581:                 }
                   2582:             }
                   2583:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2584:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2585:             }
1.1277    raeburn  2586:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2587:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2588:                     $domdefaults{$type.'postsubtimeout'} = 
                   2589:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2590:                 }
                   2591:             }
1.1230    raeburn  2592:         }
1.1286    raeburn  2593:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2594:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2595:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2596:                 if (@clonecodes) {
                   2597:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2598:                 }
                   2599:             }
                   2600:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2601:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2602:         }
1.1356    raeburn  2603:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2604:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2605:         } 
1.1047    raeburn  2606:     }
1.1073    raeburn  2607:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2608:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2609:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2610:         }
                   2611:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2612:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2613:         }
1.1279    raeburn  2614:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2615:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2616:         }
1.1073    raeburn  2617:     }
1.1254    raeburn  2618:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2619:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2620:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2621:                             'approval','limit');
                   2622:             foreach my $type (@coursetypes) {
                   2623:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2624:                     my @mgrdc = ();
                   2625:                     foreach my $item (@settings) {
                   2626:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2627:                             push(@mgrdc,$item);
                   2628:                         }
                   2629:                     }
                   2630:                     if (@mgrdc) {
                   2631:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2632:                     }
                   2633:                 }
                   2634:             }
                   2635:         }
                   2636:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2637:             foreach my $type (@coursetypes) {
                   2638:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2639:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2640:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2641:                     }
                   2642:                 }
                   2643:             }
                   2644:         }
                   2645:     }
1.1258    raeburn  2646:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2647:         $domdefaults{'catauth'} = 'std';
                   2648:         $domdefaults{'catunauth'} = 'std';
                   2649:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2650:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2651:         }
                   2652:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2653:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2654:         }
                   2655:     }
1.1315    raeburn  2656:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2657:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2658:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2659:         }
1.1338    raeburn  2660:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2661:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2662:         }
                   2663:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2664:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2665:         }
                   2666:     }
1.1320    raeburn  2667:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2668:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2669:         foreach my $prefix (@prefixes) {
                   2670:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2671:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2672:             }
                   2673:         }
                   2674:     }
1.1314    raeburn  2675:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2676:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2677:     }
1.1332    raeburn  2678:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2679:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2680:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2681:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2682:         }
                   2683:     }
1.1219    raeburn  2684:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2685:     return %domdefaults;
                   2686: }
                   2687: 
1.1311    raeburn  2688: sub course_portal_url {
                   2689:     my ($cnum,$cdom) = @_;
                   2690:     my $chome = &homeserver($cnum,$cdom);
                   2691:     my $hostname = &hostname($chome);
                   2692:     my $protocol = $protocol{$chome};
                   2693:     $protocol = 'http' if ($protocol ne 'https');
                   2694:     my %domdefaults = &get_domain_defaults($cdom);
                   2695:     my $firsturl;
                   2696:     if ($domdefaults{'portal_def'}) {
                   2697:         $firsturl = $domdefaults{'portal_def'};
                   2698:     } else {
                   2699:         $firsturl = $protocol.'://'.$hostname;
                   2700:     }
                   2701:     return $firsturl;
                   2702: }
                   2703: 
1.344     www      2704: # --------------------------------------------------- Assign a key to a student
                   2705: 
                   2706: sub assign_access_key {
1.364     www      2707: #
                   2708: # a valid key looks like uname:udom#comments
                   2709: # comments are being appended
                   2710: #
1.498     www      2711:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2712:     $kdom=
1.620     albertel 2713:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2714:     $knum=
1.620     albertel 2715:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2716:     $cdom=
1.620     albertel 2717:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2718:     $cnum=
1.620     albertel 2719:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2720:     $udom=$env{'user.name'} unless (defined($udom));
                   2721:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2722:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2723:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2724:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2725:                                                   # assigned to this person
                   2726:                                                   # - this should not happen,
1.345     www      2727:                                                   # unless something went wrong
                   2728:                                                   # the first time around
                   2729: # ready to assign
1.364     www      2730:         $logentry=$1.'; '.$logentry;
1.496     www      2731:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2732:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2733: # key now belongs to user
1.346     www      2734: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2735:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2736:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2737:                 return 'ok';
                   2738:             } else {
                   2739:                 return 
                   2740:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2741: 	    }
                   2742:         } else {
                   2743:             return 'error: Could not assign key, try again later.';
                   2744:         }
1.364     www      2745:     } elsif (!$existing{$ckey}) {
1.345     www      2746: # the key does not exist
                   2747: 	return 'error: The key does not exist';
                   2748:     } else {
                   2749: # the key is somebody else's
                   2750: 	return 'error: The key is already in use';
                   2751:     }
1.344     www      2752: }
                   2753: 
1.364     www      2754: # ------------------------------------------ put an additional comment on a key
                   2755: 
                   2756: sub comment_access_key {
                   2757: #
                   2758: # a valid key looks like uname:udom#comments
                   2759: # comments are being appended
                   2760: #
                   2761:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2762:     $cdom=
1.620     albertel 2763:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2764:     $cnum=
1.620     albertel 2765:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2766:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2767:     if ($existing{$ckey}) {
                   2768:         $existing{$ckey}.='; '.$logentry;
                   2769: # ready to assign
1.367     www      2770:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2771:                                                  $cdom,$cnum) eq 'ok') {
                   2772: 	    return 'ok';
                   2773:         } else {
                   2774: 	    return 'error: Count not store comment.';
                   2775:         }
                   2776:     } else {
                   2777: # the key does not exist
                   2778: 	return 'error: The key does not exist';
                   2779:     }
                   2780: }
                   2781: 
1.344     www      2782: # ------------------------------------------------------ Generate a set of keys
                   2783: 
                   2784: sub generate_access_keys {
1.364     www      2785:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2786:     $cdom=
1.620     albertel 2787:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2788:     $cnum=
1.620     albertel 2789:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2790:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2791:     unless (($cdom) && ($cnum)) { return 0; }
                   2792:     if ($number>10000) { return 0; }
                   2793:     sleep(2); # make sure don't get same seed twice
                   2794:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2795:     my $total=0;
                   2796:     for (my $i=1;$i<=$number;$i++) {
                   2797:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2798:                   sprintf("%lx",int(100000*rand)).'-'.
                   2799:                   sprintf("%lx",int(100000*rand));
                   2800:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2801:        $newkey=~s/0/h/g; # and also 0 and O
                   2802:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2803:        if ($existing{$newkey}) {
                   2804:            $i--;
                   2805:        } else {
1.364     www      2806: 	  if (&put('accesskeys',
                   2807:               { $newkey => '# generated '.localtime().
1.620     albertel 2808:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2809:                            '; '.$logentry },
                   2810: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2811:               $total++;
                   2812: 	  }
                   2813:        }
                   2814:     }
1.620     albertel 2815:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2816:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2817:     return $total;
                   2818: }
                   2819: 
                   2820: # ------------------------------------------------------- Validate an accesskey
                   2821: 
                   2822: sub validate_access_key {
                   2823:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2824:     $cdom=
1.620     albertel 2825:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2826:     $cnum=
1.620     albertel 2827:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2828:     $udom=$env{'user.domain'} unless (defined($udom));
                   2829:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2830:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2831:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2832: }
                   2833: 
                   2834: # ------------------------------------- Find the section of student in a course
1.652     albertel 2835: sub devalidate_getsection_cache {
                   2836:     my ($udom,$unam,$courseid)=@_;
                   2837:     my $hashid="$udom:$unam:$courseid";
                   2838:     &devalidate_cache_new('getsection',$hashid);
                   2839: }
1.298     matthew  2840: 
1.815     albertel 2841: sub courseid_to_courseurl {
                   2842:     my ($courseid) = @_;
                   2843:     #already url style courseid
                   2844:     return $courseid if ($courseid =~ m{^/});
                   2845: 
                   2846:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2847: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2848: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2849: 	return "/$cdom/$cnum";
                   2850:     }
                   2851: 
                   2852:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2853:     if (exists($courseinfo{'num'})) {
                   2854: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2855:     }
                   2856: 
                   2857:     return undef;
                   2858: }
                   2859: 
1.298     matthew  2860: sub getsection {
                   2861:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2862:     my $cachetime=1800;
1.551     albertel 2863: 
                   2864:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2865:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2866:     if (defined($cached)) { return $result; }
                   2867: 
1.298     matthew  2868:     my %Pending; 
                   2869:     my %Expired;
                   2870:     #
                   2871:     # Each role can either have not started yet (pending), be active, 
                   2872:     #    or have expired.
                   2873:     #
                   2874:     # If there is an active role, we are done.
                   2875:     #
                   2876:     # If there is more than one role which has not started yet, 
                   2877:     #     choose the one which will start sooner
                   2878:     # If there is one role which has not started yet, return it.
                   2879:     #
                   2880:     # If there is more than one expired role, choose the one which ended last.
                   2881:     # If there is a role which has expired, return it.
                   2882:     #
1.815     albertel 2883:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2884:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2885:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2886:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2887:         my $section=$1;
                   2888:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2889:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2890:         my $now=time;
1.548     albertel 2891:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2892:             $Expired{$end}=$section;
                   2893:             next;
                   2894:         }
1.548     albertel 2895:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2896:             $Pending{$start}=$section;
                   2897:             next;
                   2898:         }
1.599     albertel 2899:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2900:     }
                   2901:     #
                   2902:     # Presumedly there will be few matching roles from the above
                   2903:     # loop and the sorting time will be negligible.
                   2904:     if (scalar(keys(%Pending))) {
                   2905:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2906:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2907:     } 
                   2908:     if (scalar(keys(%Expired))) {
                   2909:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2910:         my $time = pop(@sorted);
1.599     albertel 2911:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2912:     }
1.599     albertel 2913:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2914: }
1.70      www      2915: 
1.599     albertel 2916: sub save_cache {
                   2917:     &purge_remembered();
1.722     albertel 2918:     #&Apache::loncommon::validate_page();
1.620     albertel 2919:     undef(%env);
1.780     albertel 2920:     undef($env_loaded);
1.599     albertel 2921: }
1.452     albertel 2922: 
1.599     albertel 2923: my $to_remember=-1;
                   2924: my %remembered;
                   2925: my %accessed;
                   2926: my $kicks=0;
                   2927: my $hits=0;
1.849     albertel 2928: sub make_key {
                   2929:     my ($name,$id) = @_;
1.872     albertel 2930:     if (length($id) > 65 
                   2931: 	&& length(&escape($id)) > 200) {
                   2932: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2933:     }
1.849     albertel 2934:     return &escape($name.':'.$id);
                   2935: }
                   2936: 
1.599     albertel 2937: sub devalidate_cache_new {
                   2938:     my ($name,$id,$debug) = @_;
                   2939:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2940:     my $remembered_id=$name.':'.$id;
1.849     albertel 2941:     $id=&make_key($name,$id);
1.599     albertel 2942:     $memcache->delete($id);
1.1319    damieng  2943:     delete($remembered{$remembered_id});
                   2944:     delete($accessed{$remembered_id});
1.599     albertel 2945: }
                   2946: 
                   2947: sub is_cached_new {
                   2948:     my ($name,$id,$debug) = @_;
1.1319    damieng  2949:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2950:     if (exists($remembered{$remembered_id})) {
                   2951: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2952: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2953: 	$hits++;
1.1319    damieng  2954: 	return ($remembered{$remembered_id},1);
1.599     albertel 2955:     }
1.1319    damieng  2956:     $id=&make_key($name,$id);
1.599     albertel 2957:     my $value = $memcache->get($id);
                   2958:     if (!(defined($value))) {
                   2959: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2960: 	return (undef,undef);
1.416     albertel 2961:     }
1.599     albertel 2962:     if ($value eq '__undef__') {
                   2963: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2964: 	$value=undef;
                   2965:     }
1.1319    damieng  2966:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2967:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2968:     return ($value,1);
                   2969: }
                   2970: 
                   2971: sub do_cache_new {
                   2972:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2973:     my $remembered_id=$name.':'.$id;
1.849     albertel 2974:     $id=&make_key($name,$id);
1.599     albertel 2975:     my $setvalue=$value;
                   2976:     if (!defined($setvalue)) {
                   2977: 	$setvalue='__undef__';
                   2978:     }
1.623     albertel 2979:     if (!defined($time) ) {
                   2980: 	$time=600;
                   2981:     }
1.599     albertel 2982:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2983:     my $result = $memcache->set($id,$setvalue,$time);
                   2984:     if (! $result) {
1.872     albertel 2985: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2986: 	$memcache->disconnect_all();
1.872     albertel 2987:     }
1.600     albertel 2988:     # need to make a copy of $value
1.1319    damieng  2989:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2990:     return $value;
                   2991: }
                   2992: 
                   2993: sub make_room {
1.1319    damieng  2994:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2995: 
1.1319    damieng  2996:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2997:                                     : $value;
1.599     albertel 2998:     if ($to_remember<0) { return; }
1.1319    damieng  2999:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3000:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3001:     my $to_kick;
                   3002:     my $max_time=0;
                   3003:     foreach my $other (keys(%accessed)) {
                   3004: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3005: 	    $to_kick=$other;
                   3006: 	    $max_time=&tv_interval($accessed{$other});
                   3007: 	}
                   3008:     }
                   3009:     delete($remembered{$to_kick});
                   3010:     delete($accessed{$to_kick});
                   3011:     $kicks++;
                   3012:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3013:     return;
                   3014: }
                   3015: 
1.599     albertel 3016: sub purge_remembered {
1.604     albertel 3017:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3018:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3019:     undef(%remembered);
                   3020:     undef(%accessed);
1.428     albertel 3021: }
1.70      www      3022: # ------------------------------------- Read an entry from a user's environment
                   3023: 
                   3024: sub userenvironment {
                   3025:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3026:     my $items;
                   3027:     foreach my $item (@what) {
                   3028:         $items.=&escape($item).'&';
                   3029:     }
                   3030:     $items=~s/\&$//;
1.70      www      3031:     my %returnhash=();
1.1009    raeburn  3032:     my $uhome = &homeserver($unam,$udom);
                   3033:     unless ($uhome eq 'no_host') {
                   3034:         my @answer=split(/\&/, 
                   3035:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3036:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3037:             return %returnhash;
                   3038:         }
1.1009    raeburn  3039:         my $i;
                   3040:         for ($i=0;$i<=$#what;$i++) {
                   3041: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3042:         }
1.70      www      3043:     }
                   3044:     return %returnhash;
1.1       albertel 3045: }
                   3046: 
1.617     albertel 3047: # ---------------------------------------------------------- Get a studentphoto
                   3048: sub studentphoto {
                   3049:     my ($udom,$unam,$ext) = @_;
                   3050:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3051:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3052:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3053:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3054:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3055:             } else {
                   3056:                 my ($result,$perm_reqd)=
1.707     albertel 3057: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3058:                 if ($result eq 'ok') {
                   3059:                     if (!($perm_reqd eq 'yes')) {
                   3060:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3061:                     }
                   3062:                 }
                   3063:             }
                   3064:         }
                   3065:     } else {
                   3066:         my ($result,$perm_reqd) = 
1.707     albertel 3067: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3068:         if ($result eq 'ok') {
                   3069:             if (!($perm_reqd eq 'yes')) {
                   3070:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3071:             }
                   3072:         }
                   3073:     }
                   3074:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3075: }
                   3076: 
                   3077: sub retrievestudentphoto {
                   3078:     my ($udom,$unam,$ext,$type) = @_;
                   3079:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3080:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3081:     if ($ret eq 'ok') {
                   3082:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3083:         if ($type eq 'thumbnail') {
                   3084:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3085:         }
                   3086:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3087:         return $tokenurl;
                   3088:     } else {
                   3089:         if ($type eq 'thumbnail') {
                   3090:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3091:         } else { 
                   3092:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3093:         }
1.617     albertel 3094:     }
                   3095: }
                   3096: 
1.263     www      3097: # -------------------------------------------------------------------- New chat
                   3098: 
                   3099: sub chatsend {
1.724     raeburn  3100:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3101:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3102:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3103:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3104:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3105: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3106: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3107: }
                   3108: 
                   3109: # ------------------------------------------ Find current version of a resource
                   3110: 
                   3111: sub getversion {
                   3112:     my $fname=&clutter(shift);
1.1189    raeburn  3113:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3114:     return &currentversion(&filelocation('',$fname));
                   3115: }
                   3116: 
                   3117: sub currentversion {
                   3118:     my $fname=shift;
                   3119:     my $author=$fname;
                   3120:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3121:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3122:     my $home=&homeserver($uname,$udom);
1.292     www      3123:     if ($home eq 'no_host') { 
                   3124:         return -1; 
                   3125:     }
1.1112    www      3126:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3127:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3128: 	return -1;
                   3129:     }
1.1112    www      3130:     return $answer;
1.263     www      3131: }
                   3132: 
1.1111    www      3133: #
                   3134: # Return special version number of resource if set by override, empty otherwise
                   3135: #
                   3136: sub usedversion {
                   3137:     my $fname=shift;
                   3138:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3139:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3140:     if ($urlversion) { return $urlversion; }
                   3141:     return '';
                   3142: }
                   3143: 
1.1       albertel 3144: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3145: 
1.1       albertel 3146: sub subscribe {
                   3147:     my $fname=shift;
1.761     raeburn  3148:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3149:     $fname=~s/[\n\r]//g;
1.1       albertel 3150:     my $author=$fname;
                   3151:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3152:     my ($udom,$uname)=split(/\//,$author);
                   3153:     my $home=homeserver($uname,$udom);
1.335     albertel 3154:     if ($home eq 'no_host') {
                   3155:         return 'not_found';
1.1       albertel 3156:     }
                   3157:     my $answer=reply("sub:$fname",$home);
1.64      www      3158:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3159: 	$answer.=' by '.$home;
                   3160:     }
1.1       albertel 3161:     return $answer;
                   3162: }
                   3163:     
1.8       www      3164: # -------------------------------------------------------------- Replicate file
                   3165: 
                   3166: sub repcopy {
                   3167:     my $filename=shift;
1.23      www      3168:     $filename=~s/\/+/\//g;
1.1142    raeburn  3169:     my $londocroot = $perlvar{'lonDocRoot'};
                   3170:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3171:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3172:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3173: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3174: 	return &repcopy_userfile($filename);
                   3175:     }
1.532     albertel 3176:     $filename=~s/[\n\r]//g;
1.8       www      3177:     my $transname="$filename.in.transfer";
1.828     www      3178: # FIXME: this should flock
1.607     raeburn  3179:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3180:     my $remoteurl=subscribe($filename);
1.64      www      3181:     if ($remoteurl =~ /^con_lost by/) {
                   3182: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3183:            return 'unavailable';
1.8       www      3184:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3185: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3186: 	   return 'not_found';
1.64      www      3187:     } elsif ($remoteurl =~ /^rejected by/) {
                   3188: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3189:            return 'forbidden';
1.20      www      3190:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3191:            return 'ok';
1.8       www      3192:     } else {
1.290     www      3193:         my $author=$filename;
                   3194:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3195:         my ($udom,$uname)=split(/\//,$author);
                   3196:         my $home=homeserver($uname,$udom);
                   3197:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3198:            my @parts=split(/\//,$filename);
                   3199:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3200:            if ($path ne "$londocroot/res") {
1.8       www      3201:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3202: 	       return 'bad_request';
1.8       www      3203:            }
                   3204:            my $count;
                   3205:            for ($count=5;$count<$#parts;$count++) {
                   3206:                $path.="/$parts[$count]";
                   3207:                if ((-e $path)!=1) {
                   3208: 		   mkdir($path,0777);
                   3209:                }
                   3210:            }
                   3211:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3212:            my $response;
                   3213:            if ($remoteurl =~ m{/raw/}) {
                   3214:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3215:            } else {
                   3216:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3217:            }
1.8       www      3218:            if ($response->is_error()) {
                   3219: 	       unlink($transname);
                   3220:                my $message=$response->status_line;
1.672     albertel 3221:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3222:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3223:                return 'unavailable';
1.8       www      3224:            } else {
1.16      www      3225: 	       if ($remoteurl!~/\.meta$/) {
                   3226:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3227:                   my $mresponse;
                   3228:                   if ($remoteurl =~ m{/raw/}) {
                   3229:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3230:                   } else {
                   3231:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3232:                   }
1.16      www      3233:                   if ($mresponse->is_error()) {
                   3234: 		      unlink($filename.'.meta');
                   3235:                       &logthis(
1.672     albertel 3236:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3237:                   }
                   3238: 	       }
1.8       www      3239:                rename($transname,$filename);
1.607     raeburn  3240:                return 'ok';
1.8       www      3241:            }
1.290     www      3242:        }
1.8       www      3243:     }
1.330     www      3244: }
                   3245: 
                   3246: # ------------------------------------------------ Get server side include body
                   3247: sub ssi_body {
1.381     albertel 3248:     my ($filelink,%form)=@_;
1.606     matthew  3249:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3250:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3251:     }
1.953     www      3252:     my $output='';
                   3253:     my $response;
1.980     raeburn  3254:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3255:        ($output,$response)=&externalssi($filelink);
1.953     www      3256:     } else {
1.1004    droeschl 3257:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3258:        $filelink .= 'inhibitmenu=yes';
1.953     www      3259:        ($output,$response)=&ssi($filelink,%form);
                   3260:     }
1.778     albertel 3261:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3262:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3263:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3264:     if (wantarray) {
                   3265:         return ($output, $response);
                   3266:     } else {
                   3267:         return $output;
                   3268:     }
1.8       www      3269: }
                   3270: 
1.15      www      3271: # --------------------------------------------------------- Server Side Include
                   3272: 
1.782     albertel 3273: sub absolute_url {
                   3274:     my ($host_name) = @_;
                   3275:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3276:     if ($host_name eq '') {
                   3277: 	$host_name = $ENV{'SERVER_NAME'};
                   3278:     }
                   3279:     return $protocol.$host_name;
                   3280: }
                   3281: 
1.942     foxr     3282: #
                   3283: #   Server side include.
                   3284: # Parameters:
                   3285: #  fn     Possibly encrypted resource name/id.
                   3286: #  form   Hash that describes how the rendering should be done
                   3287: #         and other things.
1.944     foxr     3288: # Returns:
1.950     raeburn  3289: #   Scalar context: The content of the response.
                   3290: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3291: #     
1.15      www      3292: sub ssi {
                   3293: 
1.944     foxr     3294:     my ($fn,%form)=@_;
1.23      www      3295:     my $request;
1.711     albertel 3296: 
                   3297:     $form{'no_update_last_known'}=1;
1.895     albertel 3298:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3299:     if (%form) {
1.782     albertel 3300:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3301:       $request->content(join('&',map { 
                   3302:             my $name = escape($_);
                   3303:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3304:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3305:             : &escape($form{$_}) );    
                   3306:         } keys(%form)));
1.23      www      3307:     } else {
1.782     albertel 3308:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3309:     }
                   3310: 
1.15      www      3311:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3312:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3313:     my $islocal;
                   3314:     if (($env{'request.course.id'}) &&
                   3315:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3316:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3317:         ($form{'grade_symb'} ne '') &&
                   3318:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3319:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3320:         $islocal = 1;
                   3321:     }
1.1384    raeburn  3322:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3323:                                                 '','','',$islocal);
1.1182    foxr     3324: 
1.944     foxr     3325:     if (wantarray) {
1.1345    raeburn  3326: 	return ($response->content, $response);
1.944     foxr     3327:     } else {
1.1345    raeburn  3328: 	return $response->content;
1.942     foxr     3329:     }
1.324     www      3330: }
                   3331: 
                   3332: sub externalssi {
                   3333:     my ($url)=@_;
                   3334:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3335:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3336:     if (wantarray) {
                   3337:         return ($response->content, $response);
                   3338:     } else {
                   3339:         return $response->content;
                   3340:     }
1.15      www      3341: }
1.254     www      3342: 
1.1354    raeburn  3343: 
                   3344: # If the local copy of a replicated resource is outdated, trigger a  
                   3345: # connection from the homeserver to flush the delayed queue. If no update 
                   3346: # happens, remove local copies of outdated resource (and corresponding
                   3347: # metadata file).
                   3348: 
1.1352    raeburn  3349: sub remove_stale_resfile {
                   3350:     my ($url) = @_;
1.1354    raeburn  3351:     my $removed;
1.1352    raeburn  3352:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3353:         my $audom = $1;
                   3354:         my $auname = $2;
1.1353    raeburn  3355:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3356:             my $homeserver = &homeserver($auname,$audom);
                   3357:             unless (($homeserver eq 'no_host') ||
                   3358:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3359:                 my $fname = &filelocation('',$url);
                   3360:                 if (-e $fname) {
                   3361:                     my $protocol = $protocol{$homeserver};
                   3362:                     $protocol = 'http' if ($protocol ne 'https');
                   3363:                     my $hostname = &hostname($homeserver);
                   3364:                     if ($hostname) {
                   3365:                         my $uri = &declutter($url);
                   3366:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3367:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3368:                         if ($response->is_success()) {
                   3369:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3370:                             my $locmodtime = (stat($fname))[9];
                   3371:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3372:                                 my $stale;
                   3373:                                 my $answer = &reply('pong',$homeserver);
                   3374:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3375:                                     sleep(0.2);
                   3376:                                     $locmodtime = (stat($fname))[9];
                   3377:                                     if ($locmodtime < $remmodtime) {
                   3378:                                         my $posstransfer = $fname.'.in.transfer';
                   3379:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3380:                                             $removed = 1;
                   3381:                                         } else {
                   3382:                                             $stale = 1;
                   3383:                                         }
                   3384:                                     } else {
                   3385:                                         $removed = 1;
                   3386:                                     }
                   3387:                                 } else {
                   3388:                                     $stale = 1;
                   3389:                                 }
                   3390:                                 if ($stale) {
                   3391:                                     unlink($fname);
                   3392:                                     if ($uri!~/\.meta$/) {
                   3393:                                         unlink($fname.'.meta');
                   3394:                                     }
                   3395:                                     &reply("unsub:$fname",$homeserver);
                   3396:                                     $removed = 1;
1.1352    raeburn  3397:                                 }
                   3398:                             }
                   3399:                         }
                   3400:                     }
                   3401:                 }
                   3402:             }
                   3403:         }
                   3404:     }
1.1354    raeburn  3405:     return $removed;
1.1352    raeburn  3406: }
                   3407: 
1.492     albertel 3408: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3409: 
                   3410: sub allowuploaded {
                   3411:     my ($srcurl,$url)=@_;
                   3412:     $url=&clutter(&declutter($url));
                   3413:     my $dir=$url;
                   3414:     $dir=~s/\/[^\/]+$//;
                   3415:     my %httpref=();
                   3416:     my $httpurl=&hreflocation('',$url);
                   3417:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3418:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3419: }
1.477     raeburn  3420: 
1.1193    raeburn  3421: #
                   3422: # Determine if the current user should be able to edit a particular resource,
                   3423: # when viewing in course context.
                   3424: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3425: #     Functions.
                   3426: # (b) When displaying folder contents in course editor, used to determine if
                   3427: #     "Edit" link will be displayed alongside resource.
                   3428: #
1.1196    raeburn  3429: #  input: six args -- filename (decluttered), course number, course domain,
                   3430: #                   url, symb (if registered) and group (if this is a group
                   3431: #                   item -- e.g., bulletin board, group page etc.).
                   3432: #  output: array of five scalars -- 
1.1193    raeburn  3433: #          $cfile -- url for file editing if editable on current server
                   3434: #          $home -- homeserver of resource (i.e., for author if published,
                   3435: #                                           or course if uploaded.).
                   3436: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3437: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3438: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3439: #
                   3440: 
                   3441: sub can_edit_resource {
1.1194    raeburn  3442:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3443:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3444: #
                   3445: # For aboutme pages user can only edit his/her own.
                   3446: #
1.1199    raeburn  3447:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3448:         my ($sdom,$sname) = ($1,$2);
                   3449:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3450:             $home = $env{'user.home'};
                   3451:             $cfile = $resurl;
                   3452:             if ($env{'form.forceedit'}) {
                   3453:                 $forceview = 1;
                   3454:             } else {
                   3455:                 $forceedit = 1;
                   3456:             }
                   3457:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3458:         } else {
                   3459:             return;
                   3460:         }
                   3461:     }
                   3462: 
                   3463:     if ($env{'request.course.id'}) {
                   3464:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3465:         if ($group ne '') {
                   3466: # if this is a group homepage or group bulletin board, check group privs
                   3467:             my $allowed = 0;
1.1197    raeburn  3468:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3469:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3470:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3471:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3472:                     $allowed = 1;
                   3473:                 }
1.1197    raeburn  3474:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3475:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3476:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3477:                     $allowed = 1;
                   3478:                 }
                   3479:             }
                   3480:             if ($allowed) {
                   3481:                 $home=&homeserver($cnum,$cdom);
                   3482:                 if ($env{'form.forceedit'}) {
                   3483:                     $forceview = 1;
                   3484:                 } else {
                   3485:                     $forceedit = 1;
                   3486:                 }
                   3487:                 $cfile = $resurl;
                   3488:             } else {
                   3489:                 return;
                   3490:             }
                   3491:         } else {
1.1208    raeburn  3492:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3493:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3494:                     return;
                   3495:                 }
                   3496:             } elsif (!$crsedit) {
1.1194    raeburn  3497: #
                   3498: # No edit allowed where CC has switched to student role.
                   3499: #
                   3500:                 return;
                   3501:             }
                   3502:         }
                   3503:     }
                   3504: 
1.1193    raeburn  3505:     if ($file ne '') {
                   3506:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3507:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3508:                 $uploaded = 1;
                   3509:                 $incourse = 1;
1.1193    raeburn  3510:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3511:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3512:                     if ($env{'form.forceedit'}) {
                   3513:                         $forceview = 1;
                   3514:                     } else {
                   3515:                         $forceedit = 1;
                   3516:                     }
1.1194    raeburn  3517:                 }
                   3518:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3519:                 $incourse = 1;
                   3520:                 if ($env{'form.forceedit'}) {
                   3521:                     $forceview = 1;
                   3522:                 } else {
                   3523:                     $forceedit = 1;
                   3524:                 }
                   3525:                 $cfile = $resurl;
                   3526:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3527:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3528:                     $incourse = 1;
                   3529:                     if ($env{'form.forceedit'}) {
                   3530:                         $forceview = 1;
                   3531:                     } else {
                   3532:                         $forceedit = 1;
                   3533:                     }
                   3534:                     $cfile = $resurl;
1.1199    raeburn  3535:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3536:                     $incourse = 1;
                   3537:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3538:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3539:                     $incourse = 1;
1.1199    raeburn  3540:                     if ($env{'form.forceedit'}) {
                   3541:                         $forceview = 1;
                   3542:                     } else {
                   3543:                         $forceedit = 1;
                   3544:                     }
                   3545:                     $cfile = $resurl;
1.1343    raeburn  3546:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3547:                     $incourse = 1;
                   3548:                     if ($env{'form.forceedit'}) {
                   3549:                         $forceview = 1;
                   3550:                     } else {
                   3551:                         $forceedit = 1;
                   3552:                     }
                   3553:                     $cfile = $resurl;
1.1208    raeburn  3554:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3555:                     $incourse = 1;
                   3556:                     if ($env{'form.forceedit'}) {
                   3557:                         $forceview = 1;
                   3558:                     } else {
                   3559:                         $forceedit = 1;
                   3560:                     }
                   3561:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3562:                 }
                   3563:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3564:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3565:                 if (&is_on_map($template)) { 
                   3566:                     $incourse = 1;
                   3567:                     $forceview = 1;
                   3568:                     $cfile = $template;
1.1193    raeburn  3569:                 }
1.1199    raeburn  3570:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3571:                     $incourse = 1;
                   3572:                     if ($env{'form.forceedit'}) {
                   3573:                         $forceview = 1;
                   3574:                     } else {
                   3575:                         $forceedit = 1;
                   3576:                     }
                   3577:                     $cfile = $resurl;
1.1343    raeburn  3578:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3579:                 $incourse = 1;
                   3580:                 if ($env{'form.forceedit'}) {
                   3581:                     $forceview = 1;
                   3582:                 } else {
                   3583:                     $forceedit = 1;
                   3584:                 }
                   3585:                 $cfile = $resurl;
1.1199    raeburn  3586:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3587:                 $incourse = 1;
                   3588:                 $forceview = 1;
                   3589:                 if ($symb) {
                   3590:                     my ($map,$id,$res)=&decode_symb($symb);
                   3591:                     $env{'request.symb'} = $symb;
                   3592:                     $cfile = &clutter($res);
                   3593:                 } else {
                   3594:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3595:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3596:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3597:                         $cfile = '/adm/wrapper'.$escfile;
                   3598:                     } else {
                   3599:                         $escfile =~ s{^http://}{};
                   3600:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3601:                     }
1.1199    raeburn  3602:                 }
1.1234    raeburn  3603:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3604:                 if ($env{'form.forceedit'}) {
                   3605:                     $forceview = 1;
                   3606:                 } else {
                   3607:                     $forceedit = 1;
                   3608:                 }
                   3609:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3610:             }
                   3611:         }
1.1194    raeburn  3612:         if ($uploaded || $incourse) {
                   3613:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3614:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3615:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3616:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3617:             # Check that the user has permission to edit this resource
                   3618:             my $setpriv = 1;
                   3619:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3620:             if (defined($cfudom)) {
                   3621:                 $home=&homeserver($cfuname,$cfudom);
                   3622:                 $cfile=$file;
                   3623:             }
                   3624:         }
1.1194    raeburn  3625:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3626:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3627:             my @ids=&current_machine_ids();
                   3628:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3629:                 $switchserver=1;
                   3630:             }
                   3631:         }
                   3632:     }
1.1194    raeburn  3633:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3634: }
                   3635: 
                   3636: sub is_course_upload {
                   3637:     my ($file,$cnum,$cdom) = @_;
                   3638:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3639:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3640:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3641:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3642:         return 1;
                   3643:     }
                   3644:     return;
                   3645: }
                   3646: 
1.1194    raeburn  3647: sub in_course {
1.1195    raeburn  3648:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3649:     if ($hideprivileged) {
                   3650:         my $skipuser;
1.1219    raeburn  3651:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3652:         my @possdoms = ($cdom);  
                   3653:         if ($coursehash{'checkforpriv'}) { 
                   3654:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3655:         }
                   3656:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3657:             $skipuser = 1;
                   3658:             if ($coursehash{'nothideprivileged'}) {
                   3659:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3660:                     my $user;
                   3661:                     if ($item =~ /:/) {
                   3662:                         $user = $item;
                   3663:                     } else {
                   3664:                         $user = join(':',split(/[\@]/,$item));
                   3665:                     }
                   3666:                     if ($user eq $uname.':'.$udom) {
                   3667:                         undef($skipuser);
                   3668:                         last;
                   3669:                     }
                   3670:                 }
                   3671:             }
                   3672:             if ($skipuser) {
                   3673:                 return 0;
                   3674:             }
                   3675:         }
                   3676:     }
1.1194    raeburn  3677:     $type ||= 'any';
                   3678:     if (!defined($cdom) || !defined($cnum)) {
                   3679:         my $cid  = $env{'request.course.id'};
                   3680:         $cdom = $env{'course.'.$cid.'.domain'};
                   3681:         $cnum = $env{'course.'.$cid.'.num'};
                   3682:     }
                   3683:     my $typesref;
1.1195    raeburn  3684:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3685:         $typesref = ['active','previous','future'];
                   3686:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3687:         $typesref = [$type];
                   3688:     }
                   3689:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3690:                               $typesref,undef,[$cdom]);
                   3691:     my ($tmp) = keys(%roles);
                   3692:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3693:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3694:     if (@course_roles > 0) {
                   3695:         return 1;
                   3696:     }
                   3697:     return 0;
                   3698: }
                   3699: 
1.478     albertel 3700: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3701: # input: action, courseID, current domain, intended
1.637     raeburn  3702: #        path to file, source of file, instruction to parse file for objects,
                   3703: #        ref to hash for embedded objects,
                   3704: #        ref to hash for codebase of java objects.
1.1095    raeburn  3705: #        reference to scalar to accommodate mime type determined
                   3706: #          from File::MMagic if $parser = parse.
1.637     raeburn  3707: #
1.485     raeburn  3708: # output: url to file (if action was uploaddoc), 
                   3709: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3710: #
1.478     albertel 3711: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3712: # course.
1.477     raeburn  3713: #
1.478     albertel 3714: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3715: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3716: #          course's home server.
1.477     raeburn  3717: #
1.478     albertel 3718: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3719: #          be copied from $source (current location) to 
                   3720: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3721: #         and will then be copied to
                   3722: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3723: #         course's home server.
1.485     raeburn  3724: #
1.481     raeburn  3725: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3726: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3727: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3728: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3729: #         in course's home server.
1.637     raeburn  3730: #
1.477     raeburn  3731: 
                   3732: sub process_coursefile {
1.1095    raeburn  3733:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3734:         $mimetype)=@_;
1.477     raeburn  3735:     my $fetchresult;
1.638     albertel 3736:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3737:     if ($action eq 'propagate') {
1.638     albertel 3738:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3739: 			     $home);
1.481     raeburn  3740:     } else {
1.477     raeburn  3741:         my $fpath = '';
                   3742:         my $fname = $file;
1.478     albertel 3743:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3744:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3745:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3746:         if ($action eq 'copy') {
                   3747:             if ($source eq '') {
                   3748:                 $fetchresult = 'no source file';
                   3749:                 return $fetchresult;
                   3750:             } else {
                   3751:                 my $destination = $filepath.'/'.$fname;
                   3752:                 rename($source,$destination);
                   3753:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3754:                                  $home);
1.481     raeburn  3755:             }
                   3756:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3757:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3758:             print $fh $env{'form.'.$source};
1.481     raeburn  3759:             close($fh);
1.637     raeburn  3760:             if ($parser eq 'parse') {
1.1024    raeburn  3761:                 my $mm = new File::MMagic;
1.1095    raeburn  3762:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3763:                 if ($type eq 'text/html') {
1.1024    raeburn  3764:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3765:                     unless ($parse_result eq 'ok') {
                   3766:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3767:                     }
1.637     raeburn  3768:                 }
1.1095    raeburn  3769:                 if (ref($mimetype)) {
                   3770:                     $$mimetype = $type;
                   3771:                 } 
1.637     raeburn  3772:             }
1.477     raeburn  3773:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3774:                                  $home);
1.481     raeburn  3775:             if ($fetchresult eq 'ok') {
                   3776:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3777:             } else {
                   3778:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3779:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3780:                 return '/adm/notfound.html';
                   3781:             }
1.477     raeburn  3782:         }
                   3783:     }
1.485     raeburn  3784:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3785:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3786:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3787:     }
                   3788:     return $fetchresult;
                   3789: }
                   3790: 
1.637     raeburn  3791: sub build_filepath {
                   3792:     my ($fpath) = @_;
                   3793:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3794:     unless ($fpath eq '') {
                   3795:         my @parts=split('/',$fpath);
                   3796:         foreach my $part (@parts) {
                   3797:             $filepath.= '/'.$part;
                   3798:             if ((-e $filepath)!=1) {
                   3799:                 mkdir($filepath,0777);
                   3800:             }
                   3801:         }
                   3802:     }
                   3803:     return $filepath;
                   3804: }
                   3805: 
                   3806: sub store_edited_file {
1.638     albertel 3807:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3808:     my $file = $primary_url;
                   3809:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3810:     my $fpath = '';
                   3811:     my $fname = $file;
                   3812:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3813:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3814:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3815:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3816:     print $fh $content;
                   3817:     close($fh);
1.638     albertel 3818:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3819:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3820: 			  $home);
1.637     raeburn  3821:     if ($$fetchresult eq 'ok') {
                   3822:         return '/uploaded/'.$fpath.'/'.$fname;
                   3823:     } else {
1.638     albertel 3824:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3825: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3826:         return '/adm/notfound.html';
                   3827:     }
                   3828: }
                   3829: 
1.531     albertel 3830: sub clean_filename {
1.831     albertel 3831:     my ($fname,$args)=@_;
1.315     www      3832: # Replace Windows backslashes by forward slashes
1.257     www      3833:     $fname=~s/\\/\//g;
1.831     albertel 3834:     if (!$args->{'keep_path'}) {
                   3835:         # Get rid of everything but the actual filename
                   3836: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3837:     }
1.315     www      3838: # Replace spaces by underscores
                   3839:     $fname=~s/\s+/\_/g;
                   3840: # Replace all other weird characters by nothing
1.831     albertel 3841:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3842: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3843: # numbers
                   3844:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3845:     return $fname;
                   3846: }
1.1051    raeburn  3847: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3848: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3849: # image with the same aspect ratio as the original, but with dimensions which do 
                   3850: # not exceed $resizewidth and $resizeheight.
                   3851:  
1.984     neumanie 3852: sub resizeImage {
1.1051    raeburn  3853:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3854:     my $ima = Image::Magick->new;
                   3855:     my $resized;
                   3856:     if (-e $img_path) {
                   3857:         $ima->Read($img_path);
                   3858:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3859:             my $width = $ima->Get('width');
                   3860:             my $height = $ima->Get('height');
                   3861:             if ($width > $resizewidth) {
                   3862: 	        my $factor = $width/$resizewidth;
                   3863:                 my $newheight = $height/$factor;
                   3864:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3865:                 $resized = 1;
                   3866:             }
                   3867:         }
                   3868:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3869:             my $width = $ima->Get('width');
                   3870:             my $height = $ima->Get('height');
                   3871:             if ($height > $resizeheight) {
                   3872:                 my $factor = $height/$resizeheight;
                   3873:                 my $newwidth = $width/$factor;
                   3874:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3875:                 $resized = 1;
                   3876:             }
                   3877:         }
                   3878:         if ($resized) {
                   3879:             $ima->Write($img_path);
                   3880:         }
                   3881:     }
                   3882:     return;
1.977     amueller 3883: }
                   3884: 
1.608     albertel 3885: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3886: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3887: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3888: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3889: #                                    canceloverwrite, or ''. 
                   3890: #                   if 'coursedoc': upload to the current course
                   3891: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3892: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3893: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3894: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3895: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3896: #        $allfiles - reference to hash for embedded objects
                   3897: #        $codebase - reference to hash for codebase of java objects
                   3898: #        $desuname - username for permanent storage of uploaded file
                   3899: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3900: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3901: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3902: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3903: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3904: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3905: #                    from File::MMagic.
1.858     raeburn  3906: # 
1.686     albertel 3907: # output: url of file in userspace, or error: <message> 
                   3908: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3909: 
1.531     albertel 3910: sub userfileupload {
1.1090    raeburn  3911:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3912:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3913:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3914:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3915:     $fname=&clean_filename($fname);
1.1090    raeburn  3916:     # See if there is anything left
1.257     www      3917:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3918:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3919:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3920:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3921:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3922:         my $now = time;
1.1090    raeburn  3923:         my $filepath;
1.1095    raeburn  3924:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3925:              $filepath = 'tmp/helprequests/'.$now;
                   3926:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3927:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3928:                          '_'.$env{'user.domain'}.'/pending';
                   3929:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3930:             my ($docuname,$docudom);
1.1350    raeburn  3931:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3932:                 $docudom = $destudom;
                   3933:             } else {
                   3934:                 $docudom = $env{'user.domain'};
                   3935:             }
1.1350    raeburn  3936:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3937:                 $docuname = $destuname;
                   3938:             } else {
                   3939:                 $docuname = $env{'user.name'};
                   3940:             }
                   3941:             if (exists($env{'form.group'})) {
                   3942:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3943:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3944:             }
                   3945:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3946:             if ($context eq 'canceloverwrite') {
                   3947:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3948:                 if (-e  $tempfile) {
                   3949:                     my @info = stat($tempfile);
                   3950:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3951:                         unlink($tempfile);
                   3952:                     }
                   3953:                 }
                   3954:                 return;
1.523     raeburn  3955:             }
                   3956:         }
1.1090    raeburn  3957:         # Create the directory if not present
1.741     raeburn  3958:         my @parts=split(/\//,$filepath);
                   3959:         my $fullpath = $perlvar{'lonDaemons'};
                   3960:         for (my $i=0;$i<@parts;$i++) {
                   3961:             $fullpath .= '/'.$parts[$i];
                   3962:             if ((-e $fullpath)!=1) {
                   3963:                 mkdir($fullpath,0777);
                   3964:             }
                   3965:         }
1.1359    raeburn  3966:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3967:         print $fh $env{'form.'.$formname};
                   3968:         close($fh);
1.1090    raeburn  3969:         if ($context eq 'existingfile') {
                   3970:             my @info = stat($fullpath.'/'.$fname);
                   3971:             return ($fullpath.'/'.$fname,$info[9]);
                   3972:         } else {
                   3973:             return $fullpath.'/'.$fname;
                   3974:         }
1.523     raeburn  3975:     }
1.995     raeburn  3976:     if ($subdir eq 'scantron') {
                   3977:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3978:     } else {
1.995     raeburn  3979:         $fname="$subdir/$fname";
                   3980:     }
1.1090    raeburn  3981:     if ($context eq 'coursedoc') {
1.638     albertel 3982: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3983: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3984:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3985:             return &finishuserfileupload($docuname,$docudom,
                   3986: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3987: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3988:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3989:         } else {
1.1218    raeburn  3990:             if ($env{'form.folder'}) {
                   3991:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3992:             }
1.638     albertel 3993:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3994: 				       $fname,$formname,$parser,
1.1095    raeburn  3995: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3996:         }
1.719     banghart 3997:     } elsif (defined($destuname)) {
                   3998:         my $docuname=$destuname;
                   3999:         my $docudom=$destudom;
1.860     raeburn  4000: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4001: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4002:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4003:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4004:     } else {
1.638     albertel 4005:         my $docuname=$env{'user.name'};
                   4006:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4007:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4008:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4009:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4010:         }
1.860     raeburn  4011: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4012: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4013:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4014:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4015:     }
1.271     www      4016: }
                   4017: 
                   4018: sub finishuserfileupload {
1.860     raeburn  4019:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4020:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4021:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4022:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4023:   
1.860     raeburn  4024:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4025:     $file=$fname;
                   4026:     if ($fname=~m|/|) {
                   4027:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4028: 	$path.=$fnamepath.'/';
                   4029:     }
1.259     www      4030:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4031:     my $count;
                   4032:     for ($count=4;$count<=$#parts;$count++) {
                   4033:         $filepath.="/$parts[$count]";
                   4034:         if ((-e $filepath)!=1) {
                   4035: 	    mkdir($filepath,0777);
                   4036:         }
                   4037:     }
1.984     neumanie 4038: 
1.258     www      4039: # Save the file
                   4040:     {
1.1359    raeburn  4041: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4042: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4043: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4044: 	    return '/adm/notfound.html';
                   4045: 	}
1.1090    raeburn  4046:         if ($context eq 'overwrite') {
1.1117    foxr     4047:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4048:             my $target = $filepath.'/'.$file;
                   4049:             if (-e $source) {
                   4050:                 my @info = stat($source);
                   4051:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4052:                     unless (&File::Copy::move($source,$target)) {
                   4053:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4054:                         return "Moving from $source failed";
                   4055:                     }
                   4056:                 } else {
                   4057:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4058:                 }
                   4059:             } else {
                   4060:                 return "Temporary file: $source missing";
                   4061:             }
                   4062:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4063: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4064: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4065: 	    return '/adm/notfound.html';
                   4066: 	}
1.570     albertel 4067: 	close(FH);
1.1051    raeburn  4068:         if ($resizewidth && $resizeheight) {
                   4069:             my $mm = new File::MMagic;
                   4070:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4071:             if ($mime_type =~ m{^image/}) {
                   4072: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4073:             }  
1.977     amueller 4074: 	}
1.258     www      4075:     }
1.1152    raeburn  4076:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4077:         if (ref($mimetype)) {
                   4078:             if ($$mimetype eq '') {
                   4079:                 my $mm = new File::MMagic;
                   4080:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4081:                 $$mimetype = $type;
                   4082:             }
                   4083:         }
                   4084:     }
1.637     raeburn  4085:     if ($parser eq 'parse') {
1.1152    raeburn  4086:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4087:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4088:                                                        $allfiles,$codebase);
                   4089:             unless ($parse_result eq 'ok') {
                   4090:                 &logthis('Failed to parse '.$filepath.$file.
                   4091: 	   	         ' for embedded media: '.$parse_result); 
                   4092:             }
1.637     raeburn  4093:         }
                   4094:     }
1.860     raeburn  4095:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4096:         my $input = $filepath.'/'.$file;
                   4097:         my $output = $filepath.'/'.'tn-'.$file;
                   4098:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4099:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4100:         system({$args[0]} @args);
1.860     raeburn  4101:         if (-e $filepath.'/'.'tn-'.$file) {
                   4102:             $fetchthumb  = 1; 
                   4103:         }
                   4104:     }
1.858     raeburn  4105:  
1.259     www      4106: # Notify homeserver to grep it
                   4107: #
1.984     neumanie 4108:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4109:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4110:     if ($fetchresult eq 'ok') {
1.860     raeburn  4111:         if ($fetchthumb) {
                   4112:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4113:             if ($thumbresult ne 'ok') {
                   4114:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4115:                          $docuhome.': '.$thumbresult);
                   4116:             }
                   4117:         }
1.259     www      4118: #
1.258     www      4119: # Return the URL to it
1.494     albertel 4120:         return '/uploaded/'.$path.$file;
1.263     www      4121:     } else {
1.494     albertel 4122:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4123: 		 ': '.$fetchresult);
1.263     www      4124:         return '/adm/notfound.html';
1.858     raeburn  4125:     }
1.493     albertel 4126: }
                   4127: 
1.637     raeburn  4128: sub extract_embedded_items {
1.961     raeburn  4129:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4130:     my @state = ();
1.1164    raeburn  4131:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4132:     my %javafiles = (
                   4133:                       codebase => '',
                   4134:                       code => '',
                   4135:                       archive => ''
                   4136:                     );
                   4137:     my %mediafiles = (
                   4138:                       src => '',
                   4139:                       movie => '',
                   4140:                      );
1.648     raeburn  4141:     my $p;
                   4142:     if ($content) {
                   4143:         $p = HTML::LCParser->new($content);
                   4144:     } else {
1.961     raeburn  4145:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4146:     }
1.641     albertel 4147:     while (my $t=$p->get_token()) {
1.640     albertel 4148: 	if ($t->[0] eq 'S') {
                   4149: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4150: 	    push(@state, $tagname);
1.648     raeburn  4151:             if (lc($tagname) eq 'allow') {
                   4152:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4153:             }
1.640     albertel 4154: 	    if (lc($tagname) eq 'img') {
                   4155: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4156: 	    }
1.886     albertel 4157: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4158:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4159:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4160:                 }
1.886     albertel 4161: 	    }
1.645     raeburn  4162:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4163:                 my $src;
1.645     raeburn  4164:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4165:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4166:                 } else {
1.1164    raeburn  4167:                     if ($attr->{'src'} ne '') {
                   4168:                         $src = $attr->{'src'};
                   4169:                         &add_filetype($allfiles,$src,'src');
                   4170:                     }
                   4171:                 }
                   4172:                 my $text = $p->get_trimmed_text();
                   4173:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4174:                     my @swfargs = split(/,/,$1);
                   4175:                     foreach my $item (@swfargs) {
                   4176:                         $item =~ s/["']//g;
                   4177:                         $item =~ s/^\s+//;
                   4178:                         $item =~ s/\s+$//;
                   4179:                     }
                   4180:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4181:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4182:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4183:                         } else {
                   4184:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4185:                         }
                   4186:                     }
1.645     raeburn  4187:                 }
                   4188:             }
                   4189:             if (lc($tagname) eq 'link') {
                   4190:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4191:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4192:                 }
                   4193:             }
1.640     albertel 4194: 	    if (lc($tagname) eq 'object' ||
                   4195: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4196: 		foreach my $item (keys(%javafiles)) {
                   4197: 		    $javafiles{$item} = '';
                   4198: 		}
1.1164    raeburn  4199:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4200:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4201:                 }
1.640     albertel 4202: 	    }
                   4203: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4204: 		my $name = lc($attr->{'name'});
                   4205: 		foreach my $item (keys(%javafiles)) {
                   4206: 		    if ($name eq $item) {
                   4207: 			$javafiles{$item} = $attr->{'value'};
                   4208: 			last;
                   4209: 		    }
                   4210: 		}
1.1164    raeburn  4211:                 my $pathfrom;
1.640     albertel 4212: 		foreach my $item (keys(%mediafiles)) {
                   4213: 		    if ($name eq $item) {
1.1164    raeburn  4214:                         $pathfrom = $attr->{'value'};
                   4215:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4216: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4217: 			last;
                   4218: 		    }
                   4219: 		}
1.1164    raeburn  4220:                 if ($name eq 'flashvars') {
                   4221:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4222:                 }
                   4223:                 if ($pathfrom ne '') {
                   4224:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4225:                                          $pathfrom);
                   4226:                 }
1.640     albertel 4227: 	    }
                   4228: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4229: 		foreach my $item (keys(%javafiles)) {
                   4230: 		    if ($attr->{$item}) {
                   4231: 			$javafiles{$item} = $attr->{$item};
                   4232: 			last;
                   4233: 		    }
                   4234: 		}
                   4235: 		foreach my $item (keys(%mediafiles)) {
                   4236: 		    if ($attr->{$item}) {
                   4237: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4238: 			last;
                   4239: 		    }
                   4240: 		}
1.1164    raeburn  4241:                 if (lc($tagname) eq 'embed') {
                   4242:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4243:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4244:                                              $attr->{'src'});
                   4245:                     }
                   4246:                 }
1.640     albertel 4247: 	    }
1.1243    raeburn  4248:             if (lc($tagname) eq 'iframe') {
                   4249:                 my $src = $attr->{'src'} ;
                   4250:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4251:                     &add_filetype($allfiles,$src,'src');
                   4252:                 } elsif ($src =~ m{^/}) {
                   4253:                     if ($env{'request.course.id'}) {
                   4254:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4255:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4256:                         my $url = &hreflocation('',$fullpath);
                   4257:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4258:                             my $relpath = $1;
                   4259:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4260:                                 &add_filetype($allfiles,$1,'src');
                   4261:                             }
                   4262:                         }
                   4263:                     }
                   4264:                 }
                   4265:             }
1.1164    raeburn  4266:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4267:                 pop(@state);
1.1164    raeburn  4268:             }
1.640     albertel 4269: 	} elsif ($t->[0] eq 'E') {
                   4270: 	    my ($tagname) = ($t->[1]);
                   4271: 	    if ($javafiles{'codebase'} ne '') {
                   4272: 		$javafiles{'codebase'} .= '/';
                   4273: 	    }  
                   4274: 	    if (lc($tagname) eq 'applet' ||
                   4275: 		lc($tagname) eq 'object' ||
                   4276: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4277: 		) {
                   4278: 		foreach my $item (keys(%javafiles)) {
                   4279: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4280: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4281: 			&add_filetype($allfiles,$file,$item);
                   4282: 		    }
                   4283: 		}
                   4284: 	    } 
                   4285: 	    pop @state;
                   4286: 	}
                   4287:     }
1.1164    raeburn  4288:     foreach my $id (sort(keys(%flashvars))) {
                   4289:         if ($shockwave{$id} ne '') {
                   4290:             my @pairs = split(/\&/,$flashvars{$id});
                   4291:             foreach my $pair (@pairs) {
                   4292:                 my ($key,$value) = split(/\=/,$pair);
                   4293:                 if ($key eq 'thumb') {
                   4294:                     &add_filetype($allfiles,$value,$key);
                   4295:                 } elsif ($key eq 'content') {
                   4296:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4297:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4298:                     if ($ext ne '') {
                   4299:                         &add_filetype($allfiles,$path.$value,$ext);
                   4300:                     }
                   4301:                 }
                   4302:             }
                   4303:         }
                   4304:     }
1.637     raeburn  4305:     return 'ok';
                   4306: }
                   4307: 
1.639     albertel 4308: sub add_filetype {
                   4309:     my ($allfiles,$file,$type)=@_;
                   4310:     if (exists($allfiles->{$file})) {
                   4311: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4312: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4313: 	}
                   4314:     } else {
                   4315: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4316:     }
                   4317: }
                   4318: 
1.1164    raeburn  4319: sub embedded_dependency {
                   4320:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4321:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4322:         if (($identifier ne '') &&
                   4323:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4324:             ($pathfrom ne '')) {
                   4325:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4326:             foreach my $dep (@{$related->{$identifier}}) {
                   4327:                 &add_filetype($allfiles,$path.$dep,'object');
                   4328:             }
                   4329:         }
                   4330:     }
                   4331:     return;
                   4332: }
                   4333: 
1.493     albertel 4334: sub removeuploadedurl {
1.984     neumanie 4335:     my ($url)=@_;	
                   4336:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4337:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4338: }
                   4339: 
                   4340: sub removeuserfile {
                   4341:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4342:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4343:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4344:     if ($result eq 'ok') {	
1.798     raeburn  4345:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4346:             my $metafile = $fname.'.meta';
                   4347:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4348: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4349:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4350:             my $sqlresult = 
1.823     albertel 4351:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4352:                                         'portfolio_metadata',$group,
                   4353:                                         'delete');
1.798     raeburn  4354:         }
                   4355:     }
                   4356:     return $result;
1.257     www      4357: }
1.15      www      4358: 
1.530     albertel 4359: sub mkdiruserfile {
                   4360:     my ($docuname,$docudom,$dir)=@_;
                   4361:     my $home=&homeserver($docuname,$docudom);
                   4362:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4363: }
                   4364: 
1.531     albertel 4365: sub renameuserfile {
                   4366:     my ($docuname,$docudom,$old,$new)=@_;
                   4367:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4368:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4369:                         &escape("$old").':'.&escape("$new"),$home);
                   4370:     if ($result eq 'ok') {
                   4371:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4372:             my $oldmeta = $old.'.meta';
                   4373:             my $newmeta = $new.'.meta';
                   4374:             my $metaresult = 
                   4375:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4376: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4377:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4378:             my $sqlresult = 
1.823     albertel 4379:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4380:                                         'portfolio_metadata',$group,
                   4381:                                         'delete');
1.798     raeburn  4382:         }
                   4383:     }
                   4384:     return $result;
1.531     albertel 4385: }
                   4386: 
1.14      www      4387: # ------------------------------------------------------------------------- Log
                   4388: 
                   4389: sub log {
                   4390:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4391:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4392: }
                   4393: 
                   4394: # ------------------------------------------------------------------ Course Log
1.352     www      4395: #
                   4396: # This routine flushes several buffers of non-mission-critical nature
                   4397: #
1.157     www      4398: 
                   4399: sub flushcourselogs {
1.352     www      4400:     &logthis('Flushing log buffers');
                   4401: #
                   4402: # course logs
                   4403: # This is a log of all transactions in a course, which can be used
                   4404: # for data mining purposes
                   4405: #
                   4406: # It also collects the courseid database, which lists last transaction
                   4407: # times and course titles for all courseids
                   4408: #
                   4409:     my %courseidbuffer=();
1.921     raeburn  4410:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4411:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4412: 		          &escape($courselogs{$crsid}),
                   4413: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4414: 	    delete $courselogs{$crsid};
                   4415:         } else {
                   4416:             &logthis('Failed to flush log buffer for '.$crsid);
                   4417:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4418:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4419:                         " exceeded maximum size, deleting.</font>");
                   4420:                delete $courselogs{$crsid};
                   4421:             }
1.352     www      4422:         }
1.920     raeburn  4423:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4424:             'description' => $coursedescrbuf{$crsid},
                   4425:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4426:             'type'        => $coursetypebuf{$crsid},
                   4427:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4428:         };
1.191     harris41 4429:     }
1.352     www      4430: #
                   4431: # Write course id database (reverse lookup) to homeserver of courses 
                   4432: # Is used in pickcourse
                   4433: #
1.840     albertel 4434:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4435:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4436:                                     $courseidbuffer{$crs_home},
                   4437:                                     $crs_home,'timeonly');
1.352     www      4438:     }
                   4439: #
                   4440: # File accesses
                   4441: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4442: #
1.449     matthew  4443:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4444:         if ($entry =~ /___count$/) {
                   4445:             my ($dom,$name);
1.807     albertel 4446:             ($dom,$name,undef)=
1.811     albertel 4447: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4448:             if (! defined($dom) || $dom eq '' || 
                   4449:                 ! defined($name) || $name eq '') {
1.620     albertel 4450:                 my $cid = $env{'request.course.id'};
                   4451:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4452:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4453:             }
1.450     matthew  4454:             my $value = $accesshash{$entry};
                   4455:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4456:             my %temphash=($url => $value);
1.449     matthew  4457:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4458:             if ($result eq 'ok') {
                   4459:                 delete $accesshash{$entry};
                   4460:             }
                   4461:         } else {
1.811     albertel 4462:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4463:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4464:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4465:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4466:                 delete $accesshash{$entry};
                   4467:             }
1.185     www      4468:         }
1.191     harris41 4469:     }
1.352     www      4470: #
                   4471: # Roles
                   4472: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4473: #
1.800     albertel 4474:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4475:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4476: 	    split(/\:/,$entry);
                   4477:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4478:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4479:                 $rudom,$runame) eq 'ok') {
                   4480: 	    delete $userrolehash{$entry};
                   4481:         }
                   4482:     }
1.662     raeburn  4483: #
1.1334    raeburn  4484: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4485: #
                   4486:     my %domrolebuffer = ();
1.1000    raeburn  4487:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4488:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4489:         if ($domrolebuffer{$rudom}) {
                   4490:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4491:                       '='.&escape($domainrolehash{$entry});
                   4492:         } else {
                   4493:             $domrolebuffer{$rudom}.=&escape($entry).
                   4494:                       '='.&escape($domainrolehash{$entry});
                   4495:         }
                   4496:         delete $domainrolehash{$entry};
                   4497:     }
                   4498:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4499: 	my %servers;
                   4500: 	if (defined(&domain($dom,'primary'))) {
                   4501: 	    my $primary=&domain($dom,'primary');
                   4502: 	    my $hostname=&hostname($primary);
                   4503: 	    $servers{$primary} = $hostname;
                   4504: 	} else { 
                   4505: 	    %servers = &get_servers($dom,'library');
                   4506: 	}
1.841     albertel 4507: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4508: 	    if (&reply('domroleput:'.$dom.':'.
                   4509: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4510: 		last;
                   4511: 	    } else {  
1.841     albertel 4512: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4513: 	    }
1.662     raeburn  4514:         }
                   4515:     }
1.186     www      4516:     $dumpcount++;
1.157     www      4517: }
                   4518: 
                   4519: sub courselog {
                   4520:     my $what=shift;
1.158     www      4521:     $what=time.':'.$what;
1.620     albertel 4522:     unless ($env{'request.course.id'}) { return ''; }
                   4523:     $coursedombuf{$env{'request.course.id'}}=
                   4524:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4525:     $coursenumbuf{$env{'request.course.id'}}=
                   4526:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4527:     $coursehombuf{$env{'request.course.id'}}=
                   4528:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4529:     $coursedescrbuf{$env{'request.course.id'}}=
                   4530:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4531:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4532:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4533:     $courseownerbuf{$env{'request.course.id'}}=
                   4534:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4535:     $coursetypebuf{$env{'request.course.id'}}=
                   4536:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4537:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4538: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4539:     } else {
1.620     albertel 4540: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4541:     }
1.620     albertel 4542:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4543: 	&flushcourselogs();
                   4544:     }
1.158     www      4545: }
                   4546: 
                   4547: sub courseacclog {
                   4548:     my $fnsymb=shift;
1.620     albertel 4549:     unless ($env{'request.course.id'}) { return ''; }
                   4550:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4551:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4552:         $what.=':POST';
1.583     matthew  4553:         # FIXME: Probably ought to escape things....
1.800     albertel 4554: 	foreach my $key (keys(%env)) {
                   4555:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4556:                 my $formitem = $1;
                   4557:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4558:                     $what.=':'.$formitem.'='.$env{$key};
                   4559:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4560:                     $what.=':'.$formitem.'='.$env{$key};
                   4561:                 }
1.158     www      4562:             }
1.191     harris41 4563:         }
1.583     matthew  4564:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4565:         # FIXME: We should not be depending on a form parameter that someone
                   4566:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4567:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4568:             $what.= ':POST';
                   4569:             # FIXME: Probably ought to escape things....
                   4570:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4571:                                  'crsdiscuss') {
1.620     albertel 4572:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4573:             }
                   4574:         }
1.158     www      4575:     }
                   4576:     &courselog($what);
1.149     www      4577: }
                   4578: 
1.185     www      4579: sub countacc {
                   4580:     my $url=&declutter(shift);
1.458     matthew  4581:     return if (! defined($url) || $url eq '');
1.620     albertel 4582:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4583: #
                   4584: # Mark that this url was used in this course
                   4585: #
1.620     albertel 4586:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4587: #
                   4588: # Increase the access count for this resource in this child process
                   4589: #
1.281     www      4590:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4591:     $accesshash{$key}++;
1.185     www      4592: }
1.349     www      4593: 
1.361     www      4594: sub linklog {
                   4595:     my ($from,$to)=@_;
                   4596:     $from=&declutter($from);
                   4597:     $to=&declutter($to);
                   4598:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4599:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4600: }
1.1160    www      4601: 
                   4602: sub statslog {
                   4603:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4604:     if ($users<2) { return; }
                   4605:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4606:             'course'       => $env{'request.course.id'},
                   4607:             'sections'     => '"all"',
                   4608:             'num_students' => $users,
                   4609:             'part'         => $part,
                   4610:             'symb'         => $symb,
                   4611:             'mean_tries'   => $av_attempts,
                   4612:             'deg_of_diff'  => $degdiff});
                   4613:     foreach my $key (keys(%dynstore)) {
                   4614:         $accesshash{$key}=$dynstore{$key};
                   4615:     }
                   4616: }
1.361     www      4617:   
1.349     www      4618: sub userrolelog {
                   4619:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4620:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4621:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4622:        $userrolehash
                   4623:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4624:                     =$tend.':'.$tstart;
1.662     raeburn  4625:     }
1.1169    droeschl 4626:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4627:        $userrolehash
                   4628:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4629:                     =$tend.':'.$tstart;
                   4630:     }
1.1334    raeburn  4631:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4632:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4633:        $domainrolehash
                   4634:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4635:                     = $tend.':'.$tstart;
                   4636:     }
1.351     www      4637: }
                   4638: 
1.957     raeburn  4639: sub courserolelog {
                   4640:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4641:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4642:         my $cdom = $1;
                   4643:         my $cnum = $2;
                   4644:         my $sec = $3;
                   4645:         my $namespace = 'rolelog';
                   4646:         my %storehash = (
                   4647:                            role    => $trole,
                   4648:                            start   => $tstart,
                   4649:                            end     => $tend,
                   4650:                            selfenroll => $selfenroll,
                   4651:                            context    => $context,
                   4652:                         );
                   4653:         if ($trole eq 'gr') {
                   4654:             $namespace = 'groupslog';
                   4655:             $storehash{'group'} = $sec;
                   4656:         } else {
                   4657:             $storehash{'section'} = $sec;
                   4658:         }
1.1188    raeburn  4659:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4660:                    $domain,$cnum,$cdom);
1.1184    raeburn  4661:         if (($trole ne 'st') || ($sec ne '')) {
                   4662:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4663:         }
                   4664:     }
                   4665:     return;
                   4666: }
                   4667: 
1.1184    raeburn  4668: sub domainrolelog {
                   4669:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4670:     if ($area =~ m{^/($match_domain)/$}) {
                   4671:         my $cdom = $1;
                   4672:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4673:         my $namespace = 'rolelog';
                   4674:         my %storehash = (
                   4675:                            role    => $trole,
                   4676:                            start   => $tstart,
                   4677:                            end     => $tend,
                   4678:                            context => $context,
                   4679:                         );
1.1188    raeburn  4680:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4681:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4682:     }
                   4683:     return;
                   4684: 
                   4685: }
                   4686: 
                   4687: sub coauthorrolelog {
                   4688:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4689:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4690:         my $audom = $1;
                   4691:         my $auname = $2;
                   4692:         my $namespace = 'rolelog';
                   4693:         my %storehash = (
                   4694:                            role    => $trole,
                   4695:                            start   => $tstart,
                   4696:                            end     => $tend,
                   4697:                            context => $context,
                   4698:                         );
1.1188    raeburn  4699:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4700:                    $domain,$auname,$audom);
1.1184    raeburn  4701:     }
                   4702:     return;
                   4703: }
                   4704: 
1.351     www      4705: sub get_course_adv_roles {
1.948     raeburn  4706:     my ($cid,$codes) = @_;
1.620     albertel 4707:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4708:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4709:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4710:     my %nothide=();
1.800     albertel 4711:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4712:         if ($user !~ /:/) {
                   4713: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4714:         } else {
                   4715:             $nothide{$user}=1;
                   4716:         }
1.470     www      4717:     }
1.1219    raeburn  4718:     my @possdoms = ($coursehash{'domain'});
                   4719:     if ($coursehash{'checkforpriv'}) {
                   4720:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4721:     }
1.351     www      4722:     my %returnhash=();
                   4723:     my %dumphash=
                   4724:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4725:     my $now=time;
1.997     raeburn  4726:     my %privileged;
1.1000    raeburn  4727:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4728: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4729:         if (($tstart) && ($tstart<0)) { next; }
                   4730:         if (($tend) && ($tend<$now)) { next; }
                   4731:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4732:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4733: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4734:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4735:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4736: 	if ($role eq 'cr') { next; }
1.948     raeburn  4737:         if ($codes) {
                   4738:             if ($section) { $role .= ':'.$section; }
                   4739:             if ($returnhash{$role}) {
                   4740:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4741:             } else {
                   4742:                 $returnhash{$role}=$username.':'.$domain;
                   4743:             }
1.351     www      4744:         } else {
1.988     raeburn  4745:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4746:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4747:             if ($returnhash{$key}) {
                   4748: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4749:             } else {
                   4750:                 $returnhash{$key}=$username.':'.$domain;
                   4751:             }
1.351     www      4752:         }
1.948     raeburn  4753:     }
1.400     www      4754:     return %returnhash;
                   4755: }
                   4756: 
                   4757: sub get_my_roles {
1.937     raeburn  4758:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4759:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4760:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4761:     my (%dumphash,%nothide);
1.1086    raeburn  4762:     if ($context eq 'userroles') {
1.1166    raeburn  4763:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4764:     } else {
1.1219    raeburn  4765:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4766:         if ($hidepriv) {
                   4767:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4768:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4769:                 if ($user !~ /:/) {
                   4770:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4771:                 } else {
                   4772:                     $nothide{$user} = 1;
                   4773:                 }
                   4774:             }
                   4775:         }
1.858     raeburn  4776:     }
1.400     www      4777:     my %returnhash=();
                   4778:     my $now=time;
1.999     raeburn  4779:     my %privileged;
1.800     albertel 4780:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4781:         my ($role,$tend,$tstart);
                   4782:         if ($context eq 'userroles') {
1.1149    raeburn  4783:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4784: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4785:         } else {
                   4786:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4787:         }
1.400     www      4788:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4789:         my $status = 'active';
1.939     raeburn  4790:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4791:             $status = 'previous';
                   4792:         } 
                   4793:         if (($tstart) && ($now<$tstart)) {
                   4794:             $status = 'future';
                   4795:         }
                   4796:         if (ref($types) eq 'ARRAY') {
                   4797:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4798:                 next;
                   4799:             } 
                   4800:         } else {
                   4801:             if ($status ne 'active') {
                   4802:                 next;
                   4803:             }
                   4804:         }
1.867     raeburn  4805:         my ($rolecode,$username,$domain,$section,$area);
                   4806:         if ($context eq 'userroles') {
1.1186    raeburn  4807:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4808:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4809:         } else {
                   4810:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4811:         }
1.832     raeburn  4812:         if (ref($roledoms) eq 'ARRAY') {
                   4813:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4814:                 next;
                   4815:             }
                   4816:         }
                   4817:         if (ref($roles) eq 'ARRAY') {
                   4818:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4819:                 if ($role =~ /^cr\//) {
                   4820:                     if (!grep(/^cr$/,@{$roles})) {
                   4821:                         next;
                   4822:                     }
1.1104    raeburn  4823:                 } elsif ($role =~ /^gr\//) {
                   4824:                     if (!grep(/^gr$/,@{$roles})) {
                   4825:                         next;
                   4826:                     }
1.922     raeburn  4827:                 } else {
                   4828:                     next;
                   4829:                 }
1.832     raeburn  4830:             }
1.867     raeburn  4831:         }
1.937     raeburn  4832:         if ($hidepriv) {
1.1219    raeburn  4833:             my @privroles = ('dc','su');
1.999     raeburn  4834:             if ($context eq 'userroles') {
1.1219    raeburn  4835:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4836:             } else {
1.1219    raeburn  4837:                 my $possdoms = [$domain];
                   4838:                 if (ref($roledoms) eq 'ARRAY') {
                   4839:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4840:                 }
1.1219    raeburn  4841:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4842:                     if (!$nothide{$username.':'.$domain}) {
                   4843:                         next;
                   4844:                     }
                   4845:                 }
1.937     raeburn  4846:             }
                   4847:         }
1.933     raeburn  4848:         if ($withsec) {
                   4849:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4850:                 $tstart.':'.$tend;
                   4851:         } else {
                   4852:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4853:         }
1.832     raeburn  4854:     }
1.373     www      4855:     return %returnhash;
1.399     www      4856: }
                   4857: 
1.1333    raeburn  4858: sub get_all_adhocroles {
                   4859:     my ($dom) = @_;
                   4860:     my @roles_by_num = ();
                   4861:     my %domdefaults = &get_domain_defaults($dom);
                   4862:     my (%description,%access_in_dom,%access_info);
                   4863:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4864:         my $count = 0;
                   4865:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4866:         my %ordered;
                   4867:         foreach my $role (sort(keys(%domcurrent))) {
                   4868:             my ($order,$desc,$access_in_dom);
                   4869:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4870:                 $order = $domcurrent{$role}{'order'};
                   4871:                 $desc = $domcurrent{$role}{'desc'};
                   4872:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4873:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4874:             }
                   4875:             if ($order eq '') {
                   4876:                 $order = $count;
                   4877:             }
                   4878:             $ordered{$order} = $role;
                   4879:             if ($desc ne '') {
                   4880:                 $description{$role} = $desc;
                   4881:             } else {
                   4882:                 $description{$role}= $role;
                   4883:             }
                   4884:             $count++;
                   4885:         }
                   4886:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4887:             push(@roles_by_num,$ordered{$item});
                   4888:         }
                   4889:     }
                   4890:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4891: }
                   4892: 
1.1332    raeburn  4893: sub get_my_adhocroles {
1.1333    raeburn  4894:     my ($cid,$checkreg) = @_;
                   4895:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4896:     if ($env{'request.course.id'} eq $cid) {
                   4897:         $cdom = $env{'course.'.$cid.'.domain'};
                   4898:         $cnum = $env{'course.'.$cid.'.num'};
                   4899:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4900:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4901:         $cdom = $1;
                   4902:         $cnum = $2;
                   4903:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4904:                                      $cdom,$cnum);
                   4905:     }
                   4906:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4907:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4908:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4909:         if ($rosterhash{$user} ne '') {
                   4910:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4911:             return ([],{}) if ($type eq 'auto');
                   4912:         }
                   4913:     }
                   4914:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4915:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4916:             my $then=$env{'user.login.time'};
                   4917:             my $update=$env{'user.update.time'};
1.1335    raeburn  4918:             if (!$update) {
                   4919:                 $update = $then;
                   4920:             }
                   4921:             my @liveroles;
1.1334    raeburn  4922:             foreach my $role ('dh','da') {
                   4923:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4924:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4925:                     my $limit = $update;
                   4926:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4927:                         $limit = $then;
                   4928:                     }
1.1335    raeburn  4929:                     my $activerole = 1;
                   4930:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4931:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4932:                     if ($activerole) {
                   4933:                         push(@liveroles,$role);
                   4934:                     }
1.1334    raeburn  4935:                 }
1.1332    raeburn  4936:             }
1.1335    raeburn  4937:             if (@liveroles) {
1.1332    raeburn  4938:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4939:                     my ($accessref,$accessinfo,%access_in_dom);
                   4940:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4941:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4942:                         if (@{$roles_by_num}) {
1.1332    raeburn  4943:                             my %settings;
                   4944:                             if ($env{'request.course.id'} eq $cid) {
                   4945:                                 foreach my $envkey (keys(%env)) {
                   4946:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4947:                                         $settings{$1} = $env{$envkey};
                   4948:                                     }
                   4949:                                 }
                   4950:                             } else {
                   4951:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4952:                             }
                   4953:                             my %setincrs;
                   4954:                             if ($settings{'internal.adhocaccess'}) {
                   4955:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4956:                             }
                   4957:                             my @statuses;
                   4958:                             if ($env{'environment.inststatus'}) {
                   4959:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4960:                             }
                   4961:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4962:                             if (ref($accessref) eq 'HASH') {
                   4963:                                 %access_in_dom = %{$accessref};
                   4964:                             }
                   4965:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4966:                                 my ($curraccess,@okstatus,@personnel);
                   4967:                                 if ($setincrs{$role}) {
                   4968:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4969:                                     if ($curraccess eq 'status') {
                   4970:                                         @okstatus = split(/\&/,$rest);
                   4971:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4972:                                         @personnel = split(/\&/,$rest);
                   4973:                                     }
                   4974:                                 } else {
                   4975:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4976:                                     if (ref($accessinfo) eq 'HASH') {
                   4977:                                         if ($curraccess eq 'status') {
                   4978:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4979:                                                 @okstatus = @{$accessinfo->{$role}};
                   4980:                                             }
                   4981:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4982:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4983:                                                 @personnel = @{$accessinfo->{$role}};
                   4984:                                             }
1.1332    raeburn  4985:                                         }
                   4986:                                     }
                   4987:                                 }
                   4988:                                 if ($curraccess eq 'none') {
                   4989:                                     next;
                   4990:                                 } elsif ($curraccess eq 'all') {
                   4991:                                     push(@possroles,$role);
1.1336    raeburn  4992:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4993:                                     if (grep(/^dh$/,@liveroles)) {
                   4994:                                         push(@possroles,$role);
                   4995:                                     } else {
                   4996:                                         next;
                   4997:                                     }
1.1336    raeburn  4998:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4999:                                     if (grep(/^da$/,@liveroles)) {
                   5000:                                         push(@possroles,$role);
                   5001:                                     } else {
                   5002:                                         next;
                   5003:                                     }
1.1332    raeburn  5004:                                 } elsif ($curraccess eq 'status') {
                   5005:                                     if (@okstatus) {
                   5006:                                         if (!@statuses) {
                   5007:                                             if (grep(/^default$/,@okstatus)) {
                   5008:                                                 push(@possroles,$role);
                   5009:                                             }
                   5010:                                         } else {
                   5011:                                             foreach my $status (@okstatus) {
                   5012:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5013:                                                     push(@possroles,$role);
                   5014:                                                     last;
                   5015:                                                 }
                   5016:                                             }
                   5017:                                         }
                   5018:                                     }
                   5019:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5020:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5021:                                         if ($curraccess eq 'exc') {
                   5022:                                             push(@possroles,$role);
                   5023:                                         }
                   5024:                                     } elsif ($curraccess eq 'inc') {
                   5025:                                         push(@possroles,$role);
                   5026:                                     }
                   5027:                                 }
                   5028:                             }
                   5029:                         }
                   5030:                     }
                   5031:                 }
                   5032:             }
                   5033:         }
                   5034:     }
1.1333    raeburn  5035:     unless (ref($description) eq 'HASH') {
                   5036:         if (ref($roles_by_num) eq 'ARRAY') {
                   5037:             my %desc;
                   5038:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5039:             $description = \%desc;
                   5040:         } else {
                   5041:             $description = {};
                   5042:         }
                   5043:     }
                   5044:     return (\@possroles,$description);
1.1332    raeburn  5045: }
                   5046: 
1.399     www      5047: # ----------------------------------------------------- Frontpage Announcements
                   5048: #
                   5049: #
                   5050: 
                   5051: sub postannounce {
                   5052:     my ($server,$text)=@_;
1.844     albertel 5053:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5054:     unless ($text=~/\w/) { $text=''; }
                   5055:     return &reply('setannounce:'.&escape($text),$server);
                   5056: }
                   5057: 
                   5058: sub getannounce {
1.448     albertel 5059: 
1.1359    raeburn  5060:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5061: 	my $announcement='';
1.800     albertel 5062: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5063: 	close($fh);
1.399     www      5064: 	if ($announcement=~/\w/) { 
                   5065: 	    return 
                   5066:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5067:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5068: 	} else {
                   5069: 	    return '';
                   5070: 	}
                   5071:     } else {
                   5072: 	return '';
                   5073:     }
1.351     www      5074: }
1.353     www      5075: 
                   5076: # ---------------------------------------------------------- Course ID routines
                   5077: # Deal with domain's nohist_courseid.db files
                   5078: #
                   5079: 
                   5080: sub courseidput {
1.921     raeburn  5081:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5082:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5083:     my $outcome;
                   5084:     if ($caller eq 'timeonly') {
                   5085:         my $cids = '';
                   5086:         foreach my $item (keys(%$storehash)) {
                   5087:             $cids.=&escape($item).'&';
                   5088:         }
                   5089:         $cids=~s/\&$//;
                   5090:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5091:                           $coursehome);       
                   5092:     } else {
                   5093:         my $items = '';
                   5094:         foreach my $item (keys(%$storehash)) {
                   5095:             $items.= &escape($item).'='.
                   5096:                      &freeze_escape($$storehash{$item}).'&';
                   5097:         }
                   5098:         $items=~s/\&$//;
                   5099:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5100:                           $coursehome);
1.918     raeburn  5101:     }
                   5102:     if ($outcome eq 'unknown_cmd') {
                   5103:         my $what;
                   5104:         foreach my $cid (keys(%$storehash)) {
                   5105:             $what .= &escape($cid).'=';
1.921     raeburn  5106:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5107:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5108:             }
                   5109:             $what =~ s/\:$/&/;
                   5110:         }
                   5111:         $what =~ s/\&$//;  
                   5112:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5113:     } else {
                   5114:         return $outcome;
                   5115:     }
1.353     www      5116: }
                   5117: 
                   5118: sub courseiddump {
1.921     raeburn  5119:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5120:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5121:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5122:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5123:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5124:     my $as_hash = 1;
                   5125:     my %returnhash;
                   5126:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5127:     my %libserv = &all_library();
                   5128:     foreach my $tryserver (keys(%libserv)) {
                   5129:         if ( (  $hostidflag == 1 
                   5130: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5131: 	     || (!defined($hostidflag)) ) {
                   5132: 
1.918     raeburn  5133: 	    if (($domfilter eq '') ||
                   5134: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5135:                 my $rep;
                   5136:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5137:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5138:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5139:                                 &escape($descfilter), &escape($instcodefilter), 
                   5140:                                 &escape($ownerfilter), &escape($coursefilter),
                   5141:                                 &escape($typefilter), &escape($regexp_ok), 
                   5142:                                 $as_hash, &escape($selfenrollonly), 
                   5143:                                 &escape($catfilter), $showhidden, $caller, 
                   5144:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5145:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5146:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5147:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5148:                 } else {
                   5149:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5150:                              $sincefilter.':'.&escape($descfilter).':'.
                   5151:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5152:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5153:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5154:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5155:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5156:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5157:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5158:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5159:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5160:                 }
                   5161:                      
1.918     raeburn  5162:                 my @pairs=split(/\&/,$rep);
                   5163:                 foreach my $item (@pairs) {
                   5164:                     my ($key,$value)=split(/\=/,$item,2);
                   5165:                     $key = &unescape($key);
                   5166:                     next if ($key =~ /^error: 2 /);
                   5167:                     my $result = &thaw_unescape($value);
                   5168:                     if (ref($result) eq 'HASH') {
                   5169:                         $returnhash{$key}=$result;
                   5170:                     } else {
1.921     raeburn  5171:                         my @responses = split(/:/,$value);
                   5172:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5173:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5174:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5175:                         }
1.1008    raeburn  5176:                     }
1.353     www      5177:                 }
                   5178:             }
                   5179:         }
                   5180:     }
                   5181:     return %returnhash;
                   5182: }
                   5183: 
1.1055    raeburn  5184: sub courselastaccess {
                   5185:     my ($cdom,$cnum,$hostidref) = @_;
                   5186:     my %returnhash;
                   5187:     if ($cdom && $cnum) {
                   5188:         my $chome = &homeserver($cnum,$cdom);
                   5189:         if ($chome ne 'no_host') {
                   5190:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5191:             &extract_lastaccess(\%returnhash,$rep);
                   5192:         }
                   5193:     } else {
                   5194:         if (!$cdom) { $cdom=''; }
                   5195:         my %libserv = &all_library();
                   5196:         foreach my $tryserver (keys(%libserv)) {
                   5197:             if (ref($hostidref) eq 'ARRAY') {
                   5198:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5199:             } 
                   5200:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5201:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5202:                 &extract_lastaccess(\%returnhash,$rep);
                   5203:             }
                   5204:         }
                   5205:     }
                   5206:     return %returnhash;
                   5207: }
                   5208: 
                   5209: sub extract_lastaccess {
                   5210:     my ($returnhash,$rep) = @_;
                   5211:     if (ref($returnhash) eq 'HASH') {
                   5212:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5213:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5214:                  $rep eq '') {
                   5215:             my @pairs=split(/\&/,$rep);
                   5216:             foreach my $item (@pairs) {
                   5217:                 my ($key,$value)=split(/\=/,$item,2);
                   5218:                 $key = &unescape($key);
                   5219:                 next if ($key =~ /^error: 2 /);
                   5220:                 $returnhash->{$key} = &thaw_unescape($value);
                   5221:             }
                   5222:         }
                   5223:     }
                   5224:     return;
                   5225: }
                   5226: 
1.658     raeburn  5227: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5228: 
                   5229: sub dcmailput {
1.685     raeburn  5230:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5231:     my $status = &Apache::lonnet::critical(
1.740     www      5232:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5233:        &escape($message),$server);
1.662     raeburn  5234:     return $status;
                   5235: }
                   5236: 
1.658     raeburn  5237: sub dcmaildump {
                   5238:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5239:     my %returnhash=();
1.846     albertel 5240: 
                   5241:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5242:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5243:                                                          &escape($enddate).':';
                   5244: 	my @esc_senders=map { &escape($_)} @$senders;
                   5245: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5246: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5247:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5248:             if (($key) && ($value)) {
                   5249:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5250:             }
                   5251:         }
                   5252:     }
                   5253:     return %returnhash;
                   5254: }
1.662     raeburn  5255: # ---------------------------------------------------------- Domain roles
                   5256: 
                   5257: sub get_domain_roles {
                   5258:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5259:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5260:         $startdate = '.';
                   5261:     }
1.1018    raeburn  5262:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5263:         $enddate = '.';
                   5264:     }
1.922     raeburn  5265:     my $rolelist;
                   5266:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5267:         $rolelist = join('&',@{$roles});
1.922     raeburn  5268:     }
1.662     raeburn  5269:     my %personnel = ();
1.841     albertel 5270: 
                   5271:     my %servers = &get_servers($dom,'library');
                   5272:     foreach my $tryserver (keys(%servers)) {
                   5273: 	%{$personnel{$tryserver}}=();
                   5274: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5275: 					    &escape($startdate).':'.
                   5276: 					    &escape($enddate).':'.
                   5277: 					    &escape($rolelist), $tryserver))) {
                   5278: 	    my ($key,$value) = split(/\=/,$line,2);
                   5279: 	    if (($key) && ($value)) {
                   5280: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5281: 	    }
                   5282: 	}
1.662     raeburn  5283:     }
                   5284:     return %personnel;
                   5285: }
1.658     raeburn  5286: 
1.1332    raeburn  5287: sub get_active_domroles {
                   5288:     my ($dom,$roles) = @_;
                   5289:     return () unless (ref($roles) eq 'ARRAY');
                   5290:     my $now = time;
                   5291:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5292:     my %domroles;
                   5293:     foreach my $server (keys(%dompersonnel)) {
                   5294:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5295:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5296:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5297:         }
                   5298:     }
                   5299:     return %domroles;
                   5300: }
                   5301: 
1.1057    www      5302: # ----------------------------------------------------------- Interval timing 
1.149     www      5303: 
1.1153    www      5304: {
                   5305: # Caches needed for speedup of navmaps
                   5306: # We don't want to cache this for very long at all (5 seconds at most)
                   5307: # 
                   5308: # The user for whom we cache
                   5309: my $cachedkey='';
                   5310: # The cached times for this user
                   5311: my %cachedtimes=();
                   5312: # When this was last done
1.1282    raeburn  5313: my $cachedtime='';
1.1153    www      5314: 
                   5315: sub load_all_first_access {
1.1308    raeburn  5316:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5317:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5318:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5319:         (!$ignorecache)) {
1.1154    raeburn  5320:         return;
                   5321:     }
                   5322:     $cachedtime=time;
                   5323:     $cachedkey=$uname.':'.$udom;
                   5324:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5325: }
                   5326: 
1.504     albertel 5327: sub get_first_access {
1.1308    raeburn  5328:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5329:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5330:     if ($argsymb) { $symb=$argsymb; }
                   5331:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5332:     if ($argmap) { $map = $argmap; }
1.926     albertel 5333:     if ($type eq 'course') {
                   5334: 	$res='course';
                   5335:     } elsif ($type eq 'map') {
1.588     albertel 5336: 	$res=&symbread($map);
                   5337:     } else {
                   5338: 	$res=$symb;
                   5339:     }
1.1308    raeburn  5340:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5341:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5342: }
                   5343: 
                   5344: sub set_first_access {
1.1162    raeburn  5345:     my ($type,$interval)=@_;
1.790     albertel 5346:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5347:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5348:     if ($type eq 'course') {
                   5349: 	$res='course';
                   5350:     } elsif ($type eq 'map') {
1.588     albertel 5351: 	$res=&symbread($map);
                   5352:     } else {
                   5353: 	$res=$symb;
                   5354:     }
1.1153    www      5355:     $cachedkey='';
1.1162    raeburn  5356:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5357:     if ($firstaccess) {
                   5358:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5359:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5360:                  "in $courseid");
1.1386    raeburn  5361:         return 'already_set';
                   5362:     } else {
1.1162    raeburn  5363:         my $start = time;
                   5364: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5365:                           $udom,$uname);
                   5366:         if ($putres eq 'ok') {
                   5367:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5368:                  $udom,$uname); 
                   5369:             &appenv(
                   5370:                      {
                   5371:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5372:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5373:                      }
                   5374:                   );
1.1365    raeburn  5375:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5376:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5377:             }
1.1386    raeburn  5378:         } elsif ($putres ne 'refused') {
                   5379:             &logthis("Result: $putres when attempting to set first access time ".
                   5380:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5381:         }
                   5382:         return $putres;
1.505     albertel 5383:     }
                   5384:     return 'already_set';
1.504     albertel 5385: }
1.1153    www      5386: }
1.1282    raeburn  5387: 
1.110     www      5388: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5389: 
                   5390: sub expirespread {
                   5391:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5392:     my $cid=$env{'request.course.id'}; 
1.110     www      5393:     if ($cid) {
                   5394:        my $now=time;
                   5395:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5396:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5397:                             $env{'course.'.$cid.'.num'}.
1.110     www      5398: 	        	    ':nohist_expirationdates:'.
                   5399:                             &escape($key).'='.$now,
1.620     albertel 5400:                             $env{'course.'.$cid.'.home'})
1.110     www      5401:     }
                   5402:     return 'ok';
1.14      www      5403: }
                   5404: 
1.109     www      5405: # ----------------------------------------------------- Devalidate Spreadsheets
                   5406: 
                   5407: sub devalidate {
1.325     www      5408:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5409:     my $cid=$env{'request.course.id'}; 
1.109     www      5410:     if ($cid) {
1.391     matthew  5411:         # delete the stored spreadsheets for
                   5412:         # - the student level sheet of this user in course's homespace
                   5413:         # - the assessment level sheet for this resource 
                   5414:         #   for this user in user's homespace
1.553     albertel 5415: 	# - current conditional state info
1.325     www      5416: 	my $key=$uname.':'.$udom.':';
1.109     www      5417:         my $status=
1.299     matthew  5418: 	    &del('nohist_calculatedsheets',
1.391     matthew  5419: 		 [$key.'studentcalc:'],
1.620     albertel 5420: 		 $env{'course.'.$cid.'.domain'},
                   5421: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5422: 		.' '.
                   5423: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5424: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5425:         unless ($status eq 'ok ok') {
                   5426:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5427:                     $uname.' at '.$udom.' for '.
1.109     www      5428: 		    $symb.': '.$status);
1.133     albertel 5429:         }
1.553     albertel 5430: 	&delenv('user.state.'.$cid);
1.109     www      5431:     }
                   5432: }
                   5433: 
1.265     albertel 5434: sub get_scalar {
                   5435:     my ($string,$end) = @_;
                   5436:     my $value;
                   5437:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5438: 	$value = $1;
                   5439:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5440: 	$value = $1;
                   5441:     }
                   5442:     return &unescape($value);
                   5443: }
                   5444: 
                   5445: sub array2str {
                   5446:   my (@array) = @_;
                   5447:   my $result=&arrayref2str(\@array);
                   5448:   $result=~s/^__ARRAY_REF__//;
                   5449:   $result=~s/__END_ARRAY_REF__$//;
                   5450:   return $result;
                   5451: }
                   5452: 
1.204     albertel 5453: sub arrayref2str {
                   5454:   my ($arrayref) = @_;
1.265     albertel 5455:   my $result='__ARRAY_REF__';
1.204     albertel 5456:   foreach my $elem (@$arrayref) {
1.265     albertel 5457:     if(ref($elem) eq 'ARRAY') {
                   5458:       $result.=&arrayref2str($elem).'&';
                   5459:     } elsif(ref($elem) eq 'HASH') {
                   5460:       $result.=&hashref2str($elem).'&';
                   5461:     } elsif(ref($elem)) {
                   5462:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5463:     } else {
                   5464:       $result.=&escape($elem).'&';
                   5465:     }
                   5466:   }
                   5467:   $result=~s/\&$//;
1.265     albertel 5468:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5469:   return $result;
                   5470: }
                   5471: 
1.168     albertel 5472: sub hash2str {
1.204     albertel 5473:   my (%hash) = @_;
                   5474:   my $result=&hashref2str(\%hash);
1.265     albertel 5475:   $result=~s/^__HASH_REF__//;
                   5476:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5477:   return $result;
                   5478: }
                   5479: 
                   5480: sub hashref2str {
                   5481:   my ($hashref)=@_;
1.265     albertel 5482:   my $result='__HASH_REF__';
1.800     albertel 5483:   foreach my $key (sort(keys(%$hashref))) {
                   5484:     if (ref($key) eq 'ARRAY') {
                   5485:       $result.=&arrayref2str($key).'=';
                   5486:     } elsif (ref($key) eq 'HASH') {
                   5487:       $result.=&hashref2str($key).'=';
                   5488:     } elsif (ref($key)) {
1.265     albertel 5489:       $result.='=';
1.800     albertel 5490:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5491:     } else {
1.1132    raeburn  5492: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5493:     }
                   5494: 
1.800     albertel 5495:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5496:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5497:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5498:       $result.=&hashref2str($hashref->{$key}).'&';
                   5499:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5500:        $result.='&';
1.800     albertel 5501:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5502:     } else {
1.800     albertel 5503:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5504:     }
                   5505:   }
1.168     albertel 5506:   $result=~s/\&$//;
1.265     albertel 5507:   $result .= '__END_HASH_REF__';
1.168     albertel 5508:   return $result;
                   5509: }
                   5510: 
                   5511: sub str2hash {
1.265     albertel 5512:     my ($string)=@_;
                   5513:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5514:     return %$hash;
                   5515: }
                   5516: 
                   5517: sub str2hashref {
1.168     albertel 5518:   my ($string) = @_;
1.265     albertel 5519: 
                   5520:   my %hash;
                   5521: 
                   5522:   if($string !~ /^__HASH_REF__/) {
                   5523:       if (! ($string eq '' || !defined($string))) {
                   5524: 	  $hash{'error'}='Not hash reference';
                   5525:       }
                   5526:       return (\%hash, $string);
                   5527:   }
                   5528: 
                   5529:   $string =~ s/^__HASH_REF__//;
                   5530: 
                   5531:   while($string !~ /^__END_HASH_REF__/) {
                   5532:       #key
                   5533:       my $key='';
                   5534:       if($string =~ /^__HASH_REF__/) {
                   5535:           ($key, $string)=&str2hashref($string);
                   5536:           if(defined($key->{'error'})) {
                   5537:               $hash{'error'}='Bad data';
                   5538:               return (\%hash, $string);
                   5539:           }
                   5540:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5541:           ($key, $string)=&str2arrayref($string);
                   5542:           if($key->[0] eq 'Array reference error') {
                   5543:               $hash{'error'}='Bad data';
                   5544:               return (\%hash, $string);
                   5545:           }
                   5546:       } else {
                   5547:           $string =~ s/^(.*?)=//;
1.267     albertel 5548: 	  $key=&unescape($1);
1.265     albertel 5549:       }
                   5550:       $string =~ s/^=//;
                   5551: 
                   5552:       #value
                   5553:       my $value='';
                   5554:       if($string =~ /^__HASH_REF__/) {
                   5555:           ($value, $string)=&str2hashref($string);
                   5556:           if(defined($value->{'error'})) {
                   5557:               $hash{'error'}='Bad data';
                   5558:               return (\%hash, $string);
                   5559:           }
                   5560:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5561:           ($value, $string)=&str2arrayref($string);
                   5562:           if($value->[0] eq 'Array reference error') {
                   5563:               $hash{'error'}='Bad data';
                   5564:               return (\%hash, $string);
                   5565:           }
                   5566:       } else {
                   5567: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5568:       }
                   5569:       $string =~ s/^&//;
                   5570: 
                   5571:       $hash{$key}=$value;
1.204     albertel 5572:   }
1.265     albertel 5573: 
                   5574:   $string =~ s/^__END_HASH_REF__//;
                   5575: 
                   5576:   return (\%hash, $string);
1.204     albertel 5577: }
                   5578: 
                   5579: sub str2array {
1.265     albertel 5580:     my ($string)=@_;
                   5581:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5582:     return @$array;
                   5583: }
                   5584: 
                   5585: sub str2arrayref {
1.204     albertel 5586:   my ($string) = @_;
1.265     albertel 5587:   my @array;
                   5588: 
                   5589:   if($string !~ /^__ARRAY_REF__/) {
                   5590:       if (! ($string eq '' || !defined($string))) {
                   5591: 	  $array[0]='Array reference error';
                   5592:       }
                   5593:       return (\@array, $string);
                   5594:   }
                   5595: 
                   5596:   $string =~ s/^__ARRAY_REF__//;
                   5597: 
                   5598:   while($string !~ /^__END_ARRAY_REF__/) {
                   5599:       my $value='';
                   5600:       if($string =~ /^__HASH_REF__/) {
                   5601:           ($value, $string)=&str2hashref($string);
                   5602:           if(defined($value->{'error'})) {
                   5603:               $array[0] ='Array reference error';
                   5604:               return (\@array, $string);
                   5605:           }
                   5606:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5607:           ($value, $string)=&str2arrayref($string);
                   5608:           if($value->[0] eq 'Array reference error') {
                   5609:               $array[0] ='Array reference error';
                   5610:               return (\@array, $string);
                   5611:           }
                   5612:       } else {
                   5613: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5614:       }
                   5615:       $string =~ s/^&//;
                   5616: 
                   5617:       push(@array, $value);
1.191     harris41 5618:   }
1.265     albertel 5619: 
                   5620:   $string =~ s/^__END_ARRAY_REF__//;
                   5621: 
                   5622:   return (\@array, $string);
1.168     albertel 5623: }
                   5624: 
1.167     albertel 5625: # -------------------------------------------------------------------Temp Store
                   5626: 
1.168     albertel 5627: sub tmpreset {
                   5628:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5629:   if (!$symb) {
                   5630:     $symb=&symbread();
1.620     albertel 5631:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5632:   }
                   5633:   $symb=escape($symb);
                   5634: 
1.620     albertel 5635:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5636:   $namespace=~s/\//\_/g;
                   5637:   $namespace=~s/\W//g;
                   5638: 
1.620     albertel 5639:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5640:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5641:   if ($domain eq 'public' && $stuname eq 'public') {
                   5642:       $stuname=$ENV{'REMOTE_ADDR'};
                   5643:   }
1.1117    foxr     5644:   my $path=LONCAPA::tempdir();
1.168     albertel 5645:   my %hash;
                   5646:   if (tie(%hash,'GDBM_File',
                   5647: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5648: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5649:     foreach my $key (keys(%hash)) {
1.180     albertel 5650:       if ($key=~ /:$symb/) {
1.168     albertel 5651: 	delete($hash{$key});
                   5652:       }
                   5653:     }
                   5654:   }
                   5655: }
                   5656: 
1.167     albertel 5657: sub tmpstore {
1.168     albertel 5658:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5659: 
                   5660:   if (!$symb) {
                   5661:     $symb=&symbread();
1.620     albertel 5662:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5663:   }
                   5664:   $symb=escape($symb);
                   5665: 
                   5666:   if (!$namespace) {
                   5667:     # I don't think we would ever want to store this for a course.
                   5668:     # it seems this will only be used if we don't have a course.
1.620     albertel 5669:     #$namespace=$env{'request.course.id'};
1.168     albertel 5670:     #if (!$namespace) {
1.620     albertel 5671:       $namespace=$env{'request.state'};
1.168     albertel 5672:     #}
                   5673:   }
                   5674:   $namespace=~s/\//\_/g;
                   5675:   $namespace=~s/\W//g;
1.620     albertel 5676:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5677:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5678:   if ($domain eq 'public' && $stuname eq 'public') {
                   5679:       $stuname=$ENV{'REMOTE_ADDR'};
                   5680:   }
1.168     albertel 5681:   my $now=time;
                   5682:   my %hash;
1.1117    foxr     5683:   my $path=LONCAPA::tempdir();
1.168     albertel 5684:   if (tie(%hash,'GDBM_File',
                   5685: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5686: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5687:     $hash{"version:$symb"}++;
                   5688:     my $version=$hash{"version:$symb"};
                   5689:     my $allkeys=''; 
                   5690:     foreach my $key (keys(%$storehash)) {
                   5691:       $allkeys.=$key.':';
1.591     albertel 5692:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5693:     }
                   5694:     $hash{"$version:$symb:timestamp"}=$now;
                   5695:     $allkeys.='timestamp';
                   5696:     $hash{"$version:keys:$symb"}=$allkeys;
                   5697:     if (untie(%hash)) {
                   5698:       return 'ok';
                   5699:     } else {
                   5700:       return "error:$!";
                   5701:     }
                   5702:   } else {
                   5703:     return "error:$!";
                   5704:   }
                   5705: }
1.167     albertel 5706: 
1.168     albertel 5707: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5708: 
1.168     albertel 5709: sub tmprestore {
                   5710:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5711: 
1.168     albertel 5712:   if (!$symb) {
                   5713:     $symb=&symbread();
1.620     albertel 5714:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5715:   }
                   5716:   $symb=escape($symb);
                   5717: 
1.620     albertel 5718:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5719: 
1.620     albertel 5720:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5721:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5722:   if ($domain eq 'public' && $stuname eq 'public') {
                   5723:       $stuname=$ENV{'REMOTE_ADDR'};
                   5724:   }
1.168     albertel 5725:   my %returnhash;
                   5726:   $namespace=~s/\//\_/g;
                   5727:   $namespace=~s/\W//g;
                   5728:   my %hash;
1.1117    foxr     5729:   my $path=LONCAPA::tempdir();
1.168     albertel 5730:   if (tie(%hash,'GDBM_File',
                   5731: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5732: 	  &GDBM_READER(),0640)) {
1.168     albertel 5733:     my $version=$hash{"version:$symb"};
                   5734:     $returnhash{'version'}=$version;
                   5735:     my $scope;
                   5736:     for ($scope=1;$scope<=$version;$scope++) {
                   5737:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5738:       my @keys=split(/:/,$vkeys);
                   5739:       my $key;
                   5740:       $returnhash{"$scope:keys"}=$vkeys;
                   5741:       foreach $key (@keys) {
1.591     albertel 5742: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5743: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5744:       }
                   5745:     }
1.168     albertel 5746:     if (!(untie(%hash))) {
                   5747:       return "error:$!";
                   5748:     }
                   5749:   } else {
                   5750:     return "error:$!";
                   5751:   }
                   5752:   return %returnhash;
1.167     albertel 5753: }
                   5754: 
1.9       www      5755: # ----------------------------------------------------------------------- Store
                   5756: 
                   5757: sub store {
1.1269    raeburn  5758:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5759:     my $home='';
                   5760: 
1.168     albertel 5761:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5762: 
1.213     www      5763:     $symb=&symbclean($symb);
1.122     albertel 5764:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5765: 
1.620     albertel 5766:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5767:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5768: 
                   5769:     &devalidate($symb,$stuname,$domain);
1.109     www      5770: 
                   5771:     $symb=escape($symb);
1.187     www      5772:     if (!$namespace) { 
1.620     albertel 5773:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5774:           return ''; 
                   5775:        } 
                   5776:     }
1.620     albertel 5777:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5778: 
                   5779:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5780:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5781: 
1.12      www      5782:     my $namevalue='';
1.800     albertel 5783:     foreach my $key (keys(%$storehash)) {
                   5784:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5785:     }
1.12      www      5786:     $namevalue=~s/\&$//;
1.187     www      5787:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5788:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5789: }
                   5790: 
1.47      www      5791: # -------------------------------------------------------------- Critical Store
                   5792: 
                   5793: sub cstore {
1.1269    raeburn  5794:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5795:     my $home='';
                   5796: 
1.168     albertel 5797:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5798: 
1.213     www      5799:     $symb=&symbclean($symb);
1.122     albertel 5800:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5801: 
1.620     albertel 5802:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5803:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5804: 
                   5805:     &devalidate($symb,$stuname,$domain);
1.109     www      5806: 
                   5807:     $symb=escape($symb);
1.187     www      5808:     if (!$namespace) { 
1.620     albertel 5809:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5810:           return ''; 
                   5811:        } 
                   5812:     }
1.620     albertel 5813:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5814: 
                   5815:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5816:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5817: 
1.47      www      5818:     my $namevalue='';
1.800     albertel 5819:     foreach my $key (keys(%$storehash)) {
                   5820:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5821:     }
1.47      www      5822:     $namevalue=~s/\&$//;
1.187     www      5823:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5824:     return critical
1.1269    raeburn  5825:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5826: }
                   5827: 
1.9       www      5828: # --------------------------------------------------------------------- Restore
                   5829: 
                   5830: sub restore {
1.124     www      5831:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5832:     my $home='';
                   5833: 
1.168     albertel 5834:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5835: 
1.122     albertel 5836:     if (!$symb) {
1.1224    raeburn  5837:         return if ($namespace eq 'courserequests');
                   5838:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5839:     } else {
1.1224    raeburn  5840:         unless ($namespace eq 'courserequests') {
                   5841:             $symb=&escape(&symbclean($symb));
                   5842:         }
1.122     albertel 5843:     }
1.188     www      5844:     if (!$namespace) { 
1.620     albertel 5845:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5846:           return ''; 
                   5847:        } 
                   5848:     }
1.620     albertel 5849:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5850:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5851:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5852:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5853: 
1.12      www      5854:     my %returnhash=();
1.800     albertel 5855:     foreach my $line (split(/\&/,$answer)) {
                   5856: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5857:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5858:     }
1.75      www      5859:     my $version;
                   5860:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5861:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5862:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5863:        }
1.75      www      5864:     }
1.13      www      5865:     return %returnhash;
1.34      www      5866: }
                   5867: 
                   5868: # ---------------------------------------------------------- Course Description
1.1118    foxr     5869: #
                   5870: #  
1.34      www      5871: 
                   5872: sub coursedescription {
1.731     albertel 5873:     my ($courseid,$args)=@_;
1.34      www      5874:     $courseid=~s/^\///;
1.49      www      5875:     $courseid=~s/\_/\//g;
1.34      www      5876:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5877:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5878:     my $normalid=$cdomain.'_'.$cnum;
                   5879:     # need to always cache even if we get errors otherwise we keep 
                   5880:     # trying and trying and trying to get the course description.
                   5881:     my %envhash=();
                   5882:     my %returnhash=();
1.731     albertel 5883:     
                   5884:     my $expiretime=600;
                   5885:     if ($env{'request.course.id'} eq $normalid) {
                   5886: 	$expiretime=120;
                   5887:     }
                   5888: 
                   5889:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5890:     if (!$args->{'freshen_cache'}
                   5891: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5892: 	foreach my $key (keys(%env)) {
                   5893: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5894: 	    my ($setting) = $1;
                   5895: 	    $returnhash{$setting} = $env{$key};
                   5896: 	}
                   5897: 	return %returnhash;
                   5898:     }
                   5899: 
1.1118    foxr     5900:     # get the data again
                   5901: 
1.731     albertel 5902:     if (!$args->{'one_time'}) {
                   5903: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5904:     }
1.811     albertel 5905: 
1.34      www      5906:     if ($chome ne 'no_host') {
1.302     albertel 5907:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5908:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5909: 	   my $username = $env{'user.name'}; # Defult username
                   5910: 	   if(defined $args->{'user'}) {
                   5911: 	       $username = $args->{'user'};
                   5912: 	   }
1.129     albertel 5913:            $returnhash{'home'}= $chome;
                   5914: 	   $returnhash{'domain'} = $cdomain;
                   5915: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5916:            if (!defined($returnhash{'type'})) {
                   5917:                $returnhash{'type'} = 'Course';
                   5918:            }
1.130     albertel 5919:            while (my ($name,$value) = each %returnhash) {
1.53      www      5920:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5921:            }
1.270     www      5922:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5923:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5924: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5925:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5926:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5927:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5928:        }
                   5929:     }
1.731     albertel 5930:     if (!$args->{'one_time'}) {
1.949     raeburn  5931: 	&appenv(\%envhash);
1.731     albertel 5932:     }
1.302     albertel 5933:     return %returnhash;
1.461     www      5934: }
                   5935: 
1.1080    raeburn  5936: sub update_released_required {
                   5937:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5938:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5939:         $cid = $env{'request.course.id'};
                   5940:         $cdom = $env{'course.'.$cid.'.domain'};
                   5941:         $cnum = $env{'course.'.$cid.'.num'};
                   5942:         $chome = $env{'course.'.$cid.'.home'};
                   5943:     }
                   5944:     if ($needsrelease) {
                   5945:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5946:         my $needsupdate;
                   5947:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5948:             $needsupdate = 1;
                   5949:         } else {
                   5950:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5951:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5952:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5953:                 $needsupdate = 1;
                   5954:             }
                   5955:         }
                   5956:         if ($needsupdate) {
                   5957:             my %needshash = (
                   5958:                              'internal.releaserequired' => $needsrelease,
                   5959:                             );
                   5960:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5961:             if ($putresult eq 'ok') {
                   5962:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5963:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5964:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5965:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5966:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5967:                 }
                   5968:             }
                   5969:         }
                   5970:     }
                   5971:     return;
                   5972: }
                   5973: 
1.461     www      5974: # -------------------------------------------------See if a user is privileged
                   5975: 
                   5976: sub privileged {
1.1219    raeburn  5977:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5978:     my $now = time;
1.1219    raeburn  5979:     my $roles;
                   5980:     if (ref($possroles) eq 'ARRAY') {
                   5981:         $roles = $possroles; 
                   5982:     } else {
                   5983:         $roles = ['dc','su'];
                   5984:     }
                   5985:     if (ref($possdomains) eq 'ARRAY') {
                   5986:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5987:         foreach my $dom (@{$possdomains}) {
                   5988:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5989:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5990:                 foreach my $role (@{$roles}) {
                   5991:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5992:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5993:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5994:                             return 1 unless (($end && $end < $now) ||
                   5995:                                              ($start && $start > $now));
                   5996:                         }
                   5997:                     }
                   5998:                 }
                   5999:             }
                   6000:         }
                   6001:     } else {
                   6002:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6003:         my $now = time;
1.1170    droeschl 6004: 
1.1275    musolffc 6005:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6006:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6007:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6008:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6009:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6010:             }
1.1219    raeburn  6011:         }
                   6012:     }
                   6013:     return 0;
                   6014: }
1.1170    droeschl 6015: 
1.1219    raeburn  6016: sub privileged_by_domain {
                   6017:     my ($domains,$roles) = @_;
                   6018:     my %privileged = ();
                   6019:     my $cachetime = 60*60*24;
                   6020:     my $now = time;
                   6021:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6022:         return %privileged;
                   6023:     }
                   6024:     foreach my $dom (@{$domains}) {
                   6025:         next if (ref($privileged{$dom}) eq 'HASH');
                   6026:         my $needroles;
                   6027:         foreach my $role (@{$roles}) {
                   6028:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6029:             if (defined($cached)) {
                   6030:                 if (ref($result) eq 'HASH') {
                   6031:                     $privileged{$dom}{$role} = $result;
                   6032:                 }
                   6033:             } else {
                   6034:                 $needroles = 1;
                   6035:             }
                   6036:         }
                   6037:         if ($needroles) {
                   6038:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6039:             $privileged{$dom} = {};
                   6040:             foreach my $server (keys(%dompersonnel)) {
                   6041:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6042:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6043:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6044:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6045:                         next if ($end && $end < $now);
                   6046:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6047:                             $dompersonnel{$server}{$item};
                   6048:                     }
                   6049:                 }
                   6050:             }
                   6051:             if (ref($privileged{$dom}) eq 'HASH') {
                   6052:                 foreach my $role (@{$roles}) {
                   6053:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6054:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6055:                     } else {
                   6056:                         my %hash = ();
                   6057:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6058:                     }
                   6059:                 }
                   6060:             }
                   6061:         }
                   6062:     }
                   6063:     return %privileged;
1.9       www      6064: }
1.1       albertel 6065: 
1.103     harris41 6066: # -------------------------------------------------------- Get user privileges
1.11      www      6067: 
                   6068: sub rolesinit {
1.1169    droeschl 6069:     my ($domain, $username) = @_;
                   6070:     my %userroles = ('user.login.time' => time);
                   6071:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6072: 
                   6073:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6074:     # also, blocking can be triggered by an activating timer
                   6075:     # it's saved in the user's %env.
                   6076:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6077:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6078:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6079:         %timerintchk, %timerintenv);
                   6080: 
1.1162    raeburn  6081:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6082:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6083:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6084:     }
1.1169    droeschl 6085: 
1.1162    raeburn  6086:     foreach my $key (keys(%timerinterval)) {
                   6087:         my ($cid,$rest) = split(/\0/,$key);
                   6088:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6089:     }
1.1169    droeschl 6090: 
1.11      www      6091:     my %allroles=();
1.1162    raeburn  6092:     my %allgroups=();
1.11      www      6093: 
1.1274    raeburn  6094:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6095:         my $role = $rolesdump{$area};
                   6096:         $area =~ s/\_\w\w$//;
                   6097: 
                   6098:         my ($trole, $tend, $tstart, $group_privs);
                   6099: 
                   6100:         if ($role =~ /^cr/) {
                   6101:         # Custom role, defined by a user 
                   6102:         # e.g., user.role.cr/msu/smith/mynewrole
                   6103:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6104:                 $trole = $1;
                   6105:                 ($tend, $tstart) = split('_', $2);
                   6106:             } else {
                   6107:                 $trole = $role;
                   6108:             }
                   6109:         } elsif ($role =~ m|^gr/|) {
                   6110:         # Role of member in a group, defined within a course/community
                   6111:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6112:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6113:             next if $tstart eq '-1';
                   6114:             ($trole, $group_privs) = split(/\//, $trole);
                   6115:             $group_privs = &unescape($group_privs);
                   6116:         } else {
                   6117:         # Just a normal role, defined in roles.tab
                   6118:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6119:         }
                   6120: 
                   6121:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6122:                  $username);
                   6123:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6124: 
                   6125:         # role expired or not available yet?
                   6126:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6127:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6128: 
                   6129:         next if $area eq '' or $trole eq '';
                   6130: 
                   6131:         my $spec = "$trole.$area";
                   6132:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6133: 
                   6134:         if ($trole =~ /^cr\//) {
                   6135:         # Custom role, defined by a user
                   6136:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6137:         } elsif ($trole eq 'gr') {
                   6138:         # Role of a member in a group, defined within a course/community
                   6139:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6140:             next;
                   6141:         } else {
                   6142:         # Normal role, defined in roles.tab
                   6143:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6144:         }
                   6145: 
                   6146:         my $cid = $tdomain.'_'.$trest;
                   6147:         unless ($firstaccchk{$cid}) {
                   6148:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6149:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6150:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6151:                         $coursetimerstarts{$cid}{$item}; 
                   6152:                 }
                   6153:             }
                   6154:             $firstaccchk{$cid} = 1;
                   6155:         }
                   6156:         unless ($timerintchk{$cid}) {
                   6157:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6158:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6159:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6160:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6161:                 }
1.12      www      6162:             }
1.1169    droeschl 6163:             $timerintchk{$cid} = 1;
1.191     harris41 6164:         }
1.11      www      6165:     }
1.1169    droeschl 6166: 
1.1341    raeburn  6167:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6168:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6169:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6170:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6171: 
1.1162    raeburn  6172:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6173: }
                   6174: 
1.567     raeburn  6175: sub set_arearole {
1.1215    raeburn  6176:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6177:     unless ($nolog) {
1.567     raeburn  6178: # log the associated role with the area
1.1215    raeburn  6179:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6180:     }
1.743     albertel 6181:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6182: }
                   6183: 
                   6184: sub custom_roleprivs {
                   6185:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6186:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6187:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6188:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6189:         my ($rdummy,$roledef)=
                   6190:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6191:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6192:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6193:             if (defined($syspriv)) {
1.1043    raeburn  6194:                 if ($trest =~ /^$match_community$/) {
                   6195:                     $syspriv =~ s/bre\&S//; 
                   6196:                 }
1.567     raeburn  6197:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6198:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6199:             }
                   6200:             if ($tdomain ne '') {
                   6201:                 if (defined($dompriv)) {
                   6202:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6203:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6204:                 }
                   6205:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6206:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6207:                         my $rolename = $1;
                   6208:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6209:                     }
1.567     raeburn  6210:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6211:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6212:                 }
                   6213:             }
                   6214:         }
                   6215:     }
                   6216: }
                   6217: 
1.1332    raeburn  6218: sub course_adhocrole_privs {
                   6219:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6220:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6221:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6222:         my (%currprivs,%storeprivs);
                   6223:         foreach my $item (split(/:/,$coursepriv)) {
                   6224:             my ($priv,$restrict) = split(/\&/,$item);
                   6225:             $currprivs{$priv} = $restrict;
                   6226:         }
                   6227:         my (%possadd,%possremove,%full);
                   6228:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6229:             my ($priv,$restrict)=split(/\&/,$item);
                   6230:             $full{$priv} = $restrict;
                   6231:         }
                   6232:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6233:              next if ($item eq '');
                   6234:              my ($rule,$rest) = split(/=/,$item);
                   6235:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6236:              foreach my $priv (split(/:/,$rest)) {
                   6237:                  if ($priv ne '') {
                   6238:                      if ($rule eq 'off') {
                   6239:                          $possremove{$priv} = 1;
                   6240:                      } else {
                   6241:                          $possadd{$priv} = 1;
                   6242:                      }
                   6243:                  }
                   6244:              }
                   6245:          }
                   6246:          foreach my $priv (sort(keys(%full))) {
                   6247:              if (exists($currprivs{$priv})) {
                   6248:                  unless (exists($possremove{$priv})) {
                   6249:                      $storeprivs{$priv} = $currprivs{$priv};
                   6250:                  }
                   6251:              } elsif (exists($possadd{$priv})) {
                   6252:                  $storeprivs{$priv} = $full{$priv};
                   6253:              }
                   6254:          }
                   6255:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6256:      }
                   6257:      return $coursepriv;
                   6258: }
                   6259: 
1.678     raeburn  6260: sub group_roleprivs {
                   6261:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6262:     my $access = 1;
                   6263:     my $now = time;
                   6264:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6265:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6266:     if ($access) {
1.811     albertel 6267:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6268:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6269:     }
                   6270: }
1.567     raeburn  6271: 
                   6272: sub standard_roleprivs {
                   6273:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6274:     if (defined($pr{$trole.':s'})) {
                   6275:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6276:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6277:     }
                   6278:     if ($tdomain ne '') {
                   6279:         if (defined($pr{$trole.':d'})) {
                   6280:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6281:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6282:         }
                   6283:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6284:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6285:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6286:         }
                   6287:     }
                   6288: }
                   6289: 
                   6290: sub set_userprivs {
1.1064    raeburn  6291:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6292:     my $author=0;
                   6293:     my $adv=0;
1.1341    raeburn  6294:     my $rar=0;
1.678     raeburn  6295:     my %grouproles = ();
                   6296:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6297:         my @groupkeys; 
1.1000    raeburn  6298:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6299:             push(@groupkeys,$role);
                   6300:         }
                   6301:         if (ref($groups_roles) eq 'HASH') {
                   6302:             foreach my $key (keys(%{$groups_roles})) {
                   6303:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6304:                     push(@groupkeys,$key);
                   6305:                 }
                   6306:             }
                   6307:         }
                   6308:         if (@groupkeys > 0) {
                   6309:             foreach my $role (@groupkeys) {
                   6310:                 my ($trole,$area,$sec,$extendedarea);
                   6311:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6312:                     $trole = $1;
                   6313:                     $area = $2;
                   6314:                     $sec = $3;
                   6315:                     $extendedarea = $area.$sec;
                   6316:                     if (exists($$allgroups{$area})) {
                   6317:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6318:                             my $spec = $trole.'.'.$extendedarea;
                   6319:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6320:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6321:                         }
1.678     raeburn  6322:                     }
                   6323:                 }
                   6324:             }
                   6325:         }
                   6326:     }
1.800     albertel 6327:     foreach my $group (keys(%grouproles)) {
                   6328:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6329:     }
1.800     albertel 6330:     foreach my $role (keys(%{$allroles})) {
                   6331:         my %thesepriv;
1.941     raeburn  6332:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6333:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6334:             if ($item ne '') {
                   6335:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6336:                 if ($restrictions eq '') {
                   6337:                     $thesepriv{$privilege}='F';
                   6338:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6339:                     $thesepriv{$privilege}.=$restrictions;
                   6340:                 }
                   6341:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6342:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6343:             }
                   6344:         }
                   6345:         my $thesestr='';
1.1104    raeburn  6346:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6347: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6348: 	}
                   6349:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6350:     }
1.1341    raeburn  6351:     return ($author,$adv,$rar);
1.567     raeburn  6352: }
                   6353: 
1.994     raeburn  6354: sub role_status {
1.1104    raeburn  6355:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6356:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6357:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6358:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6359:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6360:             $$where = '/'.$two;
1.994     raeburn  6361:             $$trolecode=$$role.'.'.$$where;
                   6362:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6363:             $$tstatus='is';
1.1104    raeburn  6364:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6365:                 $$tstatus='future';
1.1034    raeburn  6366:                 if ($$tstart<$now) {
                   6367:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6368:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6369:                             my (%allroles,%allgroups,$group_privs,
                   6370:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6371:                             my %userroles = (
                   6372:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6373:                             );
1.1064    raeburn  6374:                             @rolecodes = ('cm'); 
1.1002    raeburn  6375:                             my $spec=$$role.'.'.$$where;
                   6376:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6377:                             if ($$role =~ /^cr\//) {
                   6378:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6379:                                 push(@rolecodes,'cr');
1.1002    raeburn  6380:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6381:                                 push(@rolecodes,$$role);
1.1002    raeburn  6382:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6383:                                                     $env{'user.name'});
1.1064    raeburn  6384:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6385:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6386:                                 $group_privs = &unescape($group_privs);
                   6387:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6388:                                 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  6389:                                 &get_groups_roles($tdomain,$trest,
                   6390:                                                   \%course_roles,\@rolecodes,
                   6391:                                                   \%groups_roles);
1.1002    raeburn  6392:                             } else {
1.1064    raeburn  6393:                                 push(@rolecodes,$$role);
1.1002    raeburn  6394:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6395:                             }
1.1341    raeburn  6396:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6397:                                                                    \%groups_roles);
1.1064    raeburn  6398:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6399:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6400:                         }
                   6401:                     }
1.1034    raeburn  6402:                     $$tstatus = 'is';
1.1002    raeburn  6403:                 }
1.994     raeburn  6404:             }
                   6405:             if ($$tend) {
1.1104    raeburn  6406:                 if ($$tend<$update) {
1.994     raeburn  6407:                     $$tstatus='expired';
                   6408:                 } elsif ($$tend<$now) {
                   6409:                     $$tstatus='will_not';
                   6410:                 }
                   6411:             }
                   6412:         }
                   6413:     }
                   6414: }
                   6415: 
1.1104    raeburn  6416: sub get_groups_roles {
                   6417:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6418:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6419:                   (ref($rolecodes) eq 'ARRAY') && 
                   6420:                   (ref($groups_roles) eq 'HASH')); 
                   6421:     if (keys(%{$cdom_courseroles}) > 0) {
                   6422:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6423:         if ($cdom ne '' && $cnum ne '') {
                   6424:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6425:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6426:                     my $crsrole = $1;
                   6427:                     my $crssec = $2;
                   6428:                     if ($crsrole =~ /^cr/) {
                   6429:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6430:                             push(@{$rolecodes},'cr');
                   6431:                         }
                   6432:                     } else {
                   6433:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6434:                             push(@{$rolecodes},$crsrole);
                   6435:                         }
                   6436:                     }
                   6437:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6438:                     if ($crssec ne '') {
                   6439:                         $rolekey .= "/$crssec";
                   6440:                     }
                   6441:                     $rolekey .= './';
                   6442:                     $groups_roles->{$rolekey} = $rolecodes;
                   6443:                 }
                   6444:             }
                   6445:         }
                   6446:     }
                   6447:     return;
                   6448: }
                   6449: 
                   6450: sub delete_env_groupprivs {
                   6451:     my ($where,$courseroles,$possroles) = @_;
                   6452:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6453:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6454:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6455:         %{$courseroles->{$udom}} =
                   6456:             &get_my_roles('','','userroles',['active'],
                   6457:                           $possroles,[$udom],1);
                   6458:     }
                   6459:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6460:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6461:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6462:             my $area = '/'.$cdom.'/'.$cnum;
                   6463:             my $privkey = "user.priv.$crsrole.$area";
                   6464:             if ($crssec ne '') {
                   6465:                 $privkey .= '/'.$crssec;
                   6466:             }
                   6467:             $privkey .= ".$area/$group";
                   6468:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6469:         }
                   6470:     }
                   6471:     return;
                   6472: }
                   6473: 
1.994     raeburn  6474: sub check_adhoc_privs {
1.1329    raeburn  6475:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6476:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6477:     if ($sec) {
                   6478:         $cckey .= '/'.$sec;
                   6479:     } 
1.1185    raeburn  6480:     my $setprivs;
1.994     raeburn  6481:     if ($env{$cckey}) {
                   6482:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6483:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6484:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6485:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6486:             $setprivs = 1;
1.994     raeburn  6487:         }
                   6488:     } else {
1.1330    raeburn  6489:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6490:         $setprivs = 1;
1.994     raeburn  6491:     }
1.1185    raeburn  6492:     return $setprivs;
1.994     raeburn  6493: }
                   6494: 
                   6495: sub set_adhoc_privileges {
1.1326    raeburn  6496: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6497:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6498:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6499:     if ($sec ne '') {
                   6500:         $area .= '/'.$sec;
                   6501:     }
1.994     raeburn  6502:     my $spec = $role.'.'.$area;
                   6503:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6504:                                   $env{'user.name'},1);
1.1326    raeburn  6505:     my %rolehash = ();
1.1332    raeburn  6506:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6507:         my $rolename = $1;
1.1326    raeburn  6508:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6509:         my %domdef = &get_domain_defaults($dcdom);
                   6510:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6511:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6512:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6513:             }
                   6514:         }
1.1326    raeburn  6515:     } else {
                   6516:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6517:     }
1.1341    raeburn  6518:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6519:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6520:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6521:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6522:         &appenv( {'request.role'        => $spec,
                   6523:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6524:                   'request.course.sec'  => $sec,
1.1088    raeburn  6525:                  }
                   6526:                );
                   6527:         my $tadv=0;
                   6528:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6529:         &appenv({'request.role.adv'    => $tadv});
                   6530:     }
1.994     raeburn  6531: }
                   6532: 
1.12      www      6533: # --------------------------------------------------------------- get interface
                   6534: 
                   6535: sub get {
1.131     albertel 6536:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6537:    my $items='';
1.800     albertel 6538:    foreach my $item (@$storearr) {
                   6539:        $items.=&escape($item).'&';
1.191     harris41 6540:    }
1.12      www      6541:    $items=~s/\&$//;
1.620     albertel 6542:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6543:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6544:    my $uhome=&homeserver($uname,$udomain);
                   6545: 
1.133     albertel 6546:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6547:    my @pairs=split(/\&/,$rep);
1.273     albertel 6548:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6549:      return @pairs;
                   6550:    }
1.15      www      6551:    my %returnhash=();
1.42      www      6552:    my $i=0;
1.800     albertel 6553:    foreach my $item (@$storearr) {
                   6554:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6555:       $i++;
1.191     harris41 6556:    }
1.15      www      6557:    return %returnhash;
1.27      www      6558: }
                   6559: 
                   6560: # --------------------------------------------------------------- del interface
                   6561: 
                   6562: sub del {
1.133     albertel 6563:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6564:    my $items='';
1.800     albertel 6565:    foreach my $item (@$storearr) {
                   6566:        $items.=&escape($item).'&';
1.191     harris41 6567:    }
1.984     neumanie 6568: 
1.27      www      6569:    $items=~s/\&$//;
1.620     albertel 6570:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6571:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6572:    my $uhome=&homeserver($uname,$udomain);
                   6573:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6574: }
                   6575: 
                   6576: # -------------------------------------------------------------- dump interface
                   6577: 
1.1180    droeschl 6578: sub unserialize {
                   6579:     my ($rep, $escapedkeys) = @_;
                   6580: 
                   6581:     return {} if $rep =~ /^error/;
                   6582: 
                   6583:     my %returnhash=();
1.1252    raeburn  6584: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6585: 	    my ($key, $value) = split(/=/, $item, 2);
                   6586: 	    $key = unescape($key) unless $escapedkeys;
                   6587: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6588: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6589: 	}
                   6590:     #return %returnhash;
                   6591:     return \%returnhash;
                   6592: }        
                   6593: 
                   6594: # see Lond::dump_with_regexp
                   6595: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6596: sub dump {
1.1180    droeschl 6597:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6598:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6599:     if (!$uname) { $uname=$env{'user.name'}; }
                   6600:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6601: 
1.1266    raeburn  6602:     if ($regexp) {
                   6603:         $regexp=&escape($regexp);
                   6604:     } else {
                   6605:         $regexp='.';
                   6606:     }
1.1180    droeschl 6607:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6608:         # user is hosted on this machine
1.1266    raeburn  6609:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6610:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6611:         return %{unserialize($reply, $escapedkeys)};
                   6612:     }
1.1166    raeburn  6613:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6614:     my @pairs=split(/\&/,$rep);
                   6615:     my %returnhash=();
1.1098    foxr     6616:     if (!($rep =~ /^error/ )) {
                   6617: 	foreach my $item (@pairs) {
                   6618: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6619:         $key = unescape($key) unless $escapedkeys;
                   6620:         #$key = &unescape($key);
1.1098    foxr     6621: 	    next if ($key =~ /^error: 2 /);
                   6622: 	    $returnhash{$key}=&thaw_unescape($value);
                   6623: 	}
1.755     albertel 6624:     }
                   6625:     return %returnhash;
1.407     www      6626: }
                   6627: 
1.1098    foxr     6628: 
1.717     albertel 6629: # --------------------------------------------------------- dumpstore interface
                   6630: 
                   6631: sub dumpstore {
                   6632:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6633:    # same as dump but keys must be escaped. They may contain colon separated
                   6634:    # lists of values that may themself contain colons (e.g. symbs).
                   6635:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6636: }
                   6637: 
1.407     www      6638: # -------------------------------------------------------------- keys interface
                   6639: 
                   6640: sub getkeys {
                   6641:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6642:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6643:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6644:    my $uhome=&homeserver($uname,$udomain);
                   6645:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6646:    my @keyarray=();
1.800     albertel 6647:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6648:       next if ($key =~ /^error: 2 /);
1.800     albertel 6649:       push(@keyarray,&unescape($key));
1.407     www      6650:    }
                   6651:    return @keyarray;
1.318     matthew  6652: }
                   6653: 
1.319     matthew  6654: # --------------------------------------------------------------- currentdump
                   6655: sub currentdump {
1.328     matthew  6656:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6657:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6658:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6659:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6660:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6661:    my $rep;
                   6662: 
                   6663:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6664:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6665:                    $courseid)));
                   6666:    } else {
                   6667:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6668:    }
                   6669: 
1.318     matthew  6670:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6671:    #
1.318     matthew  6672:    my %returnhash=();
1.319     matthew  6673:    #
1.1343    raeburn  6674:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6675:        # an old lond will not know currentdump
                   6676:        # Do a dump and make it look like a currentdump
1.822     albertel 6677:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6678:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6679:        my %hash = @tmp;
                   6680:        @tmp=();
1.424     matthew  6681:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6682:    } else {
                   6683:        my @pairs=split(/\&/,$rep);
1.800     albertel 6684:        foreach my $pair (@pairs) {
                   6685:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6686:            my ($symb,$param) = split(/:/,$key);
                   6687:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6688:                                                         &thaw_unescape($value);
1.319     matthew  6689:        }
1.191     harris41 6690:    }
1.12      www      6691:    return %returnhash;
1.424     matthew  6692: }
                   6693: 
                   6694: sub convert_dump_to_currentdump{
                   6695:     my %hash = %{shift()};
                   6696:     my %returnhash;
                   6697:     # Code ripped from lond, essentially.  The only difference
                   6698:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6699:     # we might run in to problems with parameter names =~ /^v\./
                   6700:     while (my ($key,$value) = each(%hash)) {
                   6701:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6702: 	$symb  = &unescape($symb);
                   6703: 	$param = &unescape($param);
1.424     matthew  6704:         next if ($v eq 'version' || $symb eq 'keys');
                   6705:         next if (exists($returnhash{$symb}) &&
                   6706:                  exists($returnhash{$symb}->{$param}) &&
                   6707:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6708:         $returnhash{$symb}->{$param}=$value;
                   6709:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6710:     }
                   6711:     #
                   6712:     # Remove all of the keys in the hashes which keep track of
                   6713:     # the version of the parameter.
                   6714:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6715:         # use a foreach because we are going to delete from the hash.
                   6716:         foreach my $key (keys(%$param_hash)) {
                   6717:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6718:         }
                   6719:     }
                   6720:     return \%returnhash;
1.12      www      6721: }
                   6722: 
1.627     albertel 6723: # ------------------------------------------------------ critical inc interface
                   6724: 
                   6725: sub cinc {
                   6726:     return &inc(@_,'critical');
                   6727: }
                   6728: 
1.449     matthew  6729: # --------------------------------------------------------------- inc interface
                   6730: 
                   6731: sub inc {
1.627     albertel 6732:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6733:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6734:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6735:     my $uhome=&homeserver($uname,$udomain);
                   6736:     my $items='';
                   6737:     if (! ref($store)) {
                   6738:         # got a single value, so use that instead
                   6739:         $items = &escape($store).'=&';
                   6740:     } elsif (ref($store) eq 'SCALAR') {
                   6741:         $items = &escape($$store).'=&';        
                   6742:     } elsif (ref($store) eq 'ARRAY') {
                   6743:         $items = join('=&',map {&escape($_);} @{$store});
                   6744:     } elsif (ref($store) eq 'HASH') {
                   6745:         while (my($key,$value) = each(%{$store})) {
                   6746:             $items.= &escape($key).'='.&escape($value).'&';
                   6747:         }
                   6748:     }
                   6749:     $items=~s/\&$//;
1.627     albertel 6750:     if ($critical) {
                   6751: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6752:     } else {
                   6753: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6754:     }
1.449     matthew  6755: }
                   6756: 
1.12      www      6757: # --------------------------------------------------------------- put interface
                   6758: 
                   6759: sub put {
1.134     albertel 6760:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6761:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6762:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6763:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6764:    my $items='';
1.800     albertel 6765:    foreach my $item (keys(%$storehash)) {
                   6766:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6767:    }
1.12      www      6768:    $items=~s/\&$//;
1.134     albertel 6769:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6770: }
                   6771: 
1.631     albertel 6772: # ------------------------------------------------------------ newput interface
                   6773: 
                   6774: sub newput {
                   6775:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6776:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6777:    if (!$uname) { $uname=$env{'user.name'}; }
                   6778:    my $uhome=&homeserver($uname,$udomain);
                   6779:    my $items='';
                   6780:    foreach my $key (keys(%$storehash)) {
                   6781:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6782:    }
                   6783:    $items=~s/\&$//;
                   6784:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6785: }
                   6786: 
                   6787: # ---------------------------------------------------------  putstore interface
                   6788: 
1.524     raeburn  6789: sub putstore {
1.1269    raeburn  6790:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6791:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6792:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6793:    my $uhome=&homeserver($uname,$udomain);
                   6794:    my $items='';
1.715     albertel 6795:    foreach my $key (keys(%$storehash)) {
                   6796:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6797:    }
1.715     albertel 6798:    $items=~s/\&$//;
1.716     albertel 6799:    my $esc_symb=&escape($symb);
                   6800:    my $esc_v=&escape($version);
1.715     albertel 6801:    my $reply =
1.716     albertel 6802:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6803: 	      $uhome);
1.1269    raeburn  6804:    if (($tolog) && ($reply eq 'ok')) {
                   6805:        my $namevalue='';
                   6806:        foreach my $key (keys(%{$storehash})) {
                   6807:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6808:        }
                   6809:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6810:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6811:                      '&version='.$esc_v.
                   6812:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6813:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6814:    }
1.715     albertel 6815:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6816:        # gfall back to way things use to be done
1.715     albertel 6817:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6818: 			    $uname);
1.524     raeburn  6819:    }
1.715     albertel 6820:    return $reply;
                   6821: }
                   6822: 
                   6823: sub old_putstore {
1.716     albertel 6824:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6825:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6826:     if (!$uname) { $uname=$env{'user.name'}; }
                   6827:     my $uhome=&homeserver($uname,$udomain);
                   6828:     my %newstorehash;
1.800     albertel 6829:     foreach my $item (keys(%$storehash)) {
                   6830: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6831: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6832:     }
                   6833:     my $items='';
                   6834:     my %allitems = ();
1.800     albertel 6835:     foreach my $item (keys(%newstorehash)) {
                   6836: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6837: 	    my $key = $1.':keys:'.$2;
                   6838: 	    $allitems{$key} .= $3.':';
                   6839: 	}
1.800     albertel 6840: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6841:     }
1.800     albertel 6842:     foreach my $item (keys(%allitems)) {
                   6843: 	$allitems{$item} =~ s/\:$//;
                   6844: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6845:     }
                   6846:     $items=~s/\&$//;
                   6847:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6848: }
                   6849: 
1.47      www      6850: # ------------------------------------------------------ critical put interface
                   6851: 
                   6852: sub cput {
1.134     albertel 6853:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6854:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6855:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6856:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6857:    my $items='';
1.800     albertel 6858:    foreach my $item (keys(%$storehash)) {
                   6859:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6860:    }
1.47      www      6861:    $items=~s/\&$//;
1.134     albertel 6862:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6863: }
                   6864: 
                   6865: # -------------------------------------------------------------- eget interface
                   6866: 
                   6867: sub eget {
1.133     albertel 6868:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6869:    my $items='';
1.800     albertel 6870:    foreach my $item (@$storearr) {
                   6871:        $items.=&escape($item).'&';
1.191     harris41 6872:    }
1.12      www      6873:    $items=~s/\&$//;
1.620     albertel 6874:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6875:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6876:    my $uhome=&homeserver($uname,$udomain);
                   6877:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6878:    my @pairs=split(/\&/,$rep);
                   6879:    my %returnhash=();
1.42      www      6880:    my $i=0;
1.800     albertel 6881:    foreach my $item (@$storearr) {
                   6882:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6883:       $i++;
1.191     harris41 6884:    }
1.12      www      6885:    return %returnhash;
                   6886: }
                   6887: 
1.667     albertel 6888: # ------------------------------------------------------------ tmpput interface
                   6889: sub tmpput {
1.802     raeburn  6890:     my ($storehash,$server,$context)=@_;
1.667     albertel 6891:     my $items='';
1.800     albertel 6892:     foreach my $item (keys(%$storehash)) {
                   6893: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6894:     }
                   6895:     $items=~s/\&$//;
1.802     raeburn  6896:     if (defined($context)) {
                   6897:         $items .= ':'.&escape($context);
                   6898:     }
1.667     albertel 6899:     return &reply("tmpput:$items",$server);
                   6900: }
                   6901: 
                   6902: # ------------------------------------------------------------ tmpget interface
                   6903: sub tmpget {
1.688     albertel 6904:     my ($token,$server)=@_;
                   6905:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6906:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6907:     my %returnhash;
1.1328    raeburn  6908:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6909:         return %returnhash;
                   6910:     }
1.667     albertel 6911:     foreach my $item (split(/\&/,$rep)) {
                   6912: 	my ($key,$value)=split(/=/,$item);
                   6913: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6914:     }
                   6915:     return %returnhash;
                   6916: }
                   6917: 
1.1113    raeburn  6918: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6919: sub tmpdel {
                   6920:     my ($token,$server)=@_;
                   6921:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6922:     return &reply("tmpdel:$token",$server);
                   6923: }
                   6924: 
1.1198    raeburn  6925: # ------------------------------------------------------------ get_timebased_id 
                   6926: 
                   6927: sub get_timebased_id {
                   6928:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6929:         $maxtries) = @_;
                   6930:     my ($newid,$error,$dellock);
                   6931:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6932:         return ('','ok','invalid call to get suffix');
                   6933:     }
                   6934: 
                   6935: # set defaults for any optional args for which values were not supplied
                   6936:     if ($who eq '') {
                   6937:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6938:     }
                   6939:     if (!$locktries) {
                   6940:         $locktries = 3;
                   6941:     }
                   6942:     if (!$maxtries) {
                   6943:         $maxtries = 10;
                   6944:     }
                   6945:     
                   6946:     if (($cdom eq '') || ($cnum eq '')) {
                   6947:         if ($env{'request.course.id'}) {
                   6948:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6949:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6950:         }
                   6951:         if (($cdom eq '') || ($cnum eq '')) {
                   6952:             return ('','ok','call to get suffix not in course context');
                   6953:         }
                   6954:     }
                   6955: 
                   6956: # construct locking item
                   6957:     my $lockhash = {
                   6958:                       $prefix."\0".'locked_'.$keyid => $who,
                   6959:                    };
                   6960:     my $tries = 0;
                   6961: 
                   6962: # attempt to get lock on nohist_$namespace file
                   6963:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6964:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6965:         $tries ++;
                   6966:         sleep 1;
                   6967:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6968:     }
                   6969: 
                   6970: # attempt to get unique identifier, based on current timestamp
                   6971:     if ($gotlock eq 'ok') {
                   6972:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6973:         my $id = time;
                   6974:         $newid = $id;
1.1268    raeburn  6975:         if ($idtype eq 'addcode') {
                   6976:             $newid .= &sixnum_code();
                   6977:         }
1.1198    raeburn  6978:         my $idtries = 0;
                   6979:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6980:             if ($idtype eq 'concat') {
                   6981:                 $newid = $id.$idtries;
1.1268    raeburn  6982:             } elsif ($idtype eq 'addcode') {
                   6983:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6984:             } else {
                   6985:                 $newid ++;
                   6986:             }
                   6987:             $idtries ++;
                   6988:         }
                   6989:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6990:             my %new_item =  (
                   6991:                               $prefix."\0".$newid => $who,
                   6992:                             );
                   6993:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6994:                                                  $cdom,$cnum);
                   6995:             if ($putresult ne 'ok') {
                   6996:                 undef($newid);
                   6997:                 $error = 'error saving new item: '.$putresult;
                   6998:             }
                   6999:         } else {
1.1268    raeburn  7000:              undef($newid);
1.1198    raeburn  7001:              $error = ('error: no unique suffix available for the new item ');
                   7002:         }
                   7003: #  remove lock
                   7004:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7005:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7006:     } else {
                   7007:         $error = "error: could not obtain lockfile\n";
                   7008:         $dellock = 'ok';
1.1276    raeburn  7009:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7010:             $dellock = 'nolock';
                   7011:         }
1.1198    raeburn  7012:     }
                   7013:     return ($newid,$dellock,$error);
                   7014: }
                   7015: 
1.1268    raeburn  7016: sub sixnum_code {
                   7017:     my $code;
                   7018:     for (0..6) {
                   7019:         $code .= int( rand(9) );
                   7020:     }
                   7021:     return $code;
                   7022: }
                   7023: 
1.765     albertel 7024: # -------------------------------------------------- portfolio access checking
                   7025: 
                   7026: sub portfolio_access {
1.1270    raeburn  7027:     my ($requrl,$clientip) = @_;
1.765     albertel 7028:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7029:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7030:     if ($result) {
                   7031:         my %setters;
                   7032:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7033:             my ($startblock,$endblock) =
                   7034:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7035:             if ($startblock && $endblock) {
                   7036:                 return 'B';
                   7037:             }
                   7038:         } else {
                   7039:             my ($startblock,$endblock) =
                   7040:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7041:             if ($startblock && $endblock) {
                   7042:                 return 'B';
                   7043:             }
                   7044:         }
                   7045:     }
1.765     albertel 7046:     if ($result eq 'ok') {
1.766     albertel 7047:        return 'F';
1.765     albertel 7048:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7049:        return 'A';
1.765     albertel 7050:     }
1.766     albertel 7051:     return '';
1.765     albertel 7052: }
                   7053: 
                   7054: sub get_portfolio_access {
1.1270    raeburn  7055:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7056: 
                   7057:     if (!ref($access_hash)) {
                   7058: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7059: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7060: 						   $file_name);
                   7061: 	$access_hash = $access_controls{$file_name};
                   7062:     }
                   7063: 
1.1270    raeburn  7064:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7065:     my $now = time;
                   7066:     if (ref($access_hash) eq 'HASH') {
                   7067:         foreach my $key (keys(%{$access_hash})) {
                   7068:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7069:             if ($start > $now) {
                   7070:                 next;
                   7071:             }
                   7072:             if ($end && $end<$now) {
                   7073:                 next;
                   7074:             }
                   7075:             if ($scope eq 'public') {
                   7076:                 $public = $key;
                   7077:                 last;
                   7078:             } elsif ($scope eq 'guest') {
                   7079:                 $guest = $key;
                   7080:             } elsif ($scope eq 'domains') {
                   7081:                 push(@domains,$key);
                   7082:             } elsif ($scope eq 'users') {
                   7083:                 push(@users,$key);
                   7084:             } elsif ($scope eq 'course') {
                   7085:                 push(@courses,$key);
                   7086:             } elsif ($scope eq 'group') {
                   7087:                 push(@groups,$key);
1.1270    raeburn  7088:             } elsif ($scope eq 'ip') {
                   7089:                 push(@ips,$key);
1.765     albertel 7090:             }
                   7091:         }
                   7092:         if ($public) {
                   7093:             return 'ok';
1.1270    raeburn  7094:         } elsif (@ips > 0) {
                   7095:             my $allowed;
                   7096:             foreach my $ipkey (@ips) {
                   7097:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7098:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7099:                         $allowed = 1;
                   7100:                         last; 
                   7101:                     }
                   7102:                 }
                   7103:             }
                   7104:             if ($allowed) {
                   7105:                 return 'ok';
                   7106:             }
1.765     albertel 7107:         }
                   7108:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7109:             if ($guest) {
                   7110:                 return $guest;
                   7111:             }
                   7112:         } else {
                   7113:             if (@domains > 0) {
                   7114:                 foreach my $domkey (@domains) {
                   7115:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7116:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7117:                             return 'ok';
                   7118:                         }
                   7119:                     }
                   7120:                 }
                   7121:             }
                   7122:             if (@users > 0) {
                   7123:                 foreach my $userkey (@users) {
1.865     raeburn  7124:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7125:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7126:                             if (ref($item) eq 'HASH') {
                   7127:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7128:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7129:                                     return 'ok';
                   7130:                                 }
                   7131:                             }
                   7132:                         }
                   7133:                     } 
1.765     albertel 7134:                 }
                   7135:             }
                   7136:             my %roleshash;
                   7137:             my @courses_and_groups = @courses;
                   7138:             push(@courses_and_groups,@groups); 
                   7139:             if (@courses_and_groups > 0) {
                   7140:                 my (%allgroups,%allroles); 
                   7141:                 my ($start,$end,$role,$sec,$group);
                   7142:                 foreach my $envkey (%env) {
1.1060    raeburn  7143:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7144:                         my $cid = $2.'_'.$3; 
                   7145:                         if ($1 eq 'gr') {
                   7146:                             $group = $4;
                   7147:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7148:                         } else {
                   7149:                             if ($4 eq '') {
                   7150:                                 $sec = 'none';
                   7151:                             } else {
                   7152:                                 $sec = $4;
                   7153:                             }
                   7154:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7155:                         }
1.811     albertel 7156:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7157:                         my $cid = $2.'_'.$3;
                   7158:                         if ($4 eq '') {
                   7159:                             $sec = 'none';
                   7160:                         } else {
                   7161:                             $sec = $4;
                   7162:                         }
                   7163:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7164:                     }
                   7165:                 }
                   7166:                 if (keys(%allroles) == 0) {
                   7167:                     return;
                   7168:                 }
                   7169:                 foreach my $key (@courses_and_groups) {
                   7170:                     my %content = %{$$access_hash{$key}};
                   7171:                     my $cnum = $content{'number'};
                   7172:                     my $cdom = $content{'domain'};
                   7173:                     my $cid = $cdom.'_'.$cnum;
                   7174:                     if (!exists($allroles{$cid})) {
                   7175:                         next;
                   7176:                     }    
                   7177:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7178:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7179:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7180:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7181:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7182:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7183:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7184:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7185:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7186:                                         if (grep/^all$/,@sections) {
                   7187:                                             return 'ok';
                   7188:                                         } else {
                   7189:                                             if (grep/^$sec$/,@sections) {
                   7190:                                                 return 'ok';
                   7191:                                             }
                   7192:                                         }
                   7193:                                     }
                   7194:                                 }
                   7195:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7196:                                     if (grep/^none$/,@groups) {
                   7197:                                         return 'ok';
                   7198:                                     }
                   7199:                                 } else {
                   7200:                                     if (grep/^all$/,@groups) {
                   7201:                                         return 'ok';
                   7202:                                     } 
                   7203:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7204:                                         if (grep/^$group$/,@groups) {
                   7205:                                             return 'ok';
                   7206:                                         }
                   7207:                                     }
                   7208:                                 } 
                   7209:                             }
                   7210:                         }
                   7211:                     }
                   7212:                 }
                   7213:             }
                   7214:             if ($guest) {
                   7215:                 return $guest;
                   7216:             }
                   7217:         }
                   7218:     }
                   7219:     return;
                   7220: }
                   7221: 
                   7222: sub course_group_datechecker {
                   7223:     my ($dates,$now,$status) = @_;
                   7224:     my ($start,$end) = split(/\./,$dates);
                   7225:     if (!$start && !$end) {
                   7226:         return 'ok';
                   7227:     }
                   7228:     if (grep/^active$/,@{$status}) {
                   7229:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7230:             return 'ok';
                   7231:         }
                   7232:     }
                   7233:     if (grep/^previous$/,@{$status}) {
                   7234:         if ($end > $now ) {
                   7235:             return 'ok';
                   7236:         }
                   7237:     }
                   7238:     if (grep/^future$/,@{$status}) {
                   7239:         if ($start > $now) {
                   7240:             return 'ok';
                   7241:         }
                   7242:     }
                   7243:     return; 
                   7244: }
                   7245: 
                   7246: sub parse_portfolio_url {
                   7247:     my ($url) = @_;
                   7248: 
                   7249:     my ($type,$udom,$unum,$group,$file_name);
                   7250:     
1.823     albertel 7251:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7252: 	$type = 1;
                   7253:         $udom = $1;
                   7254:         $unum = $2;
                   7255:         $file_name = $3;
1.823     albertel 7256:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7257: 	$type = 2;
                   7258:         $udom = $1;
                   7259:         $unum = $2;
                   7260:         $group = $3;
                   7261:         $file_name = $3.'/'.$4;
                   7262:     }
                   7263:     if (wantarray) {
                   7264: 	return ($type,$udom,$unum,$file_name,$group);
                   7265:     }
                   7266:     return $type;
                   7267: }
                   7268: 
                   7269: sub is_portfolio_url {
                   7270:     my ($url) = @_;
                   7271:     return scalar(&parse_portfolio_url($url));
                   7272: }
                   7273: 
1.798     raeburn  7274: sub is_portfolio_file {
                   7275:     my ($file) = @_;
1.820     raeburn  7276:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7277:         return 1;
                   7278:     }
                   7279:     return;
                   7280: }
                   7281: 
1.976     raeburn  7282: sub usertools_access {
1.1084    raeburn  7283:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7284:     my ($access,%tools);
                   7285:     if ($context eq '') {
                   7286:         $context = 'tools';
                   7287:     }
                   7288:     if ($context eq 'requestcourses') {
                   7289:         %tools = (
                   7290:                       official   => 1,
                   7291:                       unofficial => 1,
1.1006    raeburn  7292:                       community  => 1,
1.1246    raeburn  7293:                       textbook   => 1,
1.1305    raeburn  7294:                       placement  => 1,
1.1368    raeburn  7295:                       lti        => 1,
1.985     raeburn  7296:                  );
1.1183    raeburn  7297:     } elsif ($context eq 'requestauthor') {
                   7298:         %tools = (
                   7299:                       requestauthor => 1,
                   7300:                  );
1.985     raeburn  7301:     } else {
                   7302:         %tools = (
                   7303:                       aboutme   => 1,
                   7304:                       blog      => 1,
1.1177    raeburn  7305:                       webdav    => 1,
1.985     raeburn  7306:                       portfolio => 1,
                   7307:                  );
                   7308:     }
1.976     raeburn  7309:     return if (!defined($tools{$tool}));
                   7310: 
1.1242    raeburn  7311:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7312:         $udom = $env{'user.domain'};
                   7313:         $uname = $env{'user.name'};
                   7314:     }
                   7315: 
1.978     raeburn  7316:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7317:         if ($action ne 'reload') {
1.985     raeburn  7318:             if ($context eq 'requestcourses') {
                   7319:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7320:             } elsif ($context eq 'requestauthor') {
                   7321:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7322:             } else {
                   7323:                 return $env{'environment.availabletools.'.$tool};
                   7324:             }
                   7325:         }
1.976     raeburn  7326:     }
                   7327: 
1.1183    raeburn  7328:     my ($toolstatus,$inststatus,$envkey);
                   7329:     if ($context eq 'requestauthor') {
                   7330:         $envkey = $context; 
                   7331:     } else {
                   7332:         $envkey = $context.'.'.$tool;
                   7333:     }
1.976     raeburn  7334: 
1.985     raeburn  7335:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7336:          ($action ne 'reload')) {
1.1183    raeburn  7337:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7338:         $inststatus = $env{'environment.inststatus'};
                   7339:     } else {
1.1084    raeburn  7340:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7341:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7342:             $inststatus = $userenvref->{'inststatus'};
                   7343:         } else {
1.1183    raeburn  7344:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7345:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7346:             $inststatus = $userenv{'inststatus'};
                   7347:         }
1.976     raeburn  7348:     }
                   7349: 
                   7350:     if ($toolstatus ne '') {
                   7351:         if ($toolstatus) {
                   7352:             $access = 1;
                   7353:         } else {
                   7354:             $access = 0;
                   7355:         }
                   7356:         return $access;
                   7357:     }
                   7358: 
1.1084    raeburn  7359:     my ($is_adv,%domdef);
                   7360:     if (ref($is_advref) eq 'HASH') {
                   7361:         $is_adv = $is_advref->{'is_adv'};
                   7362:     } else {
                   7363:         $is_adv = &is_advanced_user($udom,$uname);
                   7364:     }
                   7365:     if (ref($domdefref) eq 'HASH') {
                   7366:         %domdef = %{$domdefref};
                   7367:     } else {
                   7368:         %domdef = &get_domain_defaults($udom);
                   7369:     }
1.976     raeburn  7370:     if (ref($domdef{$tool}) eq 'HASH') {
                   7371:         if ($is_adv) {
                   7372:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7373:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7374:                     $access = 1;
                   7375:                 } else {
                   7376:                     $access = 0;
                   7377:                 }
                   7378:                 return $access;
                   7379:             }
                   7380:         }
                   7381:         if ($inststatus ne '') {
                   7382:             my ($hasaccess,$hasnoaccess);
                   7383:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7384:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7385:                     if ($domdef{$tool}{$affiliation}) {
                   7386:                         $hasaccess = 1;
                   7387:                     } else {
                   7388:                         $hasnoaccess = 1;
                   7389:                     }
                   7390:                 }
                   7391:             }
                   7392:             if ($hasaccess || $hasnoaccess) {
                   7393:                 if ($hasaccess) {
                   7394:                     $access = 1;
                   7395:                 } elsif ($hasnoaccess) {
                   7396:                     $access = 0; 
                   7397:                 }
                   7398:                 return $access;
                   7399:             }
                   7400:         } else {
                   7401:             if ($domdef{$tool}{'default'} ne '') {
                   7402:                 if ($domdef{$tool}{'default'}) {
                   7403:                     $access = 1;
                   7404:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7405:                     $access = 0;
                   7406:                 }
                   7407:                 return $access;
                   7408:             }
                   7409:         }
                   7410:     } else {
1.1177    raeburn  7411:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7412:             $access = 1;
                   7413:         } else {
                   7414:             $access = 0;
                   7415:         }
1.976     raeburn  7416:         return $access;
                   7417:     }
                   7418: }
                   7419: 
1.1050    raeburn  7420: sub is_course_owner {
                   7421:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7422:     if (($udom eq '') || ($uname eq '')) {
                   7423:         $udom = $env{'user.domain'};
                   7424:         $uname = $env{'user.name'};
                   7425:     }
                   7426:     unless (($udom eq '') || ($uname eq '')) {
                   7427:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7428:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7429:                 return 1;
                   7430:             } else {
                   7431:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7432:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7433:                     return 1;
                   7434:                 }
                   7435:             }
                   7436:         }
                   7437:     }
                   7438:     return;
                   7439: }
                   7440: 
1.976     raeburn  7441: sub is_advanced_user {
                   7442:     my ($udom,$uname) = @_;
1.1085    raeburn  7443:     if ($udom ne '' && $uname ne '') {
                   7444:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7445:             if (wantarray) {
                   7446:                 return ($env{'user.adv'},$env{'user.author'});
                   7447:             } else {
                   7448:                 return $env{'user.adv'};
                   7449:             }
1.1085    raeburn  7450:         }
                   7451:     }
1.976     raeburn  7452:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7453:     my %allroles;
1.1128    raeburn  7454:     my ($is_adv,$is_author);
1.976     raeburn  7455:     foreach my $role (keys(%roleshash)) {
                   7456:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7457:         my $area = '/'.$tdomain.'/'.$trest;
                   7458:         if ($sec ne '') {
                   7459:             $area .= '/'.$sec;
                   7460:         }
                   7461:         if (($area ne '') && ($trole ne '')) {
                   7462:             my $spec=$trole.'.'.$area;
                   7463:             if ($trole =~ /^cr\//) {
                   7464:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7465:             } elsif ($trole ne 'gr') {
                   7466:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7467:             }
1.1128    raeburn  7468:             if ($trole eq 'au') {
                   7469:                 $is_author = 1;
                   7470:             }
1.976     raeburn  7471:         }
                   7472:     }
                   7473:     foreach my $role (keys(%allroles)) {
                   7474:         last if ($is_adv);
                   7475:         foreach my $item (split(/:/,$allroles{$role})) {
                   7476:             if ($item ne '') {
                   7477:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7478:                 if ($privilege eq 'adv') {
                   7479:                     $is_adv = 1;
                   7480:                     last;
                   7481:                 }
                   7482:             }
                   7483:         }
                   7484:     }
1.1128    raeburn  7485:     if (wantarray) {
                   7486:         return ($is_adv,$is_author);
                   7487:     }
1.976     raeburn  7488:     return $is_adv;
                   7489: }
1.798     raeburn  7490: 
1.1035    raeburn  7491: sub check_can_request {
1.1368    raeburn  7492:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7493:     my $canreq = 0;
1.1368    raeburn  7494:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7495:         $uname = $env{'user.name'};
                   7496:         $udom = $env{'user.domain'};
                   7497:     }
1.1035    raeburn  7498:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7499:     my @options = ('approval','validate','autolimit');
                   7500:     my $optregex = join('|',@options);
                   7501:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7502:         foreach my $type (@{$types}) {
1.1368    raeburn  7503:             if (&usertools_access($uname,$udom,$type,undef,
                   7504:                                   'requestcourses')) {
1.1035    raeburn  7505:                 $canreq ++;
1.1036    raeburn  7506:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7507:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7508:                 }
1.1368    raeburn  7509:                 if ($dom eq $udom) {
1.1035    raeburn  7510:                     $can_request->{$type} = 1;
                   7511:                 }
                   7512:             }
1.1368    raeburn  7513:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7514:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7515:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7516:                 if (@curr > 0) {
1.1036    raeburn  7517:                     foreach my $item (@curr) {
                   7518:                         if (ref($request_domains) eq 'HASH') {
                   7519:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7520:                             if ($otherdom ne '') {
                   7521:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7522:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7523:                                         push(@{$request_domains->{$type}},$otherdom);
                   7524:                                     }
                   7525:                                 } else {
                   7526:                                     push(@{$request_domains->{$type}},$otherdom);
                   7527:                                 }
                   7528:                             }
                   7529:                         }
                   7530:                     }
1.1368    raeburn  7531:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7532:                         $canreq ++;
1.1035    raeburn  7533:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7534:                             $can_request->{$type} = 1;
                   7535:                         }
                   7536:                     }
                   7537:                 }
                   7538:             }
                   7539:         }
                   7540:     }
                   7541:     return $canreq;
                   7542: }
                   7543: 
1.341     www      7544: # ---------------------------------------------- Custom access rule evaluation
                   7545: 
                   7546: sub customaccess {
                   7547:     my ($priv,$uri)=@_;
1.807     albertel 7548:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7549:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7550:     $udom = &LONCAPA::clean_domain($udom);
                   7551:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7552:     my $access=0;
1.800     albertel 7553:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7554: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7555: 	if ($type eq 'user') {
                   7556: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7557: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7558: 		if ($tdom) {
                   7559: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7560: 		}
1.896     albertel 7561: 		if ($tuname) {
                   7562: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7563: 		}
                   7564: 		$access=($effect eq 'allow');
                   7565: 		last;
                   7566: 	    }
                   7567: 	} else {
                   7568: 	    if ($role) {
                   7569: 		if ($role ne $urole) { next; }
                   7570: 	    }
                   7571: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7572: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7573: 		if ($tdom) {
                   7574: 		    if ($tdom ne $udom) { next; }
                   7575: 		}
                   7576: 		if ($tcrs) {
                   7577: 		    if ($tcrs ne $ucrs) { next; }
                   7578: 		}
                   7579: 		if ($tsec) {
                   7580: 		    if ($tsec ne $usec) { next; }
                   7581: 		}
                   7582: 		$access=($effect eq 'allow');
                   7583: 		last;
                   7584: 	    }
                   7585: 	    if ($realm eq '' && $role eq '') {
                   7586: 		$access=($effect eq 'allow');
                   7587: 	    }
1.402     bowersj2 7588: 	}
1.341     www      7589:     }
                   7590:     return $access;
                   7591: }
                   7592: 
1.103     harris41 7593: # ------------------------------------------------- Check for a user privilege
1.12      www      7594: 
                   7595: sub allowed {
1.1281    raeburn  7596:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7597:     my $ver_orguri=$uri;
1.439     www      7598:     $uri=&deversion($uri);
1.152     www      7599:     my $orguri=$uri;
1.52      www      7600:     $uri=&declutter($uri);
1.809     raeburn  7601: 
1.810     raeburn  7602:     if ($priv eq 'evb') {
                   7603: # Evade communication block restrictions for specified role in a course
                   7604:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7605:             return $1;
                   7606:         } else {
                   7607:             return;
                   7608:         }
                   7609:     }
                   7610: 
1.620     albertel 7611:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7612: # Free bre access to adm and meta resources
1.1343    raeburn  7613:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7614: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7615: 	&& ($priv eq 'bre')) {
1.14      www      7616: 	return 'F';
1.159     www      7617:     }
                   7618: 
1.545     banghart 7619: # Free bre access to user's own portfolio contents
1.714     raeburn  7620:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7621:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7622: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7623:         my %setters;
                   7624:         my ($startblock,$endblock) = 
                   7625:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7626:         if ($startblock && $endblock) {
                   7627:             return 'B';
                   7628:         } else {
                   7629:             return 'F';
                   7630:         }
1.545     banghart 7631:     }
                   7632: 
1.762     raeburn  7633: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7634:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7635:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7636:         if (exists($env{'request.course.id'})) {
                   7637:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7638:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7639:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7640:                 my $courseprivid=$env{'request.course.id'};
                   7641:                 $courseprivid=~s/\_/\//;
                   7642:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7643:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7644:                     return $1; 
1.762     raeburn  7645:                 } else {
                   7646:                     if ($env{'request.course.sec'}) {
                   7647:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7648:                     }
                   7649:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7650:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7651:                         return $2;
                   7652:                     }
1.714     raeburn  7653:                 }
                   7654:             }
                   7655:         }
                   7656:     }
                   7657: 
1.159     www      7658: # Free bre to public access
                   7659: 
                   7660:     if ($priv eq 'bre') {
1.1362    raeburn  7661:         my $copyright;
                   7662:         unless ($uri =~ /ext\.tool/) {
                   7663:             $copyright=&metadata($uri,'copyright');
                   7664:         }
1.620     albertel 7665: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7666:            return 'F'; 
                   7667:         }
1.238     www      7668:         if ($copyright eq 'priv') {
                   7669:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7670: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7671: 		return '';
                   7672:             }
                   7673:         }
                   7674:         if ($copyright eq 'domain') {
                   7675:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7676: 	    unless (($env{'user.domain'} eq $1) ||
                   7677:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7678: 		return '';
                   7679:             }
1.262     matthew  7680:         }
1.620     albertel 7681:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7682:             # Library role, so allow browsing of resources in this domain.
                   7683:             return 'F';
1.238     www      7684:         }
1.341     www      7685:         if ($copyright eq 'custom') {
                   7686: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7687:         }
1.14      www      7688:     }
1.264     matthew  7689:     # Domain coordinator is trying to create a course
1.620     albertel 7690:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7691:         # uri is the requested domain in this case.
                   7692:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7693:         # a role of dc for the domain in question.
1.620     albertel 7694:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7695:     }
1.29      www      7696: 
1.52      www      7697:     my $thisallowed='';
                   7698:     my $statecond=0;
                   7699:     my $courseprivid='';
                   7700: 
1.1039    raeburn  7701:     my $ownaccess;
1.1043    raeburn  7702:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7703:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7704:         if ($uri eq '') {
                   7705:             $ownaccess = 1;
                   7706:         } else {
                   7707:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7708:                 my $udom = $env{'user.domain'};
                   7709:                 my $uname = $env{'user.name'};
                   7710:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7711:                     $ownaccess = 1;
1.1040    raeburn  7712:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7713:                     unless ($uri =~ m{\.\./}) {
                   7714:                         $ownaccess = 1;
                   7715:                     }
                   7716:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7717:                     my $now = time;
                   7718:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7719:                         my $adom = $1;
                   7720:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7721:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7722:                                 my ($start,$end) = split('.',$env{$key});
                   7723:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7724:                                     $ownaccess = 1;
                   7725:                                     last;
                   7726:                                 }
                   7727:                             }
                   7728:                         }
                   7729:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7730:                         my $adom = $1;
                   7731:                         my $aname = $2;
1.1042    raeburn  7732:                         foreach my $role ('ca','aa') { 
                   7733:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7734:                                 my ($start,$end) =
                   7735:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7736:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7737:                                     $ownaccess = 1;
                   7738:                                     last;
                   7739:                                 }
1.1039    raeburn  7740:                             }
                   7741:                         }
                   7742:                     }
                   7743:                 }
                   7744:             }
                   7745:         }
                   7746:     }
                   7747: 
1.52      www      7748: # Course
                   7749: 
1.620     albertel 7750:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7751:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7752:             $thisallowed.=$1;
                   7753:         }
1.52      www      7754:     }
1.29      www      7755: 
1.52      www      7756: # Domain
                   7757: 
1.620     albertel 7758:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7759:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7760:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7761:             $thisallowed.=$1;
                   7762:         }
1.12      www      7763:     }
1.52      www      7764: 
1.1141    raeburn  7765: # User who is not author or co-author might still be able to edit
                   7766: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7767:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7768:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7769:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7770:             $thisallowed.=$1;
                   7771:         }
                   7772:     }
                   7773: 
1.52      www      7774: # Course: uri itself is a course
1.66      www      7775:     my $courseuri=$uri;
                   7776:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7777:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7778: 
1.620     albertel 7779:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7780:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7781:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7782:             $thisallowed.=$1;
                   7783:         }
1.12      www      7784:     }
1.29      www      7785: 
1.665     albertel 7786: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7787: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7788:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7789: 	$thisallowed='';
1.671     raeburn  7790:         my ($match)=&is_on_map($uri);
                   7791:         if ($match) {
                   7792:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7793:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7794:                 my $value = $1;
                   7795:                 if ($noblockcheck) {
                   7796:                     $thisallowed.=$value;
1.1162    raeburn  7797:                 } else {
1.1281    raeburn  7798:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7799:                     if (@blockers > 0) {
                   7800:                         $thisallowed = 'B';
                   7801:                     } else {
                   7802:                         $thisallowed.=$value;
                   7803:                     }
1.1162    raeburn  7804:                 }
1.671     raeburn  7805:             }
                   7806:         } else {
1.705     albertel 7807:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7808:             if ($refuri) {
                   7809:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7810:                     $thisallowed='F';
1.671     raeburn  7811:                 } else {
                   7812:                     $refuri=&declutter($refuri);
                   7813:                     my ($match) = &is_on_map($refuri);
                   7814:                     if ($match) {
1.1281    raeburn  7815:                         if ($noblockcheck) {
                   7816:                             $thisallowed='F';
1.1162    raeburn  7817:                         } else {
1.1281    raeburn  7818:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7819:                             if (@blockers > 0) {
                   7820:                                 $thisallowed = 'B';
                   7821:                             } else {
                   7822:                                 $thisallowed='F';
                   7823:                             }
1.1162    raeburn  7824:                         }
1.671     raeburn  7825:                     }
1.669     raeburn  7826:                 }
1.671     raeburn  7827:             }
                   7828:         }
1.314     www      7829:     }
1.492     albertel 7830: 
1.766     albertel 7831:     if ($priv eq 'bre'
                   7832: 	&& $thisallowed ne 'F' 
                   7833: 	&& $thisallowed ne '2'
                   7834: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7835: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7836:     }
1.1250    raeburn  7837: 
1.52      www      7838: # Full access at system, domain or course-wide level? Exit.
1.29      www      7839:     if ($thisallowed=~/F/) {
                   7840: 	return 'F';
                   7841:     }
                   7842: 
1.52      www      7843: # If this is generating or modifying users, exit with special codes
1.29      www      7844: 
1.643     www      7845:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7846: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7847: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7848: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7849: 	    unless ($auname) { return $thisallowed; }
                   7850: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7851: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7852: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7853: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7854: 	}
1.52      www      7855: 	return $thisallowed;
                   7856:     }
                   7857: #
1.103     harris41 7858: # Gathered so far: system, domain and course wide privileges
1.52      www      7859: #
                   7860: # Course: See if uri or referer is an individual resource that is part of 
                   7861: # the course
                   7862: 
1.620     albertel 7863:     if ($env{'request.course.id'}) {
1.232     www      7864: 
1.620     albertel 7865:        $courseprivid=$env{'request.course.id'};
                   7866:        if ($env{'request.course.sec'}) {
                   7867:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7868:        }
                   7869:        $courseprivid=~s/\_/\//;
                   7870:        my $checkreferer=1;
1.232     www      7871:        my ($match,$cond)=&is_on_map($uri);
                   7872:        if ($match) {
                   7873:            $statecond=$cond;
1.620     albertel 7874:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7875:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7876:                my $value = $1;
                   7877:                if ($priv eq 'bre') {
1.1281    raeburn  7878:                    if ($noblockcheck) {
                   7879:                        $thisallowed.=$value;
1.1162    raeburn  7880:                    } else {
1.1281    raeburn  7881:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7882:                        if (@blockers > 0) {
                   7883:                            $thisallowed = 'B';
                   7884:                        } else {
                   7885:                            $thisallowed.=$value;
                   7886:                        }
1.1162    raeburn  7887:                    }
                   7888:                } else {
                   7889:                    $thisallowed.=$value;
                   7890:                }
1.52      www      7891:                $checkreferer=0;
                   7892:            }
1.29      www      7893:        }
1.83      www      7894:        
1.148     www      7895:        if ($checkreferer) {
1.620     albertel 7896: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7897:             unless ($refuri) {
1.800     albertel 7898:                 foreach my $key (keys(%env)) {
                   7899: 		    if ($key=~/^httpref\..*\*/) {
                   7900: 			my $pattern=$key;
1.156     www      7901:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7902:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7903:                         $pattern=~s/\//\\\//g;
1.152     www      7904:                         if ($orguri=~/$pattern/) {
1.800     albertel 7905: 			    $refuri=$env{$key};
1.148     www      7906:                         }
                   7907:                     }
1.191     harris41 7908:                 }
1.148     www      7909:             }
1.232     www      7910: 
1.148     www      7911:          if ($refuri) { 
1.152     www      7912: 	  $refuri=&declutter($refuri);
1.232     www      7913:           my ($match,$cond)=&is_on_map($refuri);
                   7914:             if ($match) {
                   7915:               my $refstatecond=$cond;
1.620     albertel 7916:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7917:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7918:                   my $value = $1;
                   7919:                   if ($priv eq 'bre') {
1.1281    raeburn  7920:                       if ($noblockcheck) {
                   7921:                           $thisallowed.=$value;
1.1162    raeburn  7922:                       } else {
1.1281    raeburn  7923:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7924:                           if (@blockers > 0) {
                   7925:                               $thisallowed = 'B';
                   7926:                           } else {
                   7927:                               $thisallowed.=$value;
                   7928:                           }
1.1162    raeburn  7929:                       }
                   7930:                   } else {
                   7931:                       $thisallowed.=$value;
                   7932:                   }
1.53      www      7933:                   $uri=$refuri;
                   7934:                   $statecond=$refstatecond;
1.52      www      7935:               }
                   7936:           }
1.148     www      7937:         }
1.29      www      7938:        }
1.52      www      7939:    }
1.29      www      7940: 
1.52      www      7941: #
1.103     harris41 7942: # Gathered now: all privileges that could apply, and condition number
1.52      www      7943: # 
                   7944: #
                   7945: # Full or no access?
                   7946: #
1.29      www      7947: 
1.52      www      7948:     if ($thisallowed=~/F/) {
                   7949: 	return 'F';
                   7950:     }
1.29      www      7951: 
1.52      www      7952:     unless ($thisallowed) {
                   7953:         return '';
                   7954:     }
1.29      www      7955: 
1.52      www      7956: # Restrictions exist, deal with them
                   7957: #
                   7958: #   C:according to course preferences
                   7959: #   R:according to resource settings
                   7960: #   L:unless locked
                   7961: #   X:according to user session state
                   7962: #
                   7963: 
                   7964: # Possibly locked functionality, check all courses
1.54      www      7965: # Locks might take effect only after 10 minutes cache expiration for other
                   7966: # courses, and 2 minutes for current course
1.52      www      7967: 
                   7968:     my $envkey;
                   7969:     if ($thisallowed=~/L/) {
1.1000    raeburn  7970:         foreach $envkey (keys(%env)) {
1.54      www      7971:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7972:                my $courseid=$2;
                   7973:                my $roleid=$1.'.'.$2;
1.92      www      7974:                $courseid=~s/^\///;
1.54      www      7975:                my $expiretime=600;
1.620     albertel 7976:                if ($env{'request.role'} eq $roleid) {
1.54      www      7977: 		  $expiretime=120;
                   7978:                }
                   7979: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7980:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7981:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7982: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7983:                }
1.620     albertel 7984:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7985:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7986: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7987:                        &log($env{'user.domain'},$env{'user.name'},
                   7988:                             $env{'user.home'},
1.57      www      7989:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7990:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7991:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7992: 		       return '';
                   7993:                    }
                   7994:                }
1.620     albertel 7995:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7996:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7997: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7998:                        &log($env{'user.domain'},$env{'user.name'},
                   7999:                             $env{'user.home'},
1.57      www      8000:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8001:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8002:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8003: 		       return '';
                   8004:                    }
                   8005:                }
                   8006: 	   }
1.29      www      8007:        }
1.52      www      8008:     }
                   8009:    
                   8010: #
                   8011: # Rest of the restrictions depend on selected course
                   8012: #
                   8013: 
1.620     albertel 8014:     unless ($env{'request.course.id'}) {
1.766     albertel 8015: 	if ($thisallowed eq 'A') {
                   8016: 	    return 'A';
1.814     raeburn  8017:         } elsif ($thisallowed eq 'B') {
                   8018:             return 'B';
1.766     albertel 8019: 	} else {
                   8020: 	    return '1';
                   8021: 	}
1.52      www      8022:     }
1.29      www      8023: 
1.52      www      8024: #
                   8025: # Now user is definitely in a course
                   8026: #
1.53      www      8027: 
                   8028: 
                   8029: # Course preferences
                   8030: 
                   8031:    if ($thisallowed=~/C/) {
1.620     albertel 8032:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8033:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8034:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8035: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8036: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8037: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8038: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8039: 			$env{'request.course.id'});
                   8040: 	   }
1.237     www      8041:            return '';
                   8042:        }
                   8043: 
1.620     albertel 8044:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8045: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8046: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8047: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8048: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8049: 			$env{'request.course.id'});
                   8050: 	   }
1.54      www      8051:            return '';
                   8052:        }
1.53      www      8053:    }
                   8054: 
                   8055: # Resource preferences
                   8056: 
                   8057:    if ($thisallowed=~/R/) {
1.620     albertel 8058:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8059:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8060: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8061: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8062: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8063: 	   }
                   8064: 	   return '';
1.54      www      8065:        }
1.53      www      8066:    }
1.30      www      8067: 
1.246     www      8068: # Restricted by state or randomout?
1.30      www      8069: 
1.52      www      8070:    if ($thisallowed=~/X/) {
1.620     albertel 8071:       if ($env{'acc.randomout'}) {
1.579     albertel 8072: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8073:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8074:             return ''; 
                   8075:          }
1.247     www      8076:       }
                   8077:       if (&condval($statecond)) {
1.52      www      8078: 	 return '2';
                   8079:       } else {
                   8080:          return '';
                   8081:       }
                   8082:    }
1.30      www      8083: 
1.766     albertel 8084:     if ($thisallowed eq 'A') {
                   8085: 	return 'A';
1.814     raeburn  8086:     } elsif ($thisallowed eq 'B') {
                   8087:         return 'B';
1.766     albertel 8088:     }
1.52      www      8089:    return 'F';
1.232     www      8090: }
1.1162    raeburn  8091: 
1.1192    raeburn  8092: # ------------------------------------------- Check construction space access
                   8093: 
                   8094: sub constructaccess {
                   8095:     my ($url,$setpriv)=@_;
                   8096: 
                   8097: # We do not allow editing of previous versions of files
                   8098:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8099: 
                   8100: # Get username and domain from URL
                   8101:     my ($ownername,$ownerdomain,$ownerhome);
                   8102: 
                   8103:     ($ownerdomain,$ownername) =
1.1325    raeburn  8104:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8105: 
                   8106: # The URL does not really point to any authorspace, forget it
                   8107:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8108: 
                   8109: # Now we need to see if the user has access to the authorspace of
                   8110: # $ownername at $ownerdomain
                   8111: 
                   8112:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8113: # Real author for this?
                   8114:        $ownerhome = $env{'user.home'};
                   8115:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8116:           return ($ownername,$ownerdomain,$ownerhome);
                   8117:        }
                   8118:     } else {
                   8119: # Co-author for this?
                   8120:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8121:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8122:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8123:             return ($ownername,$ownerdomain,$ownerhome);
                   8124:         }
1.1312    raeburn  8125:         if ($env{'request.course.id'}) {
                   8126:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8127:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8128:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8129:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8130:                     return ($ownername,$ownerdomain,$ownerhome);
                   8131:                 }
                   8132:             }
                   8133:         }
1.1192    raeburn  8134:     }
                   8135: 
                   8136: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8137: # we might as well leave
                   8138:    unless ($setpriv) { return ''; }
                   8139: 
                   8140: # Backdoor access?
                   8141:     my $allowed=&allowed('eco',$ownerdomain);
                   8142: # Nope
                   8143:     unless ($allowed) { return ''; }
                   8144: # Looks like we may have access, but could be locked by the owner of the construction space
                   8145:     if ($allowed eq 'U') {
                   8146:         my %blocked=&get('environment',['domcoord.author'],
                   8147:                          $ownerdomain,$ownername);
                   8148: # Is blocked by owner
                   8149:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8150:     }
                   8151:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8152: # Grant temporary access
                   8153:         my $then=$env{'user.login.time'};
1.1209    raeburn  8154:         my $update=$env{'user.update.time'};
1.1192    raeburn  8155:         if (!$update) { $update = $then; }
                   8156:         my $refresh=$env{'user.refresh.time'};
                   8157:         if (!$refresh) { $refresh = $update; }
                   8158:         my $now = time;
                   8159:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8160:                            $now,'ca','constructaccess');
                   8161:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8162:         return($ownername,$ownerdomain,$ownerhome);
                   8163:     }
                   8164: # No business here
                   8165:     return '';
                   8166: }
                   8167: 
1.1282    raeburn  8168: # ----------------------------------------------------------- Content Blocking
                   8169: 
                   8170: {
                   8171: # Caches for faster Course Contents display where content blocking
                   8172: # is in operation (i.e., interval param set) for timed quiz.
                   8173: #
                   8174: # User for whom data are being temporarily cached.
                   8175: my $cacheduser='';
                   8176: # Cached blockers for this user (a hash of blocking items). 
                   8177: my %cachedblockers=();
                   8178: # When the data were last cached.
                   8179: my $cachedlast='';
                   8180: 
                   8181: sub load_all_blockers {
                   8182:     my ($uname,$udom,$blocks)=@_;
                   8183:     if (($uname ne '') && ($udom ne '')) { 
                   8184:         if (($cacheduser eq $uname.':'.$udom) &&
                   8185:             (abs($cachedlast-time)<5)) {
                   8186:             return;
                   8187:         }
                   8188:     }
                   8189:     $cachedlast=time;
                   8190:     $cacheduser=$uname.':'.$udom;
                   8191:     %cachedblockers = &get_commblock_resources($blocks);
                   8192: }
                   8193: 
1.1162    raeburn  8194: sub get_comm_blocks {
                   8195:     my ($cdom,$cnum) = @_;
                   8196:     if ($cdom eq '' || $cnum eq '') {
                   8197:         return unless ($env{'request.course.id'});
                   8198:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8199:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8200:     }
                   8201:     my %commblocks;
                   8202:     my $hashid=$cdom.'_'.$cnum;
                   8203:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8204:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8205:         %commblocks = %{$blocksref};
                   8206:     } else {
                   8207:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8208:         my $cachetime = 600;
                   8209:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8210:     }
                   8211:     return %commblocks;
                   8212: }
                   8213: 
1.1282    raeburn  8214: sub get_commblock_resources {
                   8215:     my ($blocks) = @_;
                   8216:     my %blockers = ();
                   8217:     return %blockers unless ($env{'request.course.id'});
                   8218:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8219:     my %commblocks;
                   8220:     if (ref($blocks) eq 'HASH') {
                   8221:         %commblocks = %{$blocks};
                   8222:     } else {
                   8223:         %commblocks = &get_comm_blocks();
                   8224:     }
1.1282    raeburn  8225:     return %blockers unless (keys(%commblocks) > 0); 
                   8226:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8227:     return %blockers unless (ref($navmap));
1.1162    raeburn  8228:     my $now = time;
                   8229:     foreach my $block (keys(%commblocks)) {
                   8230:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8231:             my ($start,$end) = ($1,$2);
                   8232:             if ($start <= $now && $end >= $now) {
                   8233:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8234:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8235:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8236:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8237:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8238:                             }
                   8239:                         }
                   8240:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8241:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8242:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8243:                             }
                   8244:                         }
                   8245:                     }
                   8246:                 }
                   8247:             }
                   8248:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8249:             my $item = $1;
1.1163    raeburn  8250:             my @to_test;
1.1162    raeburn  8251:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8252:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8253:                     my @interval;
                   8254:                     my $type = 'map';
                   8255:                     if ($item eq 'course') {
                   8256:                         $type = 'course';
                   8257:                         @interval=&EXT("resource.0.interval");
                   8258:                     } else {
                   8259:                         if ($item =~ /___\d+___/) {
                   8260:                             $type = 'resource';
                   8261:                             @interval=&EXT("resource.0.interval",$item);
                   8262:                             if (ref($navmap)) {                        
                   8263:                                 my $res = $navmap->getBySymb($item); 
                   8264:                                 push(@to_test,$res);
                   8265:                             }
1.1162    raeburn  8266:                         } else {
1.1282    raeburn  8267:                             my $mapsymb = &symbread($item,1);
                   8268:                             if ($mapsymb) {
                   8269:                                 if (ref($navmap)) {
                   8270:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8271:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8272:                                     foreach my $res (@to_test) {
                   8273:                                         my $symb = $res->symb();
                   8274:                                         next if ($symb eq $mapsymb);
                   8275:                                         if ($symb ne '') {
                   8276:                                             @interval=&EXT("resource.0.interval",$symb);
                   8277:                                             if ($interval[1] eq 'map') {
                   8278:                                                 last;
1.1162    raeburn  8279:                                             }
                   8280:                                         }
                   8281:                                     }
                   8282:                                 }
                   8283:                             }
                   8284:                         }
1.1282    raeburn  8285:                     }
1.1310    raeburn  8286:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8287:                         my $timelimit = $1; 
1.1282    raeburn  8288:                         my $first_access;
                   8289:                         if ($type eq 'resource') {
                   8290:                             $first_access=&get_first_access($interval[1],$item);
                   8291:                         } elsif ($type eq 'map') {
                   8292:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8293:                         } else {
                   8294:                             $first_access=&get_first_access($interval[1]);
                   8295:                         }
                   8296:                         if ($first_access) {
1.1292    raeburn  8297:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8298:                             if ($timesup > $now) {
                   8299:                                 my $activeblock;
                   8300:                                 foreach my $res (@to_test) {
1.1283    raeburn  8301:                                     if ($res->answerable()) {
1.1282    raeburn  8302:                                         $activeblock = 1;
                   8303:                                         last;
                   8304:                                     }
                   8305:                                 }
                   8306:                                 if ($activeblock) {
                   8307:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8308:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8309:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8310:                                          }
                   8311:                                     }
                   8312:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8313:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8314:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8315:                                         }
1.1162    raeburn  8316:                                     }
                   8317:                                 }
                   8318:                             }
                   8319:                         }
                   8320:                     }
                   8321:                 }
                   8322:             }
                   8323:         }
                   8324:     }
1.1282    raeburn  8325:     return %blockers;
1.1162    raeburn  8326: }
                   8327: 
1.1282    raeburn  8328: sub has_comm_blocking {
                   8329:     my ($priv,$symb,$uri,$blocks) = @_;
                   8330:     my @blockers;
                   8331:     return unless ($env{'request.course.id'});
                   8332:     return unless ($priv eq 'bre');
                   8333:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8334:     return if ($env{'request.state'} eq 'construct');
                   8335:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8336:     return unless (keys(%cachedblockers) > 0);
                   8337:     my (%possibles,@symbs);
                   8338:     if (!$symb) {
                   8339:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8340:     }
1.1282    raeburn  8341:     if ($symb) {
                   8342:         @symbs = ($symb);
                   8343:     } elsif (keys(%possibles)) { 
                   8344:         @symbs = keys(%possibles);
                   8345:     }
                   8346:     my $noblock;
                   8347:     foreach my $symb (@symbs) {
                   8348:         last if ($noblock);
                   8349:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8350:         foreach my $block (keys(%cachedblockers)) {
                   8351:             if ($block =~ /^firstaccess____(.+)$/) {
                   8352:                 my $item = $1;
                   8353:                 if (($item eq $map) || ($item eq $symb)) {
                   8354:                     $noblock = 1;
                   8355:                     last;
                   8356:                 }
                   8357:             }
                   8358:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8359:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8360:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8361:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8362:                             push(@blockers,$block);
                   8363:                         }
                   8364:                     }
                   8365:                 }
1.1162    raeburn  8366:             }
1.1282    raeburn  8367:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8368:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8369:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8370:                         push(@blockers,$block);
                   8371:                     }
                   8372:                 }
1.1162    raeburn  8373:             }
                   8374:         }
                   8375:     }
1.1282    raeburn  8376:     return if ($noblock);
                   8377:     return @blockers;
                   8378: }
1.1162    raeburn  8379: }
                   8380: 
1.1282    raeburn  8381: # -------------------------------- Deversion and split uri into path an filename   
                   8382: 
1.1133    foxr     8383: #
1.1282    raeburn  8384: #   Removes the version from a URI and
1.1133    foxr     8385: #   splits it in to its filename and path to the filename.
                   8386: #   Seems like File::Basename could have done this more clearly.
                   8387: #   Parameters:
                   8388: #      $uri   - input URI
                   8389: #   Returns:
                   8390: #     Two element list consisting of 
                   8391: #     $pathname  - the URI up to and excluding the trailing /
                   8392: #     $filename  - The part of the URI following the last /
                   8393: #  NOTE:
                   8394: #    Another realization of this is simply:
                   8395: #    use File::Basename;
                   8396: #    ...
                   8397: #    $uri = shift;
                   8398: #    $filename = basename($uri);
                   8399: #    $path     = dirname($uri);
                   8400: #    return ($filename, $path);
                   8401: #
                   8402: #     The implementation below is probably faster however.
                   8403: #
1.710     albertel 8404: sub split_uri_for_cond {
                   8405:     my $uri=&deversion(&declutter(shift));
                   8406:     my @uriparts=split(/\//,$uri);
                   8407:     my $filename=pop(@uriparts);
                   8408:     my $pathname=join('/',@uriparts);
                   8409:     return ($pathname,$filename);
                   8410: }
1.232     www      8411: # --------------------------------------------------- Is a resource on the map?
                   8412: 
                   8413: sub is_on_map {
1.710     albertel 8414:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8415:     #Trying to find the conditional for the file
1.620     albertel 8416:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8417: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8418:     if ($match) {
1.289     bowersj2 8419: 	return (1,$1);
                   8420:     } else {
1.434     www      8421: 	return (0,0);
1.289     bowersj2 8422:     }
1.12      www      8423: }
                   8424: 
1.427     www      8425: # --------------------------------------------------------- Get symb from alias
                   8426: 
                   8427: sub get_symb_from_alias {
                   8428:     my $symb=shift;
                   8429:     my ($map,$resid,$url)=&decode_symb($symb);
                   8430: # Already is a symb
                   8431:     if ($url) { return $symb; }
                   8432: # Must be an alias
                   8433:     my $aliassymb='';
                   8434:     my %bighash;
1.620     albertel 8435:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8436:                             &GDBM_READER(),0640)) {
                   8437:         my $rid=$bighash{'mapalias_'.$symb};
                   8438: 	if ($rid) {
                   8439: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8440: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8441: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8442: 	}
                   8443:         untie %bighash;
                   8444:     }
                   8445:     return $aliassymb;
                   8446: }
                   8447: 
1.12      www      8448: # ----------------------------------------------------------------- Define Role
                   8449: 
                   8450: sub definerole {
                   8451:   if (allowed('mcr','/')) {
1.1326    raeburn  8452:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8453:     foreach my $role (split(':',$sysrole)) {
                   8454: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8455:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8456:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8457: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8458:                return "refused:s:$crole&$cqual"; 
                   8459:             }
                   8460:         }
1.191     harris41 8461:     }
1.800     albertel 8462:     foreach my $role (split(':',$domrole)) {
                   8463: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8464:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8465:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8466: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8467:                return "refused:d:$crole&$cqual"; 
                   8468:             }
                   8469:         }
1.191     harris41 8470:     }
1.800     albertel 8471:     foreach my $role (split(':',$courole)) {
                   8472: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8473:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8474:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8475: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8476:                return "refused:c:$crole&$cqual"; 
                   8477:             }
                   8478:         }
1.191     harris41 8479:     }
1.1326    raeburn  8480:     my $uhome;
                   8481:     if (($uname ne '') && ($udom ne '')) {
                   8482:         $uhome = &homeserver($uname,$udom);
                   8483:         return $uhome if ($uhome eq 'no_host');
                   8484:     } else {
                   8485:         $uname = $env{'user.name'};
                   8486:         $udom = $env{'user.domain'};
                   8487:         $uhome = $env{'user.home'};
                   8488:     }
1.620     albertel 8489:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8490:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8491:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8492:     return reply($command,$uhome);
1.12      www      8493:   } else {
                   8494:     return 'refused';
                   8495:   }
1.105     harris41 8496: }
                   8497: 
                   8498: # ---------------- Make a metadata query against the network of library servers
                   8499: 
                   8500: sub metadata_query {
1.1237    raeburn  8501:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8502:     my %rhash;
1.845     albertel 8503:     my %libserv = &all_library();
1.244     matthew  8504:     my @server_list = (defined($server_array) ? @$server_array
                   8505:                                               : keys(%libserv) );
                   8506:     for my $server (@server_list) {
1.1237    raeburn  8507:         my $domains = ''; 
                   8508:         if (ref($domains_hash) eq 'HASH') {
                   8509:             $domains = $domains_hash->{$server}; 
                   8510:         }
1.118     harris41 8511: 	unless ($custom or $customshow) {
1.1237    raeburn  8512: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8513: 	    $rhash{$server}=$reply;
                   8514: 	}
                   8515: 	else {
                   8516: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8517: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8518: 			     $server);
                   8519: 	    $rhash{$server}=$reply;
                   8520: 	}
1.112     harris41 8521:     }
1.118     harris41 8522:     return \%rhash;
1.240     www      8523: }
                   8524: 
                   8525: # ----------------------------------------- Send log queries and wait for reply
                   8526: 
                   8527: sub log_query {
                   8528:     my ($uname,$udom,$query,%filters)=@_;
                   8529:     my $uhome=&homeserver($uname,$udom);
                   8530:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8531:     my $uhost=&hostname($uhome);
1.800     albertel 8532:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8533:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8534:                        $uhome);
1.479     albertel 8535:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8536:     return get_query_reply($queryid);
                   8537: }
                   8538: 
1.818     raeburn  8539: # -------------------------- Update MySQL table for portfolio file
                   8540: 
                   8541: sub update_portfolio_table {
1.821     raeburn  8542:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8543:     if ($group ne '') {
                   8544:         $file_name =~s /^\Q$group\E//;
                   8545:     }
1.818     raeburn  8546:     my $homeserver = &homeserver($uname,$udom);
                   8547:     my $queryid=
1.821     raeburn  8548:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8549:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8550:     my $reply = &get_query_reply($queryid);
                   8551:     return $reply;
                   8552: }
                   8553: 
1.899     raeburn  8554: # -------------------------- Update MySQL allusers table
                   8555: 
                   8556: sub update_allusers_table {
                   8557:     my ($uname,$udom,$names) = @_;
                   8558:     my $homeserver = &homeserver($uname,$udom);
                   8559:     my $queryid=
                   8560:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8561:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8562:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8563:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8564:                'generation='.&escape($names->{'generation'}).'%%'.
                   8565:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8566:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8567:     return;
1.899     raeburn  8568: }
                   8569: 
1.508     raeburn  8570: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8571: 
                   8572: sub fetch_enrollment_query {
1.511     raeburn  8573:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8574:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8575:     my $maxtries = 1;
1.508     raeburn  8576:     if ($context eq 'automated') {
                   8577:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8578:         $sleep = 2;
                   8579:         $loopmax = 100;
1.547     raeburn  8580:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8581:     } else {
                   8582:         $homeserver = &homeserver($cnum,$dom);
                   8583:     }
1.838     albertel 8584:     my $host=&hostname($homeserver);
1.506     raeburn  8585:     my $cmd = '';
1.1000    raeburn  8586:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8587:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8588:     }
                   8589:     $cmd =~ s/%%$//;
                   8590:     $cmd = &escape($cmd);
                   8591:     my $query = 'fetchenrollment';
1.620     albertel 8592:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8593:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8594:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8595:         return 'error: '.$queryid;
                   8596:     }
1.1317    raeburn  8597:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8598:     my $tries = 1;
                   8599:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8600:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8601:         $tries ++;
                   8602:     }
1.526     raeburn  8603:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8604:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8605:     } else {
1.901     albertel 8606:         my @responses = split(/:/,$reply);
1.1322    raeburn  8607:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8608:             foreach my $line (@responses) {
                   8609:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8610:                 $$replyref{$key} = $value;
                   8611:             }
                   8612:         } else {
1.1117    foxr     8613:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8614:             foreach my $line (@responses) {
                   8615:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8616:                 $$replyref{$key} = $value;
                   8617:                 if ($value > 0) {
1.800     albertel 8618:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8619:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8620:                         my $destname = $pathname.'/'.$filename;
                   8621:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8622:                         if ($xml_classlist =~ /^error/) {
                   8623:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8624:                         } else {
1.1359    raeburn  8625:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8626:                                 print FILE &unescape($xml_classlist);
                   8627:                                 close(FILE);
1.526     raeburn  8628:                             } else {
                   8629:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8630:                             }
                   8631:                         }
                   8632:                     }
                   8633:                 }
                   8634:             }
                   8635:         }
                   8636:         return 'ok';
                   8637:     }
                   8638:     return 'error';
                   8639: }
                   8640: 
1.242     www      8641: sub get_query_reply {
1.1317    raeburn  8642:     my ($queryid,$sleep,$loopmax) = @_;;
                   8643:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8644:         $sleep = 0.2;
                   8645:     }
                   8646:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8647:         $loopmax = 100;
                   8648:     }
1.1117    foxr     8649:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8650:     my $reply='';
1.1317    raeburn  8651:     for (1..$loopmax) {
                   8652: 	sleep($sleep);
1.240     www      8653:         if (-e $replyfile.'.end') {
1.1359    raeburn  8654: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8655: 		$reply = join('',<$fh>);
                   8656: 		close($fh);
1.240     www      8657: 	   } else { return 'error: reply_file_error'; }
1.242     www      8658:            return &unescape($reply);
                   8659: 	}
1.240     www      8660:     }
1.242     www      8661:     return 'timeout:'.$queryid;
1.240     www      8662: }
                   8663: 
                   8664: sub courselog_query {
1.241     www      8665: #
                   8666: # possible filters:
                   8667: # url: url or symb
                   8668: # username
                   8669: # domain
                   8670: # action: view, submit, grade
                   8671: # start: timestamp
                   8672: # end: timestamp
                   8673: #
1.240     www      8674:     my (%filters)=@_;
1.620     albertel 8675:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8676:     if ($filters{'url'}) {
                   8677: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8678:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8679:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8680:     }
1.620     albertel 8681:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8682:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8683:     return &log_query($cname,$cdom,'courselog',%filters);
                   8684: }
                   8685: 
                   8686: sub userlog_query {
1.858     raeburn  8687: #
                   8688: # possible filters:
                   8689: # action: log check role
                   8690: # start: timestamp
                   8691: # end: timestamp
                   8692: #
1.240     www      8693:     my ($uname,$udom,%filters)=@_;
                   8694:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8695: }
                   8696: 
1.506     raeburn  8697: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8698: 
                   8699: sub auto_run {
1.508     raeburn  8700:     my ($cnum,$cdom) = @_;
1.876     raeburn  8701:     my $response = 0;
                   8702:     my $settings;
                   8703:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8704:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8705:         $settings = $domconfig{'autoenroll'};
                   8706:         if ($settings->{'run'} eq '1') {
                   8707:             $response = 1;
                   8708:         }
                   8709:     } else {
1.934     raeburn  8710:         my $homeserver;
                   8711:         if (&is_course($cdom,$cnum)) {
                   8712:             $homeserver = &homeserver($cnum,$cdom);
                   8713:         } else {
                   8714:             $homeserver = &domain($cdom,'primary');
                   8715:         }
                   8716:         if ($homeserver ne 'no_host') {
                   8717:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8718:         }
1.876     raeburn  8719:     }
1.506     raeburn  8720:     return $response;
                   8721: }
1.776     albertel 8722: 
1.506     raeburn  8723: sub auto_get_sections {
1.508     raeburn  8724:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8725:     my $homeserver;
                   8726:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8727:         $homeserver = &homeserver($cnum,$cdom);
                   8728:     }
                   8729:     if (!defined($homeserver)) { 
                   8730:         if ($cdom =~ /^$match_domain$/) {
                   8731:             $homeserver = &domain($cdom,'primary');
                   8732:         }
                   8733:     }
                   8734:     my @secs;
                   8735:     if (defined($homeserver)) {
                   8736:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8737:         unless ($response eq 'refused') {
                   8738:             @secs = split(/:/,$response);
                   8739:         }
1.506     raeburn  8740:     }
                   8741:     return @secs;
                   8742: }
1.776     albertel 8743: 
1.506     raeburn  8744: sub auto_new_course {
1.1099    raeburn  8745:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8746:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8747:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8748:     return $response;
                   8749: }
1.776     albertel 8750: 
1.506     raeburn  8751: sub auto_validate_courseID {
1.508     raeburn  8752:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8753:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8754:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8755:     return $response;
                   8756: }
1.776     albertel 8757: 
1.1007    raeburn  8758: sub auto_validate_instcode {
1.1020    raeburn  8759:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8760:     my ($homeserver,$response);
                   8761:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8762:         $homeserver = &homeserver($cnum,$cdom);
                   8763:     }
                   8764:     if (!defined($homeserver)) {
                   8765:         if ($cdom =~ /^$match_domain$/) {
                   8766:             $homeserver = &domain($cdom,'primary');
                   8767:         }
                   8768:     }
1.1065    raeburn  8769:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8770:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8771:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8772:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8773: }
                   8774: 
1.506     raeburn  8775: sub auto_create_password {
1.873     raeburn  8776:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8777:     my ($homeserver,$response);
1.506     raeburn  8778:     my $create_passwd = 0;
                   8779:     my $authchk = '';
1.873     raeburn  8780:     if ($udom =~ /^$match_domain$/) {
                   8781:         $homeserver = &domain($udom,'primary');
                   8782:     }
                   8783:     if ($homeserver eq '') {
                   8784:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8785:             $homeserver = &homeserver($cnum,$cdom);
                   8786:         }
                   8787:     }
                   8788:     if ($homeserver eq '') {
                   8789:         $authchk = 'nodomain';
1.506     raeburn  8790:     } else {
1.873     raeburn  8791:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8792:         if ($response eq 'refused') {
                   8793:             $authchk = 'refused';
                   8794:         } else {
1.901     albertel 8795:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8796:         }
1.506     raeburn  8797:     }
                   8798:     return ($authparam,$create_passwd,$authchk);
                   8799: }
                   8800: 
1.706     raeburn  8801: sub auto_photo_permission {
                   8802:     my ($cnum,$cdom,$students) = @_;
                   8803:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8804:     my ($outcome,$perm_reqd,$conditions) = 
                   8805: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8806:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8807: 	return (undef,undef);
                   8808:     }
1.706     raeburn  8809:     return ($outcome,$perm_reqd,$conditions);
                   8810: }
                   8811: 
                   8812: sub auto_checkphotos {
                   8813:     my ($uname,$udom,$pid) = @_;
                   8814:     my $homeserver = &homeserver($uname,$udom);
                   8815:     my ($result,$resulttype);
                   8816:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8817: 				   &escape($uname).':'.&escape($pid),
                   8818: 				   $homeserver));
1.709     albertel 8819:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8820: 	return (undef,undef);
                   8821:     }
1.706     raeburn  8822:     if ($outcome) {
                   8823:         ($result,$resulttype) = split(/:/,$outcome);
                   8824:     } 
                   8825:     return ($result,$resulttype);
                   8826: }
                   8827: 
                   8828: sub auto_photochoice {
                   8829:     my ($cnum,$cdom) = @_;
                   8830:     my $homeserver = &homeserver($cnum,$cdom);
                   8831:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8832: 						       &escape($cdom),
                   8833: 						       $homeserver)));
1.709     albertel 8834:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8835: 	return (undef,undef);
                   8836:     }
1.706     raeburn  8837:     return ($update,$comment);
                   8838: }
                   8839: 
                   8840: sub auto_photoupdate {
                   8841:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8842:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8843:     my $host=&hostname($homeserver);
1.706     raeburn  8844:     my $cmd = '';
                   8845:     my $maxtries = 1;
1.800     albertel 8846:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8847:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8848:     }
                   8849:     $cmd =~ s/%%$//;
                   8850:     $cmd = &escape($cmd);
                   8851:     my $query = 'institutionalphotos';
                   8852:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8853:     unless ($queryid=~/^\Q$host\E\_/) {
                   8854:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8855:         return 'error: '.$queryid;
                   8856:     }
                   8857:     my $reply = &get_query_reply($queryid);
                   8858:     my $tries = 1;
                   8859:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8860:         $reply = &get_query_reply($queryid);
                   8861:         $tries ++;
                   8862:     }
                   8863:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8864:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8865:     } else {
                   8866:         my @responses = split(/:/,$reply);
                   8867:         my $outcome = shift(@responses); 
                   8868:         foreach my $item (@responses) {
                   8869:             my ($key,$value) = split(/=/,$item);
                   8870:             $$photo{$key} = $value;
                   8871:         }
                   8872:         return $outcome;
                   8873:     }
                   8874:     return 'error';
                   8875: }
                   8876: 
1.521     raeburn  8877: sub auto_instcode_format {
1.793     albertel 8878:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8879: 	$cat_order) = @_;
1.521     raeburn  8880:     my $courses = '';
1.772     raeburn  8881:     my @homeservers;
1.521     raeburn  8882:     if ($caller eq 'global') {
1.841     albertel 8883: 	my %servers = &get_servers($codedom,'library');
                   8884: 	foreach my $tryserver (keys(%servers)) {
                   8885: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8886: 		push(@homeservers,$tryserver);
                   8887: 	    }
1.584     raeburn  8888:         }
1.1022    raeburn  8889:     } elsif ($caller eq 'requests') {
                   8890:         if ($codedom =~ /^$match_domain$/) {
                   8891:             my $chome = &domain($codedom,'primary');
                   8892:             unless ($chome eq 'no_host') {
                   8893:                 push(@homeservers,$chome);
                   8894:             }
                   8895:         }
1.521     raeburn  8896:     } else {
1.772     raeburn  8897:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8898:     }
1.793     albertel 8899:     foreach my $code (keys(%{$instcodes})) {
                   8900:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8901:     }
                   8902:     chop($courses);
1.772     raeburn  8903:     my $ok_response = 0;
                   8904:     my $response;
                   8905:     while (@homeservers > 0 && $ok_response == 0) {
                   8906:         my $server = shift(@homeservers); 
                   8907:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8908:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8909:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8910: 		split(/:/,$response);
1.772     raeburn  8911:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8912:             push(@{$codetitles},&str2array($codetitles_str));
                   8913:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8914:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8915:             $ok_response = 1;
                   8916:         }
                   8917:     }
                   8918:     if ($ok_response) {
1.521     raeburn  8919:         return 'ok';
1.772     raeburn  8920:     } else {
                   8921:         return $response;
1.521     raeburn  8922:     }
                   8923: }
                   8924: 
1.792     raeburn  8925: sub auto_instcode_defaults {
                   8926:     my ($domain,$returnhash,$code_order) = @_;
                   8927:     my @homeservers;
1.841     albertel 8928: 
                   8929:     my %servers = &get_servers($domain,'library');
                   8930:     foreach my $tryserver (keys(%servers)) {
                   8931: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8932: 	    push(@homeservers,$tryserver);
                   8933: 	}
1.792     raeburn  8934:     }
1.841     albertel 8935: 
1.792     raeburn  8936:     my $response;
1.841     albertel 8937:     foreach my $server (@homeservers) {
1.792     raeburn  8938:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8939:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8940: 	
                   8941: 	foreach my $pair (split(/\&/,$response)) {
                   8942: 	    my ($name,$value)=split(/\=/,$pair);
                   8943: 	    if ($name eq 'code_order') {
                   8944: 		@{$code_order} = split(/\&/,&unescape($value));
                   8945: 	    } else {
                   8946: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8947: 	    }
                   8948: 	}
                   8949: 	return 'ok';
1.792     raeburn  8950:     }
1.841     albertel 8951: 
                   8952:     return $response;
1.1003    raeburn  8953: }
                   8954: 
                   8955: sub auto_possible_instcodes {
1.1007    raeburn  8956:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8957:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8958:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8959:         return;
                   8960:     }
1.1003    raeburn  8961:     my (@homeservers,$uhome);
                   8962:     if (defined(&domain($domain,'primary'))) {
                   8963:         $uhome=&domain($domain,'primary');
                   8964:         push(@homeservers,&domain($domain,'primary'));
                   8965:     } else {
                   8966:         my %servers = &get_servers($domain,'library');
                   8967:         foreach my $tryserver (keys(%servers)) {
                   8968:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8969:                 push(@homeservers,$tryserver);
                   8970:             }
                   8971:         }
                   8972:     }
                   8973:     my $response;
                   8974:     foreach my $server (@homeservers) {
                   8975:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8976:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8977:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8978:             split(':',$response);
                   8979:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8980:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8981:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8982:             my ($name,$value)=split('=',$item);
                   8983:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8984:         }
                   8985:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8986:             my ($name,$value)=split('=',$item);
                   8987:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8988:         }
                   8989:         return 'ok';
                   8990:     }
                   8991:     return $response;
                   8992: }
1.792     raeburn  8993: 
1.1010    raeburn  8994: sub auto_courserequest_checks {
                   8995:     my ($dom) = @_;
1.1020    raeburn  8996:     my ($homeserver,%validations);
                   8997:     if ($dom =~ /^$match_domain$/) {
                   8998:         $homeserver = &domain($dom,'primary');
                   8999:     }
                   9000:     unless ($homeserver eq 'no_host') {
                   9001:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9002:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9003:             my @items = split(/&/,$response);
                   9004:             foreach my $item (@items) {
                   9005:                 my ($key,$value) = split('=',$item);
                   9006:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9007:             }
                   9008:         }
                   9009:     }
1.1010    raeburn  9010:     return %validations; 
                   9011: }
                   9012: 
1.1020    raeburn  9013: sub auto_courserequest_validation {
1.1255    raeburn  9014:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9015:     my ($homeserver,$response);
                   9016:     if ($dom =~ /^$match_domain$/) {
                   9017:         $homeserver = &domain($dom,'primary');
                   9018:     }
1.1255    raeburn  9019:     unless ($homeserver eq 'no_host') {
                   9020:         my $customdata;
                   9021:         if (ref($custominfo) eq 'HASH') {
                   9022:             $customdata = &freeze_escape($custominfo);
                   9023:         }
1.1020    raeburn  9024:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9025:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9026:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9027:                                     $customdata,$homeserver));
1.1020    raeburn  9028:     }
                   9029:     return $response;
                   9030: }
                   9031: 
1.777     albertel 9032: sub auto_validate_class_sec {
1.918     raeburn  9033:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9034:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9035:     my $ownerlist;
                   9036:     if (ref($owners) eq 'ARRAY') {
                   9037:         $ownerlist = join(',',@{$owners});
                   9038:     } else {
                   9039:         $ownerlist = $owners;
                   9040:     }
1.773     raeburn  9041:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9042:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9043:     return $response;
                   9044: }
                   9045: 
1.1367    raeburn  9046: sub auto_validate_instclasses {
                   9047:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9048:     my ($homeserver,%validations);
                   9049:     $homeserver = &homeserver($cnum,$cdom);
                   9050:     unless ($homeserver eq 'no_host') {
                   9051:         my $ownerlist;
                   9052:         if (ref($owners) eq 'ARRAY') {
                   9053:             $ownerlist = join(',',@{$owners});
                   9054:         } else {
                   9055:             $ownerlist = $owners;
                   9056:         }
                   9057:         if (ref($classesref) eq 'HASH') {
                   9058:             my $classes = &freeze_escape($classesref);
                   9059:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9060:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9061:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9062:                 my @items = split(/&/,$response);
                   9063:                 foreach my $item (@items) {
                   9064:                     my ($key,$value) = split('=',$item);
                   9065:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9066:                 }
                   9067:             }
                   9068:         }
                   9069:     }
                   9070:     return %validations;
                   9071: }
                   9072: 
1.1248    raeburn  9073: sub auto_crsreq_update {
                   9074:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9075:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9076:     my ($homeserver,%crsreqresponse);
                   9077:     if ($cdom =~ /^$match_domain$/) {
                   9078:         $homeserver = &domain($cdom,'primary');
                   9079:     }
                   9080:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9081:         my $info;
                   9082:         if (ref($inbound) eq 'HASH') {
                   9083:             $info = &freeze_escape($inbound);
                   9084:         }
                   9085:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9086:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9087:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9088:                             &escape($title).':'.&escape($code).':'.
                   9089:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9090:                             $homeserver);
1.1248    raeburn  9091:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9092:             my @items = split(/&/,$response);
                   9093:             foreach my $item (@items) {
                   9094:                 my ($key,$value) = split('=',$item);
                   9095:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9096:             }
                   9097:         }
                   9098:     }
                   9099:     return \%crsreqresponse;
                   9100: }
                   9101: 
1.1305    raeburn  9102: sub auto_export_grades {
1.1309    raeburn  9103:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9104:     my ($homeserver,%exportresponse);
                   9105:     if ($cdom =~ /^$match_domain$/) {
                   9106:         $homeserver = &domain($cdom,'primary');
                   9107:     }
                   9108:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9109:         my $info;
                   9110:         if (ref($inforef) eq 'HASH') {
                   9111:             $info = &freeze_escape($inforef);
                   9112:         }
                   9113:         if (ref($gradesref) eq 'HASH') {
                   9114:             my $grades = &freeze_escape($gradesref);
                   9115:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9116:                                 $info.':'.$grades,$homeserver);
                   9117:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9118:                 my @items = split(/&/,$response);
                   9119:                 foreach my $item (@items) {
                   9120:                     my ($key,$value) = split('=',$item);
                   9121:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9122:                 }
                   9123:             }
                   9124:         }
                   9125:     }
                   9126:     return \%exportresponse;
1.1305    raeburn  9127: }
                   9128: 
1.1287    raeburn  9129: sub check_instcode_cloning {
                   9130:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9131:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9132:         return;
                   9133:     }
                   9134:     my $canclone;
                   9135:     if (@{$code_order} > 0) {
                   9136:         my $instcoderegexp ='^';
                   9137:         my @clonecodes = split(/\&/,$cloner);
                   9138:         foreach my $item (@{$code_order}) {
                   9139:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9140:                 foreach my $pair (@clonecodes) {
                   9141:                     my ($key,$val) = split(/\=/,$pair,2);
                   9142:                     $val = &unescape($val);
                   9143:                     if ($key eq $item) {
                   9144:                         $instcoderegexp .= '('.$val.')';
                   9145:                         last;
                   9146:                     }
                   9147:                 }
                   9148:             } else {
                   9149:                 $instcoderegexp .= $codedefaults->{$item};
                   9150:             }
                   9151:         }
                   9152:         $instcoderegexp .= '$';
                   9153:         my (@from,@to);
                   9154:         eval {
                   9155:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9156:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9157:         };
                   9158:         if ((@from > 0) && (@to > 0)) {
                   9159:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9160:             if (!@diffs) {
                   9161:                 $canclone = 1;
                   9162:             }
                   9163:         }
                   9164:     }
                   9165:     return $canclone;
                   9166: }
                   9167: 
                   9168: sub default_instcode_cloning {
                   9169:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9170:     my (%codedefaults,@code_order,$canclone);
                   9171:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9172:         %codedefaults = %{$codedefaultsref};
                   9173:         @code_order = @{$codeorderref};
                   9174:     } elsif ($clonedom) {
                   9175:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9176:     }
                   9177:     if (($domdefclone) && (@code_order)) {
                   9178:         my @clonecodes = split(/\+/,$domdefclone);
                   9179:         my $instcoderegexp ='^';
                   9180:         foreach my $item (@code_order) {
                   9181:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9182:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9183:             } else {
                   9184:                 $instcoderegexp .= $codedefaults{$item};
                   9185:             }
                   9186:         }
                   9187:         $instcoderegexp .= '$';
                   9188:         my (@from,@to);
                   9189:         eval {
                   9190:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9191:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9192:         };
                   9193:         if ((@from > 0) && (@to > 0)) {
                   9194:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9195:             if (!@diffs) {
                   9196:                 $canclone = 1;
                   9197:             }
                   9198:         }
                   9199:     }
                   9200:     return $canclone;
                   9201: }
                   9202: 
1.679     raeburn  9203: # ------------------------------------------------------- Course Group routines
                   9204: 
                   9205: sub get_coursegroups {
1.809     raeburn  9206:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9207:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9208: }
                   9209: 
1.679     raeburn  9210: sub modify_coursegroup {
                   9211:     my ($cdom,$cnum,$groupsettings) = @_;
                   9212:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9213: }
                   9214: 
1.809     raeburn  9215: sub toggle_coursegroup_status {
                   9216:     my ($cdom,$cnum,$group,$action) = @_;
                   9217:     my ($from_namespace,$to_namespace);
                   9218:     if ($action eq 'delete') {
                   9219:         $from_namespace = 'coursegroups';
                   9220:         $to_namespace = 'deleted_groups';
                   9221:     } else {
                   9222:         $from_namespace = 'deleted_groups';
                   9223:         $to_namespace = 'coursegroups';
                   9224:     }
                   9225:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9226:     if (my $tmp = &error(%curr_group)) {
                   9227:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9228:         return ('read error',$tmp);
                   9229:     } else {
                   9230:         my %savedsettings = %curr_group; 
1.809     raeburn  9231:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9232:         my $deloutcome;
                   9233:         if ($result eq 'ok') {
1.809     raeburn  9234:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9235:         } else {
                   9236:             return ('write error',$result);
                   9237:         }
                   9238:         if ($deloutcome eq 'ok') {
                   9239:             return 'ok';
                   9240:         } else {
                   9241:             return ('delete error',$deloutcome);
                   9242:         }
                   9243:     }
                   9244: }
                   9245: 
1.679     raeburn  9246: sub modify_group_roles {
1.957     raeburn  9247:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9248:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9249:     my $role = 'gr/'.&escape($userprivs);
                   9250:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9251:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9252:     if ($result eq 'ok') {
                   9253:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9254:     }
1.679     raeburn  9255:     return $result;
                   9256: }
                   9257: 
                   9258: sub modify_coursegroup_membership {
                   9259:     my ($cdom,$cnum,$membership) = @_;
                   9260:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9261:     return $result;
                   9262: }
                   9263: 
1.682     raeburn  9264: sub get_active_groups {
                   9265:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9266:     my $now = time;
                   9267:     my %groups = ();
                   9268:     foreach my $key (keys(%env)) {
1.811     albertel 9269:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9270:             my ($start,$end) = split(/\./,$env{$key});
                   9271:             if (($end!=0) && ($end<$now)) { next; }
                   9272:             if (($start!=0) && ($start>$now)) { next; }
                   9273:             if ($1 eq $cdom && $2 eq $cnum) {
                   9274:                 $groups{$3} = $env{$key} ;
                   9275:             }
                   9276:         }
                   9277:     }
                   9278:     return %groups;
                   9279: }
                   9280: 
1.683     raeburn  9281: sub get_group_membership {
                   9282:     my ($cdom,$cnum,$group) = @_;
                   9283:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9284: }
                   9285: 
                   9286: sub get_users_groups {
                   9287:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9288:     my @usersgroups;
1.683     raeburn  9289:     my $cachetime=1800;
                   9290: 
                   9291:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9292:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9293:     if (defined($cached)) {
1.734     albertel 9294:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9295:     } else {  
                   9296:         $grouplist = '';
1.816     raeburn  9297:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9298:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9299:         my $access_end = $env{'course.'.$courseid.
                   9300:                               '.default_enrollment_end_date'};
                   9301:         my $now = time;
                   9302:         foreach my $key (keys(%roleshash)) {
                   9303:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9304:                 my $group = $1;
                   9305:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9306:                     my $start = $2;
                   9307:                     my $end = $1;
                   9308:                     if ($start == -1) { next; } # deleted from group
                   9309:                     if (($start!=0) && ($start>$now)) { next; }
                   9310:                     if (($end!=0) && ($end<$now)) {
                   9311:                         if ($access_end && $access_end < $now) {
                   9312:                             if ($access_end - $end < 86400) {
                   9313:                                 push(@usersgroups,$group);
1.733     raeburn  9314:                             }
                   9315:                         }
1.817     raeburn  9316:                         next;
1.733     raeburn  9317:                     }
1.817     raeburn  9318:                     push(@usersgroups,$group);
1.683     raeburn  9319:                 }
                   9320:             }
                   9321:         }
1.817     raeburn  9322:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9323:         $grouplist = join(':',@usersgroups);
                   9324:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9325:     }
1.733     raeburn  9326:     return @usersgroups;
1.683     raeburn  9327: }
                   9328: 
                   9329: sub devalidate_getgroups_cache {
                   9330:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9331:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9332: 
1.683     raeburn  9333:     my $hashid="$udom:$uname:$courseid";
                   9334:     &devalidate_cache_new('getgroups',$hashid);
                   9335: }
                   9336: 
1.12      www      9337: # ------------------------------------------------------------------ Plain Text
                   9338: 
                   9339: sub plaintext {
1.988     raeburn  9340:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9341:     if ($short =~ m{^cr/}) {
1.758     albertel 9342: 	return (split('/',$short))[-1];
                   9343:     }
1.742     raeburn  9344:     if (!defined($cid)) {
                   9345:         $cid = $env{'request.course.id'};
                   9346:     }
                   9347:     my %rolenames = (
1.1008    raeburn  9348:                       Course    => 'std',
                   9349:                       Community => 'alt1',
1.1305    raeburn  9350:                       Placement => 'std',
1.742     raeburn  9351:                     );
1.1037    raeburn  9352:     if ($cid ne '') {
                   9353:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9354:             unless ($forcedefault) {
                   9355:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9356:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9357:                 return &Apache::lonlocal::mt($roletext);
                   9358:             }
                   9359:         }
                   9360:     }
                   9361:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9362:         (defined($rolenames{$type})) && 
                   9363:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9364:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9365:     } elsif ($cid ne '') {
                   9366:         my $crstype = $env{'course.'.$cid.'.type'};
                   9367:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9368:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9369:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9370:         }
1.742     raeburn  9371:     }
1.1037    raeburn  9372:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9373: }
                   9374: 
                   9375: # ----------------------------------------------------------------- Assign Role
                   9376: 
                   9377: sub assignrole {
1.957     raeburn  9378:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9379:         $context)=@_;
1.21      www      9380:     my $mrole;
                   9381:     if ($role =~ /^cr\//) {
1.393     www      9382:         my $cwosec=$url;
1.811     albertel 9383:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9384: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9385:            my $refused = 1;
                   9386:            if ($context eq 'requestcourses') {
                   9387:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9388:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9389:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9390:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9391:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9392:                            if ($crsenv{'internal.courseowner'} eq
                   9393:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9394:                                $refused = '';
                   9395:                            }
                   9396:                        }
                   9397:                    }
                   9398:                }
                   9399:            }
                   9400:            if ($refused) {
                   9401:                &logthis('Refused custom assignrole: '.
                   9402:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9403:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9404:                return 'refused';
                   9405:            }
1.104     www      9406:         }
1.21      www      9407:         $mrole='cr';
1.678     raeburn  9408:     } elsif ($role =~ /^gr\//) {
                   9409:         my $cwogrp=$url;
1.811     albertel 9410:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9411:         unless (&allowed('mdg',$cwogrp)) {
                   9412:             &logthis('Refused group assignrole: '.
                   9413:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9414:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9415:             return 'refused';
                   9416:         }
                   9417:         $mrole='gr';
1.21      www      9418:     } else {
1.82      www      9419:         my $cwosec=$url;
1.811     albertel 9420:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9421:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9422:             my $refused;
                   9423:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9424:                 if (!(&allowed('c'.$role,$url))) {
                   9425:                     $refused = 1;
                   9426:                 }
                   9427:             } else {
                   9428:                 $refused = 1;
                   9429:             }
1.947     raeburn  9430:             if ($refused) {
1.1045    raeburn  9431:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9432:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9433:                     my %crsenv;
                   9434:                     if ($role eq 'cc' || $role eq 'co') {
                   9435:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9436:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9437:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9438:                                 if ($crsenv{'internal.courseowner'} eq 
                   9439:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9440:                                     $refused = '';
                   9441:                                 }
                   9442:                             }
                   9443:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9444:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9445:                                 if ($crsenv{'internal.courseowner'} eq 
                   9446:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9447:                                     $refused = '';
                   9448:                                 }
                   9449:                             }
                   9450:                         }
                   9451:                     }
1.1368    raeburn  9452:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9453:                     if ($role eq 'st') {
                   9454:                         $refused = '';
1.1377    raeburn  9455:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9456:                         $refused = '';
                   9457:                     }
1.1017    raeburn  9458:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9459:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9460:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9461:                         my $wrongcc;
                   9462:                         if ($cnum =~ /^$match_community$/) {
                   9463:                             $wrongcc = 1 if ($role eq 'cc');
                   9464:                         } else {
                   9465:                             $wrongcc = 1 if ($role eq 'co');
                   9466:                         }
                   9467:                         unless ($wrongcc) {
                   9468:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9469:                             if ($crsenv{'internal.courseowner'} eq 
                   9470:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9471:                                 $refused = '';
                   9472:                             }
1.1017    raeburn  9473:                         }
                   9474:                     }
1.1183    raeburn  9475:                 } elsif ($context eq 'requestauthor') {
                   9476:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9477:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9478:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9479:                             $refused = '';
                   9480:                         } else {
                   9481:                             my %domdefaults = &get_domain_defaults($udom);
                   9482:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9483:                                 my $checkbystatus;
                   9484:                                 if ($env{'user.adv'}) { 
                   9485:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9486:                                     if ($disposition eq 'automatic') {
                   9487:                                         $refused = '';
                   9488:                                     } elsif ($disposition eq '') {
                   9489:                                         $checkbystatus = 1;
                   9490:                                     } 
                   9491:                                 } else {
                   9492:                                     $checkbystatus = 1;
                   9493:                                 }
                   9494:                                 if ($checkbystatus) {
                   9495:                                     if ($env{'environment.inststatus'}) {
                   9496:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9497:                                         foreach my $type (@inststatuses) {
                   9498:                                             if (($type ne '') &&
                   9499:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9500:                                                 $refused = '';
                   9501:                                             }
                   9502:                                         }
                   9503:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9504:                                         $refused = '';
                   9505:                                     }
                   9506:                                 }
                   9507:                             }
                   9508:                         }
                   9509:                     }
1.1017    raeburn  9510:                 }
                   9511:                 if ($refused) {
1.947     raeburn  9512:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9513:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9514: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9515:                     return 'refused';
                   9516:                 }
1.932     raeburn  9517:             }
1.1131    raeburn  9518:         } elsif ($role eq 'au') {
                   9519:             if ($url ne '/'.$udom.'/') {
                   9520:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9521:                          ' to assign author role for '.$uname.':'.$udom.
                   9522:                          ' in domain: '.$url.' refused (wrong domain).');
                   9523:                 return 'refused';
                   9524:             }
1.104     www      9525:         }
1.21      www      9526:         $mrole=$role;
                   9527:     }
1.620     albertel 9528:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9529:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9530:     if ($end) { $command.='_'.$end; }
1.21      www      9531:     if ($start) {
                   9532: 	if ($end) { 
1.81      www      9533:            $command.='_'.$start; 
1.21      www      9534:         } else {
1.81      www      9535:            $command.='_0_'.$start;
1.21      www      9536:         }
                   9537:     }
1.739     raeburn  9538:     my $origstart = $start;
                   9539:     my $origend = $end;
1.957     raeburn  9540:     my $delflag;
1.357     www      9541: # actually delete
                   9542:     if ($deleteflag) {
1.373     www      9543: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9544: # modify command to delete the role
1.620     albertel 9545:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9546:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9547: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9548: # set start and finish to negative values for userrolelog
                   9549:            $start=-1;
                   9550:            $end=-1;
1.957     raeburn  9551:            $delflag = 1;
1.357     www      9552:         }
                   9553:     }
                   9554: # send command
1.349     www      9555:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9556: # log new user role if status is ok
1.349     www      9557:     if ($answer eq 'ok') {
1.663     raeburn  9558: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9559:         if (($role eq 'cc') || ($role eq 'in') ||
                   9560:             ($role eq 'ep') || ($role eq 'ad') ||
                   9561:             ($role eq 'ta') || ($role eq 'st') ||
                   9562:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9563:             ($role eq 'co')) {
1.1200    raeburn  9564: # for course roles, perform group memberships changes triggered by role change.
                   9565:             unless ($role =~ /^gr/) {
                   9566:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9567:                                                  $origstart,$selfenroll,$context);
                   9568:             }
1.1184    raeburn  9569:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9570:                            $selfenroll,$context);
                   9571:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9572:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9573:                  ($role eq 'da')) {
1.1184    raeburn  9574:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9575:                            $context);
                   9576:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9577:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9578:                              $context); 
                   9579:         }
1.1053    raeburn  9580:         if ($role eq 'cc') {
                   9581:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9582:         }
1.349     www      9583:     }
                   9584:     return $answer;
1.169     harris41 9585: }
                   9586: 
1.1053    raeburn  9587: sub autoupdate_coowners {
                   9588:     my ($url,$end,$start,$uname,$udom) = @_;
                   9589:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9590:     if (($cdom ne '') && ($cnum ne '')) {
                   9591:         my $now = time;
                   9592:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9593:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9594:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9595:             my $instcode = $coursehash{'internal.coursecode'};
                   9596:             if ($instcode ne '') {
1.1056    raeburn  9597:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9598:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9599:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9600:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9601:                         if ($result eq 'valid') {
                   9602:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9603:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9604:                                     push(@newcoowners,$coowner);
                   9605:                                 }
                   9606:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9607:                                     push(@newcoowners,$uname.':'.$udom);
                   9608:                                 }
                   9609:                                 @newcoowners = sort(@newcoowners);
                   9610:                             } else {
                   9611:                                 push(@newcoowners,$uname.':'.$udom);
                   9612:                             }
                   9613:                         } else {
                   9614:                             if ($coursehash{'internal.co-owners'}) {
                   9615:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9616:                                     unless ($coowner eq $uname.':'.$udom) {
                   9617:                                         push(@newcoowners,$coowner);
                   9618:                                     }
                   9619:                                 }
                   9620:                                 unless (@newcoowners > 0) {
                   9621:                                     $delcoowners = 1;
                   9622:                                     $coowners = '';
                   9623:                                 }
                   9624:                             }
                   9625:                         }
                   9626:                         if (@newcoowners || $delcoowners) {
                   9627:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9628:                                             $delcoowners,@newcoowners);
                   9629:                         }
                   9630:                     }
                   9631:                 }
                   9632:             }
                   9633:         }
                   9634:     }
                   9635: }
                   9636: 
                   9637: sub store_coowners {
                   9638:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9639:     my $cid = $cdom.'_'.$cnum;
                   9640:     my ($coowners,$delresult,$putresult);
                   9641:     if (@newcoowners) {
                   9642:         $coowners = join(',',@newcoowners);
                   9643:         my %coownershash = (
                   9644:                             'internal.co-owners' => $coowners,
                   9645:                            );
                   9646:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9647:         if ($putresult eq 'ok') {
                   9648:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9649:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9650:             }
                   9651:         }
                   9652:     }
                   9653:     if ($delcoowners) {
                   9654:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9655:         if ($delresult eq 'ok') {
                   9656:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9657:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9658:             }
                   9659:         }
                   9660:     }
                   9661:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9662:         my %crsinfo =
                   9663:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9664:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9665:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9666:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9667:         }
                   9668:     }
                   9669: }
                   9670: 
1.169     harris41 9671: # -------------------------------------------------- Modify user authentication
1.197     www      9672: # Overrides without validation
                   9673: 
1.169     harris41 9674: sub modifyuserauth {
                   9675:     my ($udom,$uname,$umode,$upass)=@_;
                   9676:     my $uhome=&homeserver($uname,$udom);
1.197     www      9677:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9678:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9679:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9680:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9681:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9682: 		     &escape($upass),$uhome);
1.620     albertel 9683:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9684:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9685:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9686:     &log($udom,,$uname,$uhome,
1.620     albertel 9687:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9688:                                      $env{'user.name'}.', '.$umode.
1.197     www      9689:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9690:     unless ($reply eq 'ok') {
1.197     www      9691:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9692: 	return 'error: '.$reply;
                   9693:     }   
1.170     harris41 9694:     return 'ok';
1.80      www      9695: }
                   9696: 
1.81      www      9697: # --------------------------------------------------------------- Modify a user
1.80      www      9698: 
1.81      www      9699: sub modifyuser {
1.206     matthew  9700:     my ($udom,    $uname, $uid,
                   9701:         $umode,   $upass, $first,
                   9702:         $middle,  $last,  $gene,
1.1058    raeburn  9703:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9704:     $udom= &LONCAPA::clean_domain($udom);
                   9705:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9706:     my $showcandelete = 'none';
                   9707:     if (ref($candelete) eq 'ARRAY') {
                   9708:         if (@{$candelete} > 0) {
                   9709:             $showcandelete = join(', ',@{$candelete});
                   9710:         }
                   9711:     }
1.81      www      9712:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9713:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9714: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9715:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9716:                                      ' desiredhome not specified'). 
1.620     albertel 9717:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9718:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9719:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9720:     my $newuser;
                   9721:     if ($uhome eq 'no_host') {
                   9722:         $newuser = 1;
1.1368    raeburn  9723:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9724:                 ($umode eq 'lti')) {
                   9725:             return 'error: more information needed to create new user';
                   9726:         }
1.1075    raeburn  9727:     }
1.80      www      9728: # ----------------------------------------------------------------- Create User
1.406     albertel 9729:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9730: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9731:         my $unhome='';
1.844     albertel 9732:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9733:             $unhome = $desiredhome;
1.620     albertel 9734: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9735: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9736:         } else { # load balancing routine for determining $unhome
1.81      www      9737:             my $loadm=10000000;
1.841     albertel 9738: 	    my %servers = &get_servers($udom,'library');
                   9739: 	    foreach my $tryserver (keys(%servers)) {
                   9740: 		my $answer=reply('load',$tryserver);
                   9741: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9742: 		    $loadm=$answer;
                   9743: 		    $unhome=$tryserver;
                   9744: 		}
1.80      www      9745: 	    }
                   9746:         }
                   9747:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9748: 	    return 'error: unable to find a home server for '.$uname.
                   9749:                    ' in domain '.$udom;
1.80      www      9750:         }
                   9751:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9752:                          &escape($upass),$unhome);
                   9753: 	unless ($reply eq 'ok') {
                   9754:             return 'error: '.$reply;
                   9755:         }   
1.230     stredwic 9756:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9757:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9758: 	    return 'error: unable verify users home machine.';
1.80      www      9759:         }
1.209     matthew  9760:     }   # End of creation of new user
1.80      www      9761: # ---------------------------------------------------------------------- Add ID
                   9762:     if ($uid) {
                   9763:        $uid=~tr/A-Z/a-z/;
                   9764:        my %uidhash=&idrget($udom,$uname);
1.196     www      9765:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9766:          && (!$forceid)) {
1.80      www      9767: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9768: 	      return 'error: user id "'.$uid.'" does not match '.
                   9769:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9770:           }
                   9771:        } else {
1.1300    raeburn  9772: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9773:        }
                   9774:     }
                   9775: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9776:     my @tmp=&get('environment',
1.899     raeburn  9777: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9778:                     'permanentemail','inststatus'],
1.134     albertel 9779: 		   $udom,$uname);
1.1075    raeburn  9780:     my (%names,%oldnames);
1.313     matthew  9781:     if ($tmp[0] =~ m/^error:.*/) { 
                   9782:         %names=(); 
                   9783:     } else {
                   9784:         %names = @tmp;
1.1075    raeburn  9785:         %oldnames = %names;
1.313     matthew  9786:     }
1.388     www      9787: #
1.1058    raeburn  9788: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9789: # of users did not contain them), do not overwrite existing values
                   9790: # unless field is in $candelete array ref.  
                   9791: #
                   9792: 
                   9793:     my @fields = ('firstname','middlename','lastname','generation',
                   9794:                   'permanentemail','id');
                   9795:     my %newvalues;
                   9796:     if (ref($candelete) eq 'ARRAY') {
                   9797:         foreach my $field (@fields) {
                   9798:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9799:                 if ($field eq 'firstname') {
                   9800:                     $names{$field} = $first;
                   9801:                 } elsif ($field eq 'middlename') {
                   9802:                     $names{$field} = $middle;
                   9803:                 } elsif ($field eq 'lastname') {
                   9804:                     $names{$field} = $last;
                   9805:                 } elsif ($field eq 'generation') { 
                   9806:                     $names{$field} = $gene;
                   9807:                 } elsif ($field eq 'permanentemail') {
                   9808:                     $names{$field} = $email;
                   9809:                 } elsif ($field eq 'id') {
                   9810:                     $names{$field}  = $uid;
                   9811:                 }
                   9812:             }
                   9813:         }
                   9814:     }
1.388     www      9815:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9816:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9817:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9818:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9819:     if ($email) {
                   9820:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9821:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9822:     }
1.899     raeburn  9823:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9824:     if (defined($inststatus)) {
                   9825:         $names{'inststatus'} = '';
                   9826:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9827:         if (ref($usertypes) eq 'HASH') {
                   9828:             my @okstatuses; 
                   9829:             foreach my $item (split(/:/,$inststatus)) {
                   9830:                 if (defined($usertypes->{$item})) {
                   9831:                     push(@okstatuses,$item);  
                   9832:                 }
                   9833:             }
                   9834:             if (@okstatuses) {
                   9835:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9836:             }
                   9837:         }
                   9838:     }
1.1075    raeburn  9839:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9840:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9841:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9842:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9843:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9844:     } else {
                   9845:         $logmsg .= ' during self creation';
                   9846:     }
1.1075    raeburn  9847:     my $changed;
                   9848:     if ($newuser) {
                   9849:         $changed = 1;
                   9850:     } else {
                   9851:         foreach my $field (@fields) {
                   9852:             if ($names{$field} ne $oldnames{$field}) {
                   9853:                 $changed = 1;
                   9854:                 last;
                   9855:             }
                   9856:         }
                   9857:     }
                   9858:     unless ($changed) {
                   9859:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9860:         &logthis($logmsg);
                   9861:         return 'ok';
                   9862:     }
                   9863:     my $reply = &put('environment', \%names, $udom,$uname);
                   9864:     if ($reply ne 'ok') { 
                   9865:         return 'error: '.$reply;
                   9866:     }
1.1087    raeburn  9867:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9868:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9869:     }
1.1075    raeburn  9870:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9871:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9872:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9873:     &logthis($logmsg);
1.134     albertel 9874:     return 'ok';
1.80      www      9875: }
                   9876: 
1.81      www      9877: # -------------------------------------------------------------- Modify student
1.80      www      9878: 
1.81      www      9879: sub modifystudent {
                   9880:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9881:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9882:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9883:     if (!$cid) {
1.620     albertel 9884: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9885: 	    return 'not_in_class';
                   9886: 	}
1.80      www      9887:     }
                   9888: # --------------------------------------------------------------- Make the user
1.81      www      9889:     my $reply=&modifyuser
1.209     matthew  9890: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9891:          $desiredhome,$email,$inststatus);
1.80      www      9892:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9893:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9894:     # student's environment
1.297     matthew  9895:     $uid = undef if (!$forceid);
1.455     albertel 9896:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9897:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9898:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9899:     return $reply;
                   9900: }
                   9901: 
                   9902: sub modify_student_enrollment {
1.1216    raeburn  9903:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9904:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9905:     my ($cdom,$cnum,$chome);
                   9906:     if (!$cid) {
1.620     albertel 9907: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9908: 	    return 'not_in_class';
                   9909: 	}
1.620     albertel 9910: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9911: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9912:     } else {
                   9913: 	($cdom,$cnum)=split(/_/,$cid);
                   9914:     }
1.620     albertel 9915:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9916:     if (!$chome) {
1.457     raeburn  9917: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9918:     }
1.455     albertel 9919:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9920:     # Make sure the user exists
1.81      www      9921:     my $uhome=&homeserver($uname,$udom);
                   9922:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9923: 	return 'error: no such user';
                   9924:     }
1.297     matthew  9925:     # Get student data if we were not given enough information
                   9926:     if (!defined($first)  || $first  eq '' || 
                   9927:         !defined($last)   || $last   eq '' || 
                   9928:         !defined($uid)    || $uid    eq '' || 
                   9929:         !defined($middle) || $middle eq '' || 
                   9930:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9931:         # They did not supply us with enough data to enroll the student, so
                   9932:         # we need to pick up more information.
1.297     matthew  9933:         my %tmp = &get('environment',
1.294     matthew  9934:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9935:                        ,$udom,$uname);
                   9936: 
1.800     albertel 9937:         #foreach my $key (keys(%tmp)) {
                   9938:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9939:         #}
1.294     matthew  9940:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9941:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9942:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9943:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9944:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9945:     }
1.556     albertel 9946:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9947:     my $user = "$uname:$udom";
                   9948:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9949:     my $reply=cput('classlist',
1.1148    raeburn  9950: 		   {$user => 
1.1314    raeburn  9951: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9952: 		   $cdom,$cnum);
1.1148    raeburn  9953:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9954:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9955:     } else { 
1.81      www      9956: 	return 'error: '.$reply;
                   9957:     }
1.297     matthew  9958:     # Add student role to user
1.83      www      9959:     my $uurl='/'.$cid;
1.81      www      9960:     $uurl=~s/\_/\//g;
                   9961:     if ($usec) {
                   9962: 	$uurl.='/'.$usec;
                   9963:     }
1.1148    raeburn  9964:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9965:                              $selfenroll,$context);
                   9966:     if ($result ne 'ok') {
                   9967:         if ($old_entry{$user} ne '') {
                   9968:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9969:         } else {
                   9970:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9971:         }
                   9972:     }
                   9973:     return $result; 
1.21      www      9974: }
                   9975: 
1.556     albertel 9976: sub format_name {
                   9977:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9978:     my $name;
                   9979:     if ($first ne 'lastname') {
                   9980: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9981:     } else {
                   9982: 	if ($lastname=~/\S/) {
                   9983: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9984: 	    $name=~s/\s+,/,/;
                   9985: 	} else {
                   9986: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9987: 	}
                   9988:     }
                   9989:     $name=~s/^\s+//;
                   9990:     $name=~s/\s+$//;
                   9991:     $name=~s/\s+/ /g;
                   9992:     return $name;
                   9993: }
                   9994: 
1.84      www      9995: # ------------------------------------------------- Write to course preferences
                   9996: 
                   9997: sub writecoursepref {
                   9998:     my ($courseid,%prefs)=@_;
                   9999:     $courseid=~s/^\///;
                   10000:     $courseid=~s/\_/\//g;
                   10001:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10002:     my $chome=homeserver($cnum,$cdomain);
                   10003:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10004: 	return 'error: no such course';
                   10005:     }
                   10006:     my $cstring='';
1.800     albertel 10007:     foreach my $pref (keys(%prefs)) {
                   10008: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10009:     }
1.84      www      10010:     $cstring=~s/\&$//;
                   10011:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10012: }
                   10013: 
                   10014: # ---------------------------------------------------------- Make/modify course
                   10015: 
                   10016: sub createcourse {
1.741     raeburn  10017:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10018:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10019:     $url=&declutter($url);
                   10020:     my $cid='';
1.1028    raeburn  10021:     if ($context eq 'requestcourses') {
                   10022:         my $can_create = 0;
                   10023:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10024:         if ($udom eq $ownerdom) {
                   10025:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10026:                                   $context)) {
                   10027:                 $can_create = 1;
                   10028:             }
                   10029:         } else {
                   10030:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10031:                                            $category);
                   10032:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10033:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10034:                 if (@curr > 0) {
                   10035:                     my @options = qw(approval validate autolimit);
                   10036:                     my $optregex = join('|',@options);
                   10037:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10038:                         $can_create = 1;
                   10039:                     }
                   10040:                 }
                   10041:             }
                   10042:         }
                   10043:         if ($can_create) {
                   10044:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10045:                 unless (&allowed('ccc',$udom)) {
                   10046:                     return 'refused'; 
                   10047:                 }
1.1017    raeburn  10048:             }
                   10049:         } else {
                   10050:             return 'refused';
                   10051:         }
1.1028    raeburn  10052:     } elsif (!&allowed('ccc',$udom)) {
                   10053:         return 'refused';
1.84      www      10054:     }
1.1011    raeburn  10055: # --------------------------------------------------------------- Get Unique ID
                   10056:     my $uname;
                   10057:     if ($cnum =~ /^$match_courseid$/) {
                   10058:         my $chome=&homeserver($cnum,$udom,'true');
                   10059:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10060:             $uname = $cnum;
                   10061:         } else {
1.1038    raeburn  10062:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10063:         }
                   10064:     } else {
1.1038    raeburn  10065:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10066:     }
                   10067:     return $uname if ($uname =~ /^error/);
                   10068: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10069:     if (!defined($course_server)) {
                   10070:         if (defined(&domain($udom,'primary'))) {
                   10071:             $course_server = &domain($udom,'primary');
                   10072:         } else {
                   10073:             $course_server = $env{'user.home'}; 
                   10074:         }
                   10075:     }
                   10076:     my %host_servers =
                   10077:         &Apache::lonnet::get_servers($udom,'library');
                   10078:     unless ($host_servers{$course_server}) {
                   10079:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10080:     }
1.84      www      10081: # ------------------------------------------------------------- Make the course
                   10082:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10083:                       $course_server);
1.84      www      10084:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10085:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10086:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10087: 	return 'error: no such course';
                   10088:     }
1.271     www      10089: # ----------------------------------------------------------------- Course made
1.516     raeburn  10090: # log existence
1.1029    raeburn  10091:     my $now = time;
1.918     raeburn  10092:     my $newcourse = {
                   10093:                     $udom.'_'.$uname => {
1.921     raeburn  10094:                                      description => $description,
                   10095:                                      inst_code   => $inst_code,
                   10096:                                      owner       => $course_owner,
                   10097:                                      type        => $crstype,
1.1029    raeburn  10098:                                      creator     => $env{'user.name'}.':'.
                   10099:                                                     $env{'user.domain'},
                   10100:                                      created     => $now,
                   10101:                                      context     => $context,
1.918     raeburn  10102:                                                 },
                   10103:                     };
1.921     raeburn  10104:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10105: # set toplevel url
1.271     www      10106:     my $topurl=$url;
                   10107:     unless ($nonstandard) {
                   10108: # ------------------------------------------ For standard courses, make top url
                   10109:         my $mapurl=&clutter($url);
1.278     www      10110:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10111:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10112: <map>
                   10113: <resource id="1" type="start"></resource>
                   10114: <resource id="2" src="$mapurl"></resource>
                   10115: <resource id="3" type="finish"></resource>
                   10116: <link index="1" from="1" to="2"></link>
                   10117: <link index="2" from="2" to="3"></link>
                   10118: </map>
                   10119: ENDINITMAP
                   10120:         $topurl=&declutter(
1.638     albertel 10121:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10122:                           );
                   10123:     }
                   10124: # ----------------------------------------------------------- Write preferences
1.84      www      10125:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10126:                      ('description'              => $description,
                   10127:                       'url'                      => $topurl,
                   10128:                       'internal.creator'         => $env{'user.name'}.':'.
                   10129:                                                     $env{'user.domain'},
                   10130:                       'internal.created'         => $now,
                   10131:                       'internal.creationcontext' => $context)
                   10132:                     );
1.84      www      10133:     return '/'.$udom.'/'.$uname;
                   10134: }
                   10135: 
1.1011    raeburn  10136: # ------------------------------------------------------------------- Create ID
                   10137: sub generate_coursenum {
1.1038    raeburn  10138:     my ($udom,$crstype) = @_;
1.1011    raeburn  10139:     my $domdesc = &domain($udom);
                   10140:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10141:     my $first;
                   10142:     if ($crstype eq 'Community') {
                   10143:         $first = '0';
                   10144:     } else {
                   10145:         $first = int(1+rand(9)); 
                   10146:     } 
                   10147:     my $uname=$first.
1.1011    raeburn  10148:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10149:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10150:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10151: # ----------------------------------------------- Make sure that does not exist
                   10152:     my $uhome=&homeserver($uname,$udom,'true');
                   10153:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10154:         if ($crstype eq 'Community') {
                   10155:             $first = '0';
                   10156:         } else {
                   10157:             $first = int(1+rand(9));
                   10158:         }
                   10159:         $uname=$first.
1.1011    raeburn  10160:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10161:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10162:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10163:         $uhome=&homeserver($uname,$udom,'true');
                   10164:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10165:             return 'error: unable to generate unique course-ID';
                   10166:         }
                   10167:     }
                   10168:     return $uname;
                   10169: }
                   10170: 
1.813     albertel 10171: sub is_course {
1.1167    droeschl 10172:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10173:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10174: 
1.1381    raeburn  10175:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10176:     my $uhome=&homeserver($cnum,$cdom);
                   10177:     my $iscourse;
                   10178:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10179:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10180:     } else {
                   10181:         my $hashid = $cdom.':'.$cnum;
                   10182:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10183:         unless (defined($cached)) {
                   10184:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10185:                                         $cnum,undef,undef,'.');
                   10186:             $iscourse = 0;
                   10187:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10188:                 $iscourse = 1;
                   10189:             }
                   10190:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10191:         }
                   10192:     }
                   10193:     return unless ($iscourse);
1.1167    droeschl 10194:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10195: }
                   10196: 
1.1015    raeburn  10197: sub store_userdata {
                   10198:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10199:     my $result;
1.1016    raeburn  10200:     if ($datakey ne '') {
1.1013    raeburn  10201:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10202:             if ($udom eq '' || $uname eq '') {
                   10203:                 $udom = $env{'user.domain'};
                   10204:                 $uname = $env{'user.name'};
                   10205:             }
                   10206:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10207:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10208:                 $result = 'error: no_host';
                   10209:             } else {
                   10210:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10211:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10212: 
                   10213:                 my $namevalue='';
                   10214:                 foreach my $key (keys(%{$storehash})) {
                   10215:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10216:                 }
                   10217:                 $namevalue=~s/\&$//;
1.1224    raeburn  10218:                 unless ($namespace eq 'courserequests') {
                   10219:                     $datakey = &escape($datakey);
                   10220:                 }
1.1105    raeburn  10221:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10222:                                   $namevalue,$uhome);
1.1013    raeburn  10223:             }
                   10224:         } else {
                   10225:             $result = 'error: data to store was not a hash reference'; 
                   10226:         }
                   10227:     } else {
                   10228:         $result= 'error: invalid requestkey'; 
                   10229:     }
                   10230:     return $result;
                   10231: }
                   10232: 
1.21      www      10233: # ---------------------------------------------------------- Assign Custom Role
                   10234: 
                   10235: sub assigncustomrole {
1.957     raeburn  10236:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10237:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10238:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10239: }
                   10240: 
                   10241: # ----------------------------------------------------------------- Revoke Role
                   10242: 
                   10243: sub revokerole {
1.957     raeburn  10244:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10245:     my $now=time;
1.965     raeburn  10246:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10247: }
                   10248: 
                   10249: # ---------------------------------------------------------- Revoke Custom Role
                   10250: 
                   10251: sub revokecustomrole {
1.957     raeburn  10252:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10253:     my $now=time;
1.357     www      10254:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10255:            $deleteflag,$selfenroll,$context);
1.17      www      10256: }
                   10257: 
1.533     banghart 10258: # ------------------------------------------------------------ Disk usage
1.535     albertel 10259: sub diskusage {
1.955     raeburn  10260:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10261:     $directorypath =~ s/\/$//;
                   10262:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10263:                        .&escape($getpropath).':'.&escape($uname).':'
                   10264:                        .&escape($udom),homeserver($uname,$udom));
                   10265:     if ($listing eq 'unknown_cmd') {
                   10266:         if ($getpropath) {
                   10267:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10268:         }
                   10269:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10270:     }
1.514     albertel 10271:     return $listing;
1.512     banghart 10272: }
                   10273: 
1.566     banghart 10274: sub is_locked {
1.1096    raeburn  10275:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10276:     my @check;
                   10277:     my $is_locked;
1.1093    raeburn  10278:     push (@check,$file_name);
1.613     albertel 10279:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10280: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10281:     my ($tmp)=keys(%locked);
                   10282:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10283:     
1.566     banghart 10284:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10285:         $is_locked = 'false';
                   10286:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10287:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10288:                $is_locked = 'true';
1.1096    raeburn  10289:                if (ref($which) eq 'ARRAY') {
                   10290:                    push(@{$which},$entry);
                   10291:                } else {
                   10292:                    last;
                   10293:                }
1.745     raeburn  10294:            }
                   10295:        }
1.566     banghart 10296:     } else {
                   10297:         $is_locked = 'false';
                   10298:     }
1.1093    raeburn  10299:     return $is_locked;
1.566     banghart 10300: }
                   10301: 
1.759     albertel 10302: sub declutter_portfile {
                   10303:     my ($file) = @_;
1.833     albertel 10304:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10305:     return $file;
                   10306: }
                   10307: 
1.559     banghart 10308: # ------------------------------------------------------------- Mark as Read Only
                   10309: 
                   10310: sub mark_as_readonly {
                   10311:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10312:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10313:     my ($tmp)=keys(%current_permissions);
                   10314:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10315:     foreach my $file (@{$files}) {
1.759     albertel 10316: 	$file = &declutter_portfile($file);
1.561     banghart 10317:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10318:     }
1.613     albertel 10319:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10320:     return;
                   10321: }
                   10322: 
1.572     banghart 10323: # ------------------------------------------------------------Save Selected Files
                   10324: 
                   10325: sub save_selected_files {
                   10326:     my ($user, $path, @files) = @_;
                   10327:     my $filename = $user."savedfiles";
1.573     banghart 10328:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10329:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10330:     foreach my $file (@files) {
1.620     albertel 10331:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10332:     }
                   10333:     foreach my $file (@other_files) {
1.574     banghart 10334:         print (OUT $file."\n");
1.572     banghart 10335:     }
1.574     banghart 10336:     close (OUT);
1.572     banghart 10337:     return 'ok';
                   10338: }
                   10339: 
1.574     banghart 10340: sub clear_selected_files {
                   10341:     my ($user) = @_;
                   10342:     my $filename = $user."savedfiles";
1.1359    raeburn  10343:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10344:     print (OUT undef);
                   10345:     close (OUT);
                   10346:     return ("ok");    
                   10347: }
                   10348: 
1.572     banghart 10349: sub files_in_path {
                   10350:     my ($user, $path) = @_;
                   10351:     my $filename = $user."savedfiles";
                   10352:     my %return_files;
1.1359    raeburn  10353:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10354:     while (my $line_in = <IN>) {
1.574     banghart 10355:         chomp ($line_in);
                   10356:         my @paths_and_file = split (m!/!, $line_in);
                   10357:         my $file_part = pop (@paths_and_file);
                   10358:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10359:         $path_part.='/';
                   10360:         my $path_and_file = $path_part.$file_part;
                   10361:         if ($path_part eq $path) {
                   10362:             $return_files{$file_part}= 'selected';
                   10363:         }
                   10364:     }
1.574     banghart 10365:     close (IN);
                   10366:     return (\%return_files);
1.572     banghart 10367: }
                   10368: 
                   10369: # called in portfolio select mode, to show files selected NOT in current directory
                   10370: sub files_not_in_path {
                   10371:     my ($user, $path) = @_;
                   10372:     my $filename = $user."savedfiles";
                   10373:     my @return_files;
                   10374:     my $path_part;
1.1359    raeburn  10375:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10376:     while (my $line = <IN>) {
1.572     banghart 10377:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10378:         my @paths_and_file = split(m|/|, $line);
                   10379:         my $file_part = pop(@paths_and_file);
                   10380:         chomp($file_part);
                   10381:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10382:         $path_part .= '/';
                   10383:         my $path_and_file = $path_part.$file_part;
                   10384:         if ($path_part ne $path) {
1.800     albertel 10385:             push(@return_files, ($path_and_file));
1.572     banghart 10386:         }
                   10387:     }
1.800     albertel 10388:     close(OUT);
1.574     banghart 10389:     return (@return_files);
1.572     banghart 10390: }
                   10391: 
1.1273    raeburn  10392: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10393:  
                   10394: sub portfiles_versioning {
                   10395:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10396:     my $portfolio_root = '/userfiles/portfolio';
                   10397:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10398:     foreach my $file (@{$portfiles}) {
                   10399:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10400:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10401:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10402:         my $getpropath = 1;
                   10403:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10404:                                              $stu_name,$getpropath);
                   10405:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10406:         my $new_answer = 
                   10407:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10408:         if ($new_answer ne 'problem getting file') {
                   10409:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10410:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10411:                               [$symb,$env{'request.course.id'},'graded']);
                   10412:         }
                   10413:     }
                   10414: }
                   10415: 
                   10416: sub get_next_version {
                   10417:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10418:     my $version;
                   10419:     if (ref($dir_list) eq 'ARRAY') {
                   10420:         foreach my $row (@{$dir_list}) {
                   10421:             my ($file) = split(/\&/,$row,2);
                   10422:             my ($file_name,$file_version,$file_ext) =
                   10423:                 &file_name_version_ext($file);
                   10424:             if (($file_name eq $answer_name) &&
                   10425:                 ($file_ext eq $answer_ext)) {
                   10426:                      # gets here if filename and extension match,
                   10427:                      # regardless of version
                   10428:                 if ($file_version ne '') {
                   10429:                     # a versioned file is found  so save it for later
                   10430:                     if ($file_version > $version) {
                   10431:                         $version = $file_version;
                   10432:                     }
                   10433:                 }
                   10434:             }
                   10435:         }
                   10436:     }
                   10437:     $version ++;
                   10438:     return($version);
                   10439: }
                   10440: 
                   10441: sub version_selected_portfile {
                   10442:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10443:     my ($answer_name,$answer_ver,$answer_ext) =
                   10444:         &file_name_version_ext($file_name);
                   10445:     my $new_answer;
                   10446:     $env{'form.copy'} =
                   10447:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10448:     if($env{'form.copy'} eq '-1') {
                   10449:         $new_answer = 'problem getting file';
                   10450:     } else {
                   10451:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10452:         my $copy_result = 
                   10453:             &finishuserfileupload($stu_name,$domain,'copy',
                   10454:                                   '/portfolio'.$directory.$new_answer);
                   10455:     }
                   10456:     undef($env{'form.copy'});
                   10457:     return ($new_answer);
                   10458: }
                   10459: 
                   10460: sub file_name_version_ext {
                   10461:     my ($file)=@_;
                   10462:     my @file_parts = split(/\./, $file);
                   10463:     my ($name,$version,$ext);
                   10464:     if (@file_parts > 1) {
                   10465:         $ext=pop(@file_parts);
                   10466:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10467:             $version=pop(@file_parts);
                   10468:         }
                   10469:         $name=join('.',@file_parts);
                   10470:     } else {
                   10471:         $name=join('.',@file_parts);
                   10472:     }
                   10473:     return($name,$version,$ext);
                   10474: }
                   10475: 
1.745     raeburn  10476: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10477: 
1.745     raeburn  10478: sub get_portfile_permissions {
                   10479:     my ($domain,$user) = @_;
1.613     albertel 10480:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10481:     my ($tmp)=keys(%current_permissions);
                   10482:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10483:     return \%current_permissions;
                   10484: }
                   10485: 
                   10486: #---------------------------------------------Get portfolio file access controls
                   10487: 
1.749     raeburn  10488: sub get_access_controls {
1.745     raeburn  10489:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10490:     my %access;
                   10491:     my $real_file = $file;
                   10492:     $file =~ s/\.meta$//;
1.745     raeburn  10493:     if (defined($file)) {
1.749     raeburn  10494:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10495:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10496:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10497:             }
                   10498:         }
1.745     raeburn  10499:     } else {
1.749     raeburn  10500:         foreach my $key (keys(%{$current_permissions})) {
                   10501:             if ($key =~ /\0accesscontrol$/) {
                   10502:                 if (defined($group)) {
                   10503:                     if ($key !~ m-^\Q$group\E/-) {
                   10504:                         next;
                   10505:                     }
                   10506:                 }
                   10507:                 my ($fullpath) = split(/\0/,$key);
                   10508:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10509:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10510:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10511:                     }
                   10512:                 }
                   10513:             }
                   10514:         }
                   10515:     }
                   10516:     return %access;
                   10517: }
                   10518: 
                   10519: sub modify_access_controls {
                   10520:     my ($file_name,$changes,$domain,$user)=@_;
                   10521:     my ($outcome,$deloutcome);
                   10522:     my %store_permissions;
                   10523:     my %new_values;
                   10524:     my %new_control;
                   10525:     my %translation;
                   10526:     my @deletions = ();
                   10527:     my $now = time;
                   10528:     if (exists($$changes{'activate'})) {
                   10529:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10530:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10531:             my $numnew = scalar(@newitems);
                   10532:             for (my $i=0; $i<$numnew; $i++) {
                   10533:                 my $newkey = $newitems[$i];
                   10534:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10535:                 if ($newkey =~ /^\d+:/) { 
                   10536:                     $newkey =~ s/^(\d+)/$newid/;
                   10537:                     $translation{$1} = $newid;
                   10538:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10539:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10540:                     $translation{$1} = $newid;
                   10541:                 }
1.749     raeburn  10542:                 $new_values{$file_name."\0".$newkey} = 
                   10543:                                           $$changes{'activate'}{$newitems[$i]};
                   10544:                 $new_control{$newkey} = $now;
                   10545:             }
                   10546:         }
                   10547:     }
                   10548:     my %todelete;
                   10549:     my %changed_items;
                   10550:     foreach my $action ('delete','update') {
                   10551:         if (exists($$changes{$action})) {
                   10552:             if (ref($$changes{$action}) eq 'HASH') {
                   10553:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10554:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10555:                     if ($action eq 'delete') { 
                   10556:                         $todelete{$itemnum} = 1;
                   10557:                     } else {
                   10558:                         $changed_items{$itemnum} = $key;
                   10559:                     }
                   10560:                 }
1.745     raeburn  10561:             }
                   10562:         }
1.749     raeburn  10563:     }
                   10564:     # get lock on access controls for file.
                   10565:     my $lockhash = {
                   10566:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10567:                                                        ':'.$env{'user.domain'},
                   10568:                    }; 
                   10569:     my $tries = 0;
                   10570:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10571:    
1.1288    damieng  10572:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10573:         $tries ++;
1.1289    damieng  10574:         sleep(0.1);
1.749     raeburn  10575:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10576:     }
                   10577:     if ($gotlock eq 'ok') {
                   10578:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10579:         my ($tmp)=keys(%curr_permissions);
                   10580:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10581:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10582:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10583:             if (ref($curr_controls) eq 'HASH') {
                   10584:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10585:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10586:                     if (defined($todelete{$itemnum})) {
                   10587:                         push(@deletions,$file_name."\0".$control_item);
                   10588:                     } else {
                   10589:                         if (defined($changed_items{$itemnum})) {
                   10590:                             $new_control{$changed_items{$itemnum}} = $now;
                   10591:                             push(@deletions,$file_name."\0".$control_item);
                   10592:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10593:                         } else {
                   10594:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10595:                         }
                   10596:                     }
1.745     raeburn  10597:                 }
                   10598:             }
                   10599:         }
1.970     raeburn  10600:         my ($group);
                   10601:         if (&is_course($domain,$user)) {
                   10602:             ($group,my $file) = split(/\//,$file_name,2);
                   10603:         }
1.749     raeburn  10604:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10605:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10606:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10607:         #  remove lock
                   10608:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10609:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10610:         my $sqlresult =
1.970     raeburn  10611:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10612:                                     $group);
1.749     raeburn  10613:     } else {
                   10614:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10615:     }
1.749     raeburn  10616:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10617: }
                   10618: 
1.827     raeburn  10619: sub make_public_indefinitely {
1.1271    raeburn  10620:     my (@requrl) = @_;
                   10621:     return &automated_portfile_access('public',\@requrl);
                   10622: }
                   10623: 
                   10624: sub automated_portfile_access {
                   10625:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10626:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10627:         return 'invalid';
                   10628:     }
1.1271    raeburn  10629:     my %urls;
                   10630:     if (ref($addsref) eq 'ARRAY') {
                   10631:         foreach my $requrl (@{$addsref}) {
                   10632:             if (&is_portfolio_url($requrl)) {
                   10633:                 unless (exists($urls{$requrl})) {
                   10634:                     $urls{$requrl} = 'add';
                   10635:                 }
                   10636:             }
                   10637:         }
                   10638:     }
                   10639:     if (ref($delsref) eq 'ARRAY') {
                   10640:         foreach my $requrl (@{$delsref}) { 
                   10641:             if (&is_portfolio_url($requrl)) {
                   10642:                 unless (exists($urls{$requrl})) {
                   10643:                     $urls{$requrl} = 'delete'; 
                   10644:                 }
                   10645:             }
                   10646:         }
                   10647:     }
                   10648:     unless (keys(%urls)) {
                   10649:         return 'invalid';
                   10650:     }
                   10651:     my $ip;
                   10652:     if ($accesstype eq 'ip') {
                   10653:         if (ref($info) eq 'HASH') {
                   10654:             if ($info->{'ip'} ne '') {
                   10655:                 $ip = $info->{'ip'};
                   10656:             }
                   10657:         }
                   10658:         if ($ip eq '') {
                   10659:             return 'invalid';
                   10660:         }
                   10661:     }
                   10662:     my $errors;
1.827     raeburn  10663:     my $now = time;
1.1271    raeburn  10664:     my %current_perms;
                   10665:     foreach my $requrl (sort(keys(%urls))) {
                   10666:         my $action;
                   10667:         if ($urls{$requrl} eq 'add') {
                   10668:             $action = 'activate';
                   10669:         } else {
                   10670:             $action = 'none';
                   10671:         }
                   10672:         my $aclnum = 0;
1.827     raeburn  10673:         my (undef,$udom,$unum,$file_name,$group) =
                   10674:             &parse_portfolio_url($requrl);
1.1271    raeburn  10675:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10676:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10677:         }
                   10678:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10679:                                                    $group,$file_name);
                   10680:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10681:             my ($num,$scope,$end,$start) = 
                   10682:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10683:             if ($scope eq $accesstype) {
                   10684:                 if (($start <= $now) && ($end == 0)) {
                   10685:                     if ($accesstype eq 'ip') {
                   10686:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10687:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10688:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10689:                                     if ($urls{$requrl} eq 'add') {
                   10690:                                         $action = 'none';
                   10691:                                         last;
                   10692:                                     } else {
                   10693:                                         $action = 'delete';
                   10694:                                         $aclnum = $num;
                   10695:                                         last;
                   10696:                                     }
                   10697:                                 }
                   10698:                             }
                   10699:                         }
                   10700:                     } elsif ($accesstype eq 'public') {
                   10701:                         if ($urls{$requrl} eq 'add') {
                   10702:                             $action = 'none';
                   10703:                             last;
                   10704:                         } else {
                   10705:                             $action = 'delete';
                   10706:                             $aclnum = $num;
                   10707:                             last;
                   10708:                         }
                   10709:                     }
                   10710:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10711:                     $action = 'update';
                   10712:                     $aclnum = $num;
1.1271    raeburn  10713:                     last;
1.827     raeburn  10714:                 }
                   10715:             }
                   10716:         }
                   10717:         if ($action eq 'none') {
1.1271    raeburn  10718:             next;
1.827     raeburn  10719:         } else {
                   10720:             my %changes;
                   10721:             my $newend = 0;
                   10722:             my $newstart = $now;
1.1271    raeburn  10723:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10724:             $changes{$action}{$newkey} = {
1.1271    raeburn  10725:                 type => $accesstype,
1.827     raeburn  10726:                 time => {
                   10727:                     start => $newstart,
                   10728:                     end   => $newend,
                   10729:                 },
                   10730:             };
1.1271    raeburn  10731:             if ($accesstype eq 'ip') {
                   10732:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10733:             }
1.827     raeburn  10734:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10735:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10736:             unless ($outcome eq 'ok') {
                   10737:                 $errors .= $outcome.' ';
                   10738:             }
1.827     raeburn  10739:         }
1.1271    raeburn  10740:     }
                   10741:     if ($errors) {
                   10742:         $errors =~ s/\s$//;
                   10743:         return $errors;
1.827     raeburn  10744:     } else {
1.1271    raeburn  10745:         return 'ok';
1.827     raeburn  10746:     }
                   10747: }
                   10748: 
1.745     raeburn  10749: #------------------------------------------------------Get Marked as Read Only
                   10750: 
                   10751: sub get_marked_as_readonly {
                   10752:     my ($domain,$user,$what,$group) = @_;
                   10753:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10754:     my @readonly_files;
1.629     banghart 10755:     my $cmp1=$what;
                   10756:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10757:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10758:         if (defined($group)) {
                   10759:             if ($file_name !~ m-^\Q$group\E/-) {
                   10760:                 next;
                   10761:             }
                   10762:         }
1.561     banghart 10763:         if (ref($value) eq "ARRAY"){
                   10764:             foreach my $stored_what (@{$value}) {
1.629     banghart 10765:                 my $cmp2=$stored_what;
1.759     albertel 10766:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10767:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10768:                 }
1.629     banghart 10769:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10770:                     push(@readonly_files, $file_name);
1.745     raeburn  10771:                     last;
1.563     banghart 10772:                 } elsif (!defined($what)) {
                   10773:                     push(@readonly_files, $file_name);
1.745     raeburn  10774:                     last;
1.561     banghart 10775:                 }
                   10776:             }
1.745     raeburn  10777:         }
1.561     banghart 10778:     }
                   10779:     return @readonly_files;
                   10780: }
1.577     banghart 10781: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10782: 
1.577     banghart 10783: sub get_marked_as_readonly_hash {
1.745     raeburn  10784:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10785:     my %readonly_files;
1.745     raeburn  10786:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10787:         if (defined($group)) {
                   10788:             if ($file_name !~ m-^\Q$group\E/-) {
                   10789:                 next;
                   10790:             }
                   10791:         }
1.577     banghart 10792:         if (ref($value) eq "ARRAY"){
                   10793:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10794:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10795:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10796:                         if ($lock_descriptor eq 'graded') {
                   10797:                             $readonly_files{$file_name} = 'graded';
                   10798:                         } elsif ($lock_descriptor eq 'handback') {
                   10799:                             $readonly_files{$file_name} = 'handback';
                   10800:                         } else {
                   10801:                             if (!exists($readonly_files{$file_name})) {
                   10802:                                 $readonly_files{$file_name} = 'locked';
                   10803:                             }
                   10804:                         }
1.745     raeburn  10805:                     }
1.750     banghart 10806:                 } 
1.577     banghart 10807:             }
                   10808:         } 
                   10809:     }
                   10810:     return %readonly_files;
                   10811: }
1.559     banghart 10812: # ------------------------------------------------------------ Unmark as Read Only
                   10813: 
                   10814: sub unmark_as_readonly {
1.629     banghart 10815:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10816:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10817:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10818:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10819:     my $symb_crs = $what;
                   10820:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10821:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10822:     my ($tmp)=keys(%current_permissions);
                   10823:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10824:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10825:     foreach my $file (@readonly_files) {
1.759     albertel 10826: 	my $clean_file = &declutter_portfile($file);
                   10827: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10828: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10829:         my @new_locks;
                   10830:         my @del_keys;
                   10831:         if (ref($current_locks) eq "ARRAY"){
                   10832:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10833:                 my $compare=$locker;
1.749     raeburn  10834:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10835:                     $compare=join('',@{$locker});
1.746     raeburn  10836:                     if ($compare ne $symb_crs) {
                   10837:                         push(@new_locks, $locker);
                   10838:                     }
1.563     banghart 10839:                 }
                   10840:             }
1.650     albertel 10841:             if (scalar(@new_locks) > 0) {
1.563     banghart 10842:                 $current_permissions{$file} = \@new_locks;
                   10843:             } else {
                   10844:                 push(@del_keys, $file);
1.613     albertel 10845:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10846:                 delete($current_permissions{$file});
1.563     banghart 10847:             }
                   10848:         }
1.561     banghart 10849:     }
1.613     albertel 10850:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10851:     return;
                   10852: }
1.512     banghart 10853: 
1.17      www      10854: # ------------------------------------------------------------ Directory lister
                   10855: 
                   10856: sub dirlist {
1.955     raeburn  10857:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10858:     $uri=~s/^\///;
                   10859:     $uri=~s/\/$//;
1.253     stredwic 10860:     my ($udom, $uname);
1.955     raeburn  10861:     if ($getuserdir) {
1.253     stredwic 10862:         $udom = $userdomain;
                   10863:         $uname = $username;
1.955     raeburn  10864:     } else {
                   10865:         (undef,$udom,$uname)=split(/\//,$uri);
                   10866:         if(defined($userdomain)) {
                   10867:             $udom = $userdomain;
                   10868:         }
                   10869:         if(defined($username)) {
                   10870:             $uname = $username;
                   10871:         }
1.253     stredwic 10872:     }
1.955     raeburn  10873:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10874: 
1.955     raeburn  10875:     $dirRoot = $perlvar{'lonDocRoot'};
                   10876:     if (defined($getpropath)) {
                   10877:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10878:         $dirRoot =~ s/\/$//;
1.955     raeburn  10879:     } elsif (defined($getuserdir)) {
                   10880:         my $subdir=$uname.'__';
                   10881:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10882:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10883:                    ."/$udom/$subdir/$uname";
                   10884:     } elsif (defined($alternateRoot)) {
                   10885:         $dirRoot = $alternateRoot;
1.751     banghart 10886:     }
1.253     stredwic 10887: 
                   10888:     if($udom) {
                   10889:         if($uname) {
1.1135    raeburn  10890:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10891:             if ($uhome eq 'no_host') {
                   10892:                 return ([],'no_host');
                   10893:             }
1.955     raeburn  10894:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10895:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10896:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10897:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10898:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10899:             } else {
                   10900:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10901:             }
1.605     matthew  10902:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10903:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10904:                 @listing_results = split(/:/,$listing);
                   10905:             } else {
                   10906:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10907:             }
1.1135    raeburn  10908:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10909:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10910:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10911:                 return ([],$listing);
                   10912:             } else {
                   10913:                 return (\@listing_results);
1.1135    raeburn  10914:             }
1.955     raeburn  10915:         } elsif(!$alternateRoot) {
1.1136    raeburn  10916:             my (%allusers,%listerror);
1.841     albertel 10917: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10918:  	    foreach my $tryserver (keys(%servers)) {
                   10919:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10920:                                   &escape($udom),$tryserver);
                   10921:                 if ($listing eq 'unknown_cmd') {
                   10922: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10923: 				      $udom, $tryserver);
                   10924:                 } else {
                   10925:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10926:                 }
1.841     albertel 10927: 		if ($listing eq 'unknown_cmd') {
                   10928: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10929: 				      $udom, $tryserver);
                   10930: 		    @listing_results = split(/:/,$listing);
                   10931: 		} else {
                   10932: 		    @listing_results =
                   10933: 			map { &unescape($_); } split(/:/,$listing);
                   10934: 		}
1.1136    raeburn  10935:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10936:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10937:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10938:                     $listerror{$tryserver} = $listing;
                   10939:                 } else {
1.841     albertel 10940: 		    foreach my $line (@listing_results) {
                   10941: 			my ($entry) = split(/&/,$line,2);
                   10942: 			$allusers{$entry} = 1;
                   10943: 		    }
                   10944: 		}
1.253     stredwic 10945:             }
1.1136    raeburn  10946:             my @alluserslist=();
1.800     albertel 10947:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10948:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10949:             }
1.1318    droeschl 10950: 
                   10951:             if (!%listerror) {
                   10952:                 # no errors
                   10953:                 return (\@alluserslist);
                   10954:             } elsif (scalar(keys(%servers)) == 1) {
                   10955:                 # one library server, one error 
                   10956:                 my ($key) = keys(%listerror);
                   10957:                 return (\@alluserslist, $listerror{$key});
                   10958:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10959:                 # con_lost indicates that we might miss data from at least one
                   10960:                 # library server
                   10961:                 return (\@alluserslist, 'con_lost');
                   10962:             } else {
                   10963:                 # multiple library servers and no con_lost -> data should be
                   10964:                 # complete. 
                   10965:                 return (\@alluserslist);
                   10966:             }
                   10967: 
1.253     stredwic 10968:         } else {
1.1136    raeburn  10969:             return ([],'missing username');
1.253     stredwic 10970:         }
1.955     raeburn  10971:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10972:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10973:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10974:         return (\@all_domains);
1.955     raeburn  10975:     } else {
1.1136    raeburn  10976:         return ([],'missing domain');
1.275     stredwic 10977:     }
                   10978: }
                   10979: 
                   10980: # --------------------------------------------- GetFileTimestamp
                   10981: # This function utilizes dirlist and returns the date stamp for
                   10982: # when it was last modified.  It will also return an error of -1
                   10983: # if an error occurs
                   10984: 
                   10985: sub GetFileTimestamp {
1.955     raeburn  10986:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10987:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10988:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10989:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10990:                                     undef,$getuserdir);
                   10991:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10992:         return -1;
                   10993:     }
                   10994:     if (ref($fileref) eq 'ARRAY') {
                   10995:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10996:         # @stats contains first the filename, then the stat output
                   10997:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10998:     } else {
                   10999:         return -1;
1.253     stredwic 11000:     }
1.26      www      11001: }
                   11002: 
1.712     albertel 11003: sub stat_file {
                   11004:     my ($uri) = @_;
1.787     albertel 11005:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11006: 
1.955     raeburn  11007:     my ($udom,$uname,$file);
1.712     albertel 11008:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11009: 	($udom,$uname,$file) =
1.811     albertel 11010: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11011: 	$file = 'userfiles/'.$file;
                   11012:     }
                   11013:     if ($uri =~ m-^/res/-) {
                   11014: 	($udom,$uname) = 
1.807     albertel 11015: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11016: 	$file = $uri;
                   11017:     }
                   11018: 
                   11019:     if (!$udom || !$uname || !$file) {
                   11020: 	# unable to handle the uri
                   11021: 	return ();
                   11022:     }
1.956     raeburn  11023:     my $getpropath;
                   11024:     if ($file =~ /^userfiles\//) {
                   11025:         $getpropath = 1;
                   11026:     }
1.1136    raeburn  11027:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11028:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11029:         return ();
                   11030:     } else {
                   11031:         if (ref($listref) eq 'ARRAY') {
                   11032:             my @stats = split('&',$listref->[0]);
                   11033: 	    shift(@stats); #filename is first
                   11034: 	    return @stats;
                   11035:         }
1.712     albertel 11036:     }
                   11037:     return ();
                   11038: }
                   11039: 
1.1313    raeburn  11040: # --------------------------------------------------------- recursedirs
                   11041: # Recursive function to traverse either a specific user's Authoring Space
                   11042: # or corresponding Published Resource Space, and populate the hash ref:
                   11043: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11044: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11045: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11046: # files in Authoring Space.
                   11047: #
                   11048: # Inputs:
                   11049: #
                   11050: # $is_home - true if current server is home server for user's space
                   11051: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11052: # $docroot - Document root (i.e., /home/httpd/html
                   11053: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11054: # $relpath - Current path (relative to top level).
                   11055: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11056: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11057: #
                   11058: # Returns: nothing
                   11059: #
                   11060: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11061: #
                   11062: # Currently used by interface/londocs.pm to create linked select boxes for
                   11063: # directory and filename to import a Course "Author" resource into a course, and
                   11064: # also to create linked select boxes for Authoring Space and Directory to choose
                   11065: # save location for creation of a new "standard" problem from the Course Editor.
                   11066: #
                   11067: 
                   11068: sub recursedirs {
                   11069:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11070:     return unless (ref($dirhashref) eq 'HASH');
                   11071:     my $currpath = $docroot.$toppath;
                   11072:     if ($relpath) {
                   11073:         $currpath .= "/$relpath";
                   11074:     }
                   11075:     my $savefile;
                   11076:     if (ref($filehashref)) {
                   11077:         $savefile = 1;
                   11078:     }
                   11079:     if ($is_home) {
                   11080:         if (opendir(my $dirh,$currpath)) {
                   11081:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11082:                 next if ($item eq '');
                   11083:                 if (-d "$currpath/$item") {
                   11084:                     my $newpath;
                   11085:                     if ($relpath) {
                   11086:                         $newpath = "$relpath/$item";
                   11087:                     } else {
                   11088:                         $newpath = $item;
                   11089:                     }
                   11090:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11091:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11092:                 } elsif ($savefile) {
                   11093:                     if ($context eq 'priv') {
                   11094:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11095:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11096:                         }
                   11097:                     } else {
                   11098:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11099:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11100:                         }
                   11101:                     }
                   11102:                 }
                   11103:             }
                   11104:             closedir($dirh);
                   11105:         }
                   11106:     } else {
                   11107:         my ($dirlistref,$listerror) =
                   11108:             &dirlist($toppath.$relpath);
                   11109:         my @dir_lines;
                   11110:         my $dirptr=16384;
                   11111:         if (ref($dirlistref) eq 'ARRAY') {
                   11112:             foreach my $dir_line (sort
                   11113:                               {
                   11114:                                   my ($afile)=split('&',$a,2);
                   11115:                                   my ($bfile)=split('&',$b,2);
                   11116:                                   return (lc($afile) cmp lc($bfile));
                   11117:                               } (@{$dirlistref})) {
                   11118:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11119:                     split(/\&/,$dir_line,16);
                   11120:                 $item =~ s/\s+$//;
                   11121:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11122:                 if ($dirptr&$testdir) {
                   11123:                     my $newpath;
                   11124:                     if ($relpath) {
                   11125:                         $newpath = "$relpath/$item";
                   11126:                     } else {
                   11127:                         $relpath = '/';
                   11128:                         $newpath = $item;
                   11129:                     }
                   11130:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11131:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11132:                 } elsif ($savefile) {
                   11133:                     if ($context eq 'priv') {
                   11134:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11135:                             $filehashref->{$relpath}{$item} = 1;
                   11136:                         }
                   11137:                     } else {
                   11138:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11139:                             $filehashref->{$relpath}{$item} = 1;
                   11140:                         }
                   11141:                     }
                   11142:                 }
                   11143:             }
                   11144:         }
                   11145:     }
                   11146:     return;
                   11147: }
                   11148: 
1.26      www      11149: # -------------------------------------------------------- Value of a Condition
                   11150: 
1.713     albertel 11151: # gets the value of a specific preevaluated condition
                   11152: #    stored in the string  $env{user.state.<cid>}
                   11153: # or looks up a condition reference in the bighash and if if hasn't
                   11154: # already been evaluated recurses into docondval to get the value of
                   11155: # the condition, then memoizing it to 
                   11156: #   $env{user.state.<cid>.<condition>}
1.40      www      11157: sub directcondval {
                   11158:     my $number=shift;
1.620     albertel 11159:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11160: 	&Apache::lonuserstate::evalstate();
                   11161:     }
1.713     albertel 11162:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11163: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11164:     } elsif ($number =~ /^_/) {
                   11165: 	my $sub_condition;
                   11166: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11167: 		&GDBM_READER(),0640)) {
                   11168: 	    $sub_condition=$bighash{'conditions'.$number};
                   11169: 	    untie(%bighash);
                   11170: 	}
                   11171: 	my $value = &docondval($sub_condition);
1.949     raeburn  11172: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11173: 	return $value;
                   11174:     }
1.620     albertel 11175:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11176:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11177:     } else {
                   11178:        return 2;
                   11179:     }
                   11180: }
                   11181: 
1.713     albertel 11182: # get the collection of conditions for this resource
1.26      www      11183: sub condval {
                   11184:     my $condidx=shift;
1.54      www      11185:     my $allpathcond='';
1.713     albertel 11186:     foreach my $cond (split(/\|/,$condidx)) {
                   11187: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11188: 	    $allpathcond.=
                   11189: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11190: 	}
1.191     harris41 11191:     }
1.54      www      11192:     $allpathcond=~s/\|$//;
1.713     albertel 11193:     return &docondval($allpathcond);
                   11194: }
                   11195: 
                   11196: #evaluates an expression of conditions
                   11197: sub docondval {
                   11198:     my ($allpathcond) = @_;
                   11199:     my $result=0;
                   11200:     if ($env{'request.course.id'}
                   11201: 	&& defined($allpathcond)) {
                   11202: 	my $operand='|';
                   11203: 	my @stack;
                   11204: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11205: 	    if ($chunk eq '(') {
                   11206: 		push @stack,($operand,$result);
                   11207: 	    } elsif ($chunk eq ')') {
                   11208: 		my $before=pop @stack;
                   11209: 		if (pop @stack eq '&') {
                   11210: 		    $result=$result>$before?$before:$result;
                   11211: 		} else {
                   11212: 		    $result=$result>$before?$result:$before;
                   11213: 		}
                   11214: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11215: 		$operand=$chunk;
                   11216: 	    } else {
                   11217: 		my $new=directcondval($chunk);
                   11218: 		if ($operand eq '&') {
                   11219: 		    $result=$result>$new?$new:$result;
                   11220: 		} else {
                   11221: 		    $result=$result>$new?$result:$new;
                   11222: 		}
                   11223: 	    }
                   11224: 	}
1.26      www      11225:     }
                   11226:     return $result;
1.421     albertel 11227: }
                   11228: 
                   11229: # ---------------------------------------------------- Devalidate courseresdata
                   11230: 
                   11231: sub devalidatecourseresdata {
                   11232:     my ($coursenum,$coursedomain)=@_;
                   11233:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11234:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11235: }
                   11236: 
1.763     www      11237: 
1.200     www      11238: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11239: #
                   11240: #  Parameters:
                   11241: #      $coursenum    - Number of the course.
                   11242: #      $coursedomain - Domain at which the course was created.
                   11243: #  Returns:
                   11244: #     A hash of the course parameters along (I think) with timestamps
                   11245: #     and version info.
1.877     foxr     11246: 
1.624     albertel 11247: sub get_courseresdata {
                   11248:     my ($coursenum,$coursedomain)=@_;
1.200     www      11249:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11250:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11251:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11252:     my %dumpreply;
1.417     albertel 11253:     unless (defined($cached)) {
1.624     albertel 11254: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11255: 	$result=\%dumpreply;
1.251     albertel 11256: 	my ($tmp) = keys(%dumpreply);
                   11257: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11258: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11259: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11260: 	    return $tmp;
1.416     albertel 11261: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11262: 	    $result=undef;
1.599     albertel 11263: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11264: 	}
                   11265:     }
1.624     albertel 11266:     return $result;
                   11267: }
                   11268: 
1.633     albertel 11269: sub devalidateuserresdata {
                   11270:     my ($uname,$udom)=@_;
                   11271:     my $hashid="$udom:$uname";
                   11272:     &devalidate_cache_new('userres',$hashid);
                   11273: }
                   11274: 
1.624     albertel 11275: sub get_userresdata {
                   11276:     my ($uname,$udom)=@_;
                   11277:     #most student don\'t have any data set, check if there is some data
                   11278:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11279: 
                   11280:     my $hashid="$udom:$uname";
                   11281:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11282:     if (!defined($cached)) {
                   11283: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11284: 	$result=\%resourcedata;
                   11285: 	&do_cache_new('userres',$hashid,$result,600);
                   11286:     }
                   11287:     my ($tmp)=keys(%$result);
                   11288:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11289: 	return $result;
                   11290:     }
                   11291:     #error 2 occurs when the .db doesn't exist
                   11292:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11293:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11294: 	    &logthis("<font color=\"blue\">WARNING:".
                   11295: 		     " Trying to get resource data for ".
                   11296: 		     $uname." at ".$udom.": ".
                   11297: 		     $tmp."</font>");
                   11298:         }
1.624     albertel 11299:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11300: 	#&EXT_cache_set($udom,$uname);
                   11301: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11302: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11303:     }
                   11304:     return $tmp;
                   11305: }
1.879     foxr     11306: #----------------------------------------------- resdata - return resource data
                   11307: #  Purpose:
                   11308: #    Return resource data for either users or for a course.
                   11309: #  Parameters:
                   11310: #     $name      - Course/user name.
                   11311: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11312: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11313: #     $mapp      - decluttered URL of enclosing map  
                   11314: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11315: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11316: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11317: #     $courseid  - CourseID (first part of param identifier).
                   11318: #     $modifier  - Middle part of param identifier.
                   11319: #     $what      - Last part of param identifier.
1.879     foxr     11320: #     @which     - Array of names of resources desired.
                   11321: #  Returns:
                   11322: #     The value of the first reasource in @which that is found in the
                   11323: #     resource hash.
                   11324: #  Exceptional Conditions:
                   11325: #     If the $type passed in is not valid (not the string 'course' or 
                   11326: #     'user', an undefined  reference is returned.
                   11327: #     If none of the resources are found, an undef is returned
1.624     albertel 11328: sub resdata {
1.1301    raeburn  11329:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11330:         $modifier,$what,@which)=@_;
1.624     albertel 11331:     my $result;
                   11332:     if ($type eq 'course') {
                   11333: 	$result=&get_courseresdata($name,$domain);
                   11334:     } elsif ($type eq 'user') {
                   11335: 	$result=&get_userresdata($name,$domain);
                   11336:     }
                   11337:     if (!ref($result)) { return $result; }    
1.251     albertel 11338:     foreach my $item (@which) {
1.1301    raeburn  11339:         if ($item->[1] eq 'course') {
                   11340:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11341:                 unless ($$recursed) {
1.1302    raeburn  11342:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11343:                     $$recursed = 1;
                   11344:                 }
                   11345:                 foreach my $item (@${recurseup}) {
                   11346:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11347:                     last if (defined($result->{$norecursechk}));
                   11348:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11349:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11350:                 }
                   11351:             }
                   11352:         }
                   11353:         if (defined($result->{$item->[0]})) {
1.927     albertel 11354: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11355: 	}
1.250     albertel 11356:     }
1.291     albertel 11357:     return undef;
1.200     www      11358: }
                   11359: 
1.1360    raeburn  11360: sub get_domain_lti {
                   11361:     my ($cdom,$context) = @_;
                   11362:     my ($name,%lti);
                   11363:     if ($context eq 'consumer') {
                   11364:         $name = 'ltitools';
                   11365:     } elsif ($context eq 'provider') {
                   11366:         $name = 'lti';
                   11367:     } else {
                   11368:         return %lti;
                   11369:     }
                   11370:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11371:     if (defined($cached)) {
                   11372:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11373:             %lti = %{$result};
1.1298    raeburn  11374:         }
                   11375:     } else {
1.1360    raeburn  11376:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11377:         if (ref($domconfig{$name}) eq 'HASH') {
                   11378:             %lti = %{$domconfig{$name}};
                   11379:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11380:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11381:                 foreach my $id (keys(%lti)) {
                   11382:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11383:                         foreach my $item ('key','secret') {
1.1360    raeburn  11384:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11385:                         }
                   11386:                     }
                   11387:                 }
                   11388:             }
1.1298    raeburn  11389:         }
                   11390:         my $cachetime = 24*60*60;
1.1360    raeburn  11391:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11392:     }
1.1360    raeburn  11393:     return %lti;
1.1298    raeburn  11394: }
                   11395: 
1.1236    raeburn  11396: sub get_numsuppfiles {
                   11397:     my ($cnum,$cdom,$ignorecache)=@_;
                   11398:     my $hashid=$cnum.':'.$cdom;
                   11399:     my ($suppcount,$cached);
                   11400:     unless ($ignorecache) {
                   11401:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11402:     }
                   11403:     unless (defined($cached)) {
                   11404:         my $chome=&homeserver($cnum,$cdom);
                   11405:         unless ($chome eq 'no_host') {
1.1366    raeburn  11406:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11407:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11408:             ($suppcount,$supptools,$errors) =
                   11409:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11410:                                                          $supptools,$errors);
1.1236    raeburn  11411:         }
                   11412:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11413:     }
                   11414:     return $suppcount;
                   11415: }
                   11416: 
1.379     matthew  11417: #
                   11418: # EXT resource caching routines
                   11419: #
                   11420: 
1.1302    raeburn  11421: {
                   11422: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11423: #
                   11424: # The course for which we cache
                   11425: my $cachedmapkey='';
                   11426: # The cached recursive maps for this course
                   11427: my %cachedmaps=();
                   11428: # When this was last done
                   11429: my $cachedmaptime='';
                   11430: 
1.379     matthew  11431: sub clear_EXT_cache_status {
1.383     albertel 11432:     &delenv('cache.EXT.');
1.379     matthew  11433: }
                   11434: 
                   11435: sub EXT_cache_status {
                   11436:     my ($target_domain,$target_user) = @_;
1.383     albertel 11437:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11438:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11439:         # We know already the user has no data
                   11440:         return 1;
                   11441:     } else {
                   11442:         return 0;
                   11443:     }
                   11444: }
                   11445: 
                   11446: sub EXT_cache_set {
                   11447:     my ($target_domain,$target_user) = @_;
1.383     albertel 11448:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11449:     #&appenv({$cachename => time});
1.379     matthew  11450: }
                   11451: 
1.28      www      11452: # --------------------------------------------------------- Value of a Variable
1.58      www      11453: sub EXT {
1.715     albertel 11454: 
1.1228    raeburn  11455:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11456:     unless ($varname) { return ''; }
1.218     albertel 11457:     #get real user name/domain, courseid and symb
                   11458:     my $courseid;
1.359     albertel 11459:     my $publicuser;
1.427     www      11460:     if ($symbparm) {
                   11461: 	$symbparm=&get_symb_from_alias($symbparm);
                   11462:     }
1.218     albertel 11463:     if (!($uname && $udom)) {
1.790     albertel 11464:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11465:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11466:     } else {
1.620     albertel 11467: 	$courseid=$env{'request.course.id'};
1.218     albertel 11468:     }
1.48      www      11469:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11470:     my $rest;
1.320     albertel 11471:     if (defined($therest[0])) {
1.48      www      11472:        $rest=join('.',@therest);
                   11473:     } else {
                   11474:        $rest='';
                   11475:     }
1.320     albertel 11476: 
1.57      www      11477:     my $qualifierrest=$qualifier;
                   11478:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11479:     my $spacequalifierrest=$space;
                   11480:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11481:     if ($realm eq 'user') {
1.48      www      11482: # --------------------------------------------------------------- user.resource
                   11483: 	if ($space eq 'resource') {
1.651     albertel 11484: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11485: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11486: 		 &&
1.744     albertel 11487: 		 ($symbparm eq &symbread()) ) {	
                   11488: 		# if we are in the middle of processing the resource the
                   11489: 		# get the value we are planning on committing
                   11490:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11491:                     return $Apache::lonhomework::results{$qualifierrest};
                   11492:                 } else {
                   11493:                     return $Apache::lonhomework::history{$qualifierrest};
                   11494:                 }
1.335     albertel 11495: 	    } else {
1.359     albertel 11496: 		my %restored;
1.620     albertel 11497: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11498: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11499: 		} else {
                   11500: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11501: 		}
1.335     albertel 11502: 		return $restored{$qualifierrest};
                   11503: 	    }
1.48      www      11504: # ----------------------------------------------------------------- user.access
                   11505:         } elsif ($space eq 'access') {
1.218     albertel 11506: 	    # FIXME - not supporting calls for a specific user
1.48      www      11507:             return &allowed($qualifier,$rest);
                   11508: # ------------------------------------------ user.preferences, user.environment
                   11509:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11510: 	    if (($uname eq $env{'user.name'}) &&
                   11511: 		($udom eq $env{'user.domain'})) {
                   11512: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11513: 	    } else {
1.359     albertel 11514: 		my %returnhash;
                   11515: 		if (!$publicuser) {
                   11516: 		    %returnhash=&userenvironment($udom,$uname,
                   11517: 						 $qualifierrest);
                   11518: 		}
1.218     albertel 11519: 		return $returnhash{$qualifierrest};
                   11520: 	    }
1.48      www      11521: # ----------------------------------------------------------------- user.course
                   11522:         } elsif ($space eq 'course') {
1.218     albertel 11523: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11524:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11525: # ------------------------------------------------------------------- user.role
                   11526:         } elsif ($space eq 'role') {
1.218     albertel 11527: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11528:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11529:             if ($qualifier eq 'value') {
                   11530: 		return $role;
                   11531:             } elsif ($qualifier eq 'extent') {
                   11532:                 return $where;
                   11533:             }
                   11534: # ----------------------------------------------------------------- user.domain
                   11535:         } elsif ($space eq 'domain') {
1.218     albertel 11536:             return $udom;
1.48      www      11537: # ------------------------------------------------------------------- user.name
                   11538:         } elsif ($space eq 'name') {
1.218     albertel 11539:             return $uname;
1.48      www      11540: # ---------------------------------------------------- Any other user namespace
1.29      www      11541:         } else {
1.359     albertel 11542: 	    my %reply;
                   11543: 	    if (!$publicuser) {
                   11544: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11545: 	    }
                   11546: 	    return $reply{$qualifierrest};
1.48      www      11547:         }
1.236     www      11548:     } elsif ($realm eq 'query') {
                   11549: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11550:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11551: 						[$spacequalifierrest]);
1.620     albertel 11552: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11553:    } elsif ($realm eq 'request') {
1.48      www      11554: # ------------------------------------------------------------- request.browser
                   11555:         if ($space eq 'browser') {
1.1145    bisitz   11556:             return $env{'browser.'.$qualifier};
1.57      www      11557: # ------------------------------------------------------------ request.filename
                   11558:         } else {
1.620     albertel 11559:             return $env{'request.'.$spacequalifierrest};
1.29      www      11560:         }
1.28      www      11561:     } elsif ($realm eq 'course') {
1.48      www      11562: # ---------------------------------------------------------- course.description
1.620     albertel 11563:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11564:     } elsif ($realm eq 'resource') {
1.165     www      11565: 
1.620     albertel 11566: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11567: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11568: 	}
1.693     albertel 11569: 
1.1232    raeburn  11570:         if ($qualifier eq '') {
                   11571: 	    if ($space eq 'title') {
                   11572: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11573: 	        return &gettitle($symbparm);
                   11574: 	    }
1.693     albertel 11575: 	
1.1232    raeburn  11576: 	    if ($space eq 'map') {
                   11577: 	        my ($map) = &decode_symb($symbparm);
                   11578: 	        return &symbread($map);
                   11579: 	    }
                   11580:             if ($space eq 'maptitle') {
                   11581:                 my ($map) = &decode_symb($symbparm);
                   11582:                 return &gettitle($map);
                   11583:             }
                   11584: 	    if ($space eq 'filename') {
                   11585: 	        if ($symbparm) {
                   11586: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11587: 	        }
                   11588: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11589: 	    }
1.1232    raeburn  11590: 
1.1233    raeburn  11591:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11592:                 if ($space eq 'visibleparts') {
                   11593:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11594:                     my $item;
                   11595:                     if (ref($navmap)) {
                   11596:                         my $res = $navmap->getBySymb($symbparm);
                   11597:                         my $parts = $res->parts();
                   11598:                         if (ref($parts) eq 'ARRAY') {
                   11599:                             $item = join(',',@{$parts});
                   11600:                         }
                   11601:                         undef($navmap);
1.1232    raeburn  11602:                     }
1.1233    raeburn  11603:                     return $item;
1.1232    raeburn  11604:                 }
                   11605:             }
                   11606:         }
1.693     albertel 11607: 
1.1301    raeburn  11608: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11609: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11610:         if (($courseid eq '') && ($cid)) {
                   11611:             $courseid = $cid;
                   11612:         }
                   11613: 	if (($symbparm && $courseid) && 
                   11614: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11615: 
1.218     albertel 11616: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11617: 
1.60      www      11618: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11619: 	    my $symbp=$symbparm;
1.1301    raeburn  11620: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11621: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11622:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11623: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11624: 	    if (($env{'user.name'} eq $uname) &&
                   11625: 		($env{'user.domain'} eq $udom)) {
                   11626: 		$section=$env{'request.course.sec'};
1.733     raeburn  11627:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11628:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11629: 	    } else {
1.539     albertel 11630: 		if (! defined($usection)) {
1.551     albertel 11631: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11632: 		} else {
                   11633: 		    $section = $usection;
                   11634: 		}
1.733     raeburn  11635:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11636: 	    }
                   11637: 
                   11638: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11639: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11640:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11641: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11642: 
1.593     albertel 11643: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11644: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11645:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11646: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11647: 
1.60      www      11648: # ----------------------------------------------------------- first, check user
1.624     albertel 11649: 
1.1301    raeburn  11650: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11651:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11652: 				       ([$courselevelr,'resource'],
                   11653: 					[$courselevelm,'map'     ],
1.1301    raeburn  11654:                                         [$courseleveli,'map'     ],
1.927     albertel 11655: 					[$courselevel, 'course'  ]));
1.931     albertel 11656: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11657: 
1.594     albertel 11658: # ------------------------------------------------ second, check some of course
1.684     raeburn  11659:             my $coursereply;
1.691     raeburn  11660:             if (@groups > 0) {
                   11661:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11662:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11663:                                        $mapp,\$recursed,\@recurseup);
                   11664:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11665:             }
1.96      www      11666: 
1.684     raeburn  11667: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11668: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11669: 				  'course',$mapp,\$recursed,\@recurseup,
                   11670:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11671: 				  ([$seclevelr,   'resource'],
                   11672: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11673:                                    [$secleveli,   'map'     ],
1.927     albertel 11674: 				   [$seclevel,    'course'  ],
                   11675: 				   [$courselevelr,'resource']));
                   11676: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11677: 
1.60      www      11678: # ------------------------------------------------------ third, check map parms
1.218     albertel 11679: 	    my %parmhash=();
                   11680: 	    my $thisparm='';
                   11681: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11682: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11683: 		    &GDBM_READER(),0640)) {
1.218     albertel 11684: 		$thisparm=$parmhash{$symbparm};
                   11685: 		untie(%parmhash);
                   11686: 	    }
1.927     albertel 11687: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11688: 	}
1.594     albertel 11689: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11690:  
                   11691:         my $what = $spacequalifierrest;
                   11692: 	$what=~s/\./\_/;
1.282     albertel 11693: 	my $filename;
                   11694: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11695: 	if ($symbparm) {
1.409     www      11696: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11697: 	} else {
1.620     albertel 11698: 	    $filename=$env{'request.filename'};
1.282     albertel 11699: 	}
1.1362    raeburn  11700:         my $toolsymb;
                   11701:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11702:             $toolsymb = $symbparm;
                   11703:         }
                   11704: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11705: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11706: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11707: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11708: 
1.1301    raeburn  11709: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11710: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11711: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11712: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11713: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11714: 				     'course',$mapp,\$recursed,\@recurseup,
                   11715:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11716: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11717:                                       [$courseleveli,'map'   ],
1.927     albertel 11718: 				      [$courselevel, 'course']));
                   11719: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11720: 	}
1.145     www      11721: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11722: 	unless ($space eq '0') {
1.336     albertel 11723: 	    my @parts=split(/_/,$space);
                   11724: 	    my $id=pop(@parts);
                   11725: 	    my $part=join('_',@parts);
                   11726: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11727: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11728: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11729: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11730: 	}
1.395     albertel 11731: 	if ($recurse) { return undef; }
1.1362    raeburn  11732: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11733: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11734: # ---------------------------------------------------- Any other user namespace
                   11735:     } elsif ($realm eq 'environment') {
                   11736: # ----------------------------------------------------------------- environment
1.620     albertel 11737: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11738: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11739: 	} else {
1.770     albertel 11740: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11741: 		return '';
                   11742: 	    }
1.219     albertel 11743: 	    my %returnhash=&userenvironment($udom,$uname,
                   11744: 					    $spacequalifierrest);
                   11745: 	    return $returnhash{$spacequalifierrest};
                   11746: 	}
1.28      www      11747:     } elsif ($realm eq 'system') {
1.48      www      11748: # ----------------------------------------------------------------- system.time
                   11749: 	if ($space eq 'time') {
                   11750: 	    return time;
                   11751:         }
1.696     albertel 11752:     } elsif ($realm eq 'server') {
                   11753: # ----------------------------------------------------------------- system.time
                   11754: 	if ($space eq 'name') {
                   11755: 	    return $ENV{'SERVER_NAME'};
                   11756:         }
1.28      www      11757:     }
1.48      www      11758:     return '';
1.61      www      11759: }
                   11760: 
1.927     albertel 11761: sub get_reply {
                   11762:     my ($reply_value) = @_;
1.940     raeburn  11763:     if (ref($reply_value) eq 'ARRAY') {
                   11764:         if (wantarray) {
                   11765: 	    return @$reply_value;
                   11766:         }
                   11767:         return $reply_value->[0];
                   11768:     } else {
                   11769:         return $reply_value;
1.927     albertel 11770:     }
                   11771: }
                   11772: 
1.691     raeburn  11773: sub check_group_parms {
1.1301    raeburn  11774:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11775:         $recursed,$recurseupref) = @_;
                   11776:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11777:                   [$what,'course']);
                   11778:     my $coursereply;
1.691     raeburn  11779:     foreach my $group (@{$groups}) {
1.1301    raeburn  11780:         my @groupitems = ();
1.691     raeburn  11781:         foreach my $level (@levels) {
1.927     albertel 11782:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11783:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11784:         }
1.1301    raeburn  11785:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11786:                                    $env{'course.'.$courseid.'.domain'},
                   11787:                                    'course',$mapp,$recursed,$recurseupref,
                   11788:                                    $courseid,'.['.$group.'].',$what,
                   11789:                                    @groupitems);
                   11790:         last if (defined($coursereply));
1.691     raeburn  11791:     }
                   11792:     return $coursereply;
                   11793: }
                   11794: 
1.1301    raeburn  11795: sub get_map_hierarchy {
1.1302    raeburn  11796:     my ($mapname,$courseid) = @_;
                   11797:     my @recurseup = ();
1.1301    raeburn  11798:     if ($mapname) {
1.1302    raeburn  11799:         if (($cachedmapkey eq $courseid) &&
                   11800:             (abs($cachedmaptime-time)<5)) {
                   11801:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11802:                 return @{$cachedmaps{$mapname}};
                   11803:             }
                   11804:         }
1.1301    raeburn  11805:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11806:         if (ref($navmap)) {
                   11807:             @recurseup = $navmap->recurseup_maps($mapname);
                   11808:             undef($navmap);
1.1302    raeburn  11809:             $cachedmaps{$mapname} = \@recurseup;
                   11810:             $cachedmaptime=time;
                   11811:             $cachedmapkey=$courseid;
1.1301    raeburn  11812:         }
                   11813:     }
                   11814:     return @recurseup;
                   11815: }
                   11816: 
1.1302    raeburn  11817: }
                   11818: 
1.691     raeburn  11819: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11820:     my ($courseid,@groups) = @_;
                   11821:     @groups = sort(@groups);
1.691     raeburn  11822:     return @groups;
                   11823: }
                   11824: 
1.395     albertel 11825: sub packages_tab_default {
1.1362    raeburn  11826:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11827:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11828: 
                   11829:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11830:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11831: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11832: 	if ($pack_type eq 'default') {
                   11833: 	    $do_default=1;
                   11834: 	} elsif ($pack_type eq 'extension') {
                   11835: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11836: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11837: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11838: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11839: 	}
                   11840:     }
                   11841:     # first look for a package that matches the requested part id
                   11842:     foreach my $package (@specifics) {
                   11843: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11844: 	next if ($pack_part ne $part);
                   11845: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11846: 	    return $packagetab{"$pack_type&$name&default"};
                   11847: 	}
                   11848:     }
                   11849:     # look for any possible matching non extension_ package
                   11850:     foreach my $package (@specifics) {
                   11851: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11852: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11853: 	    return $packagetab{"$pack_type&$name&default"};
                   11854: 	}
1.585     albertel 11855: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11856: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11857: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11858: 	}
                   11859:     }
1.738     albertel 11860:     # look for any posible extension_ match
                   11861:     foreach my $package (@extension) {
                   11862: 	my ($package,$pack_type)=@{$package};
                   11863: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11864: 	    return $packagetab{"$pack_type&$name&default"};
                   11865: 	}
                   11866: 	if (defined($packagetab{$package."&$name&default"})) {
                   11867: 	    return $packagetab{$package."&$name&default"};
                   11868: 	}
                   11869:     }
                   11870:     # look for a global default setting
                   11871:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11872: 	return $packagetab{"default&$name&default"};
                   11873:     }
1.395     albertel 11874:     return undef;
                   11875: }
                   11876: 
1.334     albertel 11877: sub add_prefix_and_part {
                   11878:     my ($prefix,$part)=@_;
                   11879:     my $keyroot;
                   11880:     if (defined($prefix) && $prefix !~ /^__/) {
                   11881: 	# prefix that has a part already
                   11882: 	$keyroot=$prefix;
                   11883:     } elsif (defined($prefix)) {
                   11884: 	# prefix that is missing a part
                   11885: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11886:     } else {
                   11887: 	# no prefix at all
                   11888: 	if (defined($part)) { $keyroot='_'.$part; }
                   11889:     }
                   11890:     return $keyroot;
                   11891: }
                   11892: 
1.71      www      11893: # ---------------------------------------------------------------- Get metadata
                   11894: 
1.599     albertel 11895: my %metaentry;
1.1070    www      11896: my %importedpartids;
1.1369    raeburn  11897: my %importedrespids;
1.71      www      11898: sub metadata {
1.1362    raeburn  11899:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11900:     $uri=&declutter($uri);
1.288     albertel 11901:     # if it is a non metadata possible uri return quickly
1.529     albertel 11902:     if (($uri eq '') || 
                   11903: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11904: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11905:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11906: 	return undef;
                   11907:     }
1.1261    raeburn  11908:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11909: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11910: 	return undef;
1.288     albertel 11911:     }
1.73      www      11912:     my $filename=$uri;
                   11913:     $uri=~s/\.meta$//;
1.172     www      11914: #
                   11915: # Is the metadata already cached?
1.177     www      11916: # Look at timestamp of caching
1.172     www      11917: # Everything is cached by the main uri, libraries are never directly cached
                   11918: #
1.428     albertel 11919:     if (!defined($liburi)) {
1.599     albertel 11920: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11921: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11922:     }
1.1362    raeburn  11923: 
                   11924: #
                   11925: # If the uri is for an external tool the file from
                   11926: # which metadata should be retrieved depends on whether
                   11927: # the tool had been configured to be gradable (set in the Course
                   11928: # Editor or Resource Editor).
                   11929: #
                   11930: # If a valid symb has been included as the third arg in the call
                   11931: # to &metadata() that can be used to retrieve the value of
                   11932: # parameter_0_gradable set for the resource, and included in the
                   11933: # uploaded map containing the tool. The value is retrieved via
                   11934: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11935: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11936: # is retrieved via &get().
                   11937: #
                   11938: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11939: # hiddenresource and encrypturl (during course initialization)
                   11940: # the map-level parameter for resource.0.gradable included in the 
                   11941: # uploaded map containing the tool will not yet have been stored
                   11942: # in the user_course_parms.db file for the user's session, so in 
                   11943: # this case fall back to retrieving gradable status from the
                   11944: # exttool_$marker.db file.
1.1362    raeburn  11945: #
                   11946: # In order to avoid an infinite loop, &metadata() will return
                   11947: # before a call to &EXT(), if the uri is for an external tool
                   11948: # and the $what for which metadata is being requested is
                   11949: # parameter_0_gradable or 0_gradable.
                   11950: #
                   11951: 
                   11952:     if ($uri =~ /ext\.tool$/) {
                   11953:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11954:             return;
                   11955:         } else {
                   11956:             my ($checked,$use_passback);
                   11957:             if ($toolsymb ne '') {
                   11958:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11959:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11960:                     $checked = 1;
                   11961:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11962:                         $use_passback = 1;
                   11963:                     }
                   11964:                 }
                   11965:             }
                   11966:             unless ($checked) {
                   11967:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11968:                 $marker=~s/\D//g;
1.1363    raeburn  11969:                 if ($marker) {
1.1362    raeburn  11970:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11971:                     $use_passback = $toolsettings{'gradable'};
                   11972:                 }
                   11973:             }
                   11974:             if ($use_passback) {
                   11975:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11976:             } else {
                   11977:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11978:             }
                   11979:         }
                   11980:     }
                   11981: 
1.428     albertel 11982:     {
1.1069    www      11983: # Imported parts would go here
1.1369    raeburn  11984:         my @origfiletagids=();
1.1069    www      11985:         my $importedparts=0;
1.1369    raeburn  11986: 
                   11987: # Imported responseids would go here
                   11988:         my $importedresponses=0;
1.172     www      11989: #
                   11990: # Is this a recursive call for a library?
                   11991: #
1.599     albertel 11992: #	if (! exists($metacache{$uri})) {
                   11993: #	    $metacache{$uri}={};
                   11994: #	}
1.924     albertel 11995: 	my $cachetime = 60*60;
1.171     www      11996:         if ($liburi) {
                   11997: 	    $liburi=&declutter($liburi);
                   11998:             $filename=$liburi;
1.401     bowersj2 11999:         } else {
1.599     albertel 12000: 	    &devalidate_cache_new('meta',$uri);
                   12001: 	    undef(%metaentry);
1.401     bowersj2 12002: 	}
1.140     www      12003:         my %metathesekeys=();
1.73      www      12004:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12005: 	my $metastring;
1.1140    www      12006: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12007: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12008: 	    $metastring = 
1.929     albertel 12009: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12010: 					  ('grade_target' => 'meta'));
                   12011: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12012: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12013:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12014: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12015: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12016: 	    $metastring=&getfile($file);
1.489     albertel 12017: 	}
1.208     albertel 12018:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12019:         my $token;
1.140     www      12020:         undef %metathesekeys;
1.71      www      12021:         while ($token=$parser->get_token) {
1.339     albertel 12022: 	    if ($token->[0] eq 'S') {
                   12023: 		if (defined($token->[2]->{'package'})) {
1.172     www      12024: #
                   12025: # This is a package - get package info
                   12026: #
1.339     albertel 12027: 		    my $package=$token->[2]->{'package'};
                   12028: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12029: 		    if (defined($token->[2]->{'id'})) { 
                   12030: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12031: 		    }
1.599     albertel 12032: 		    if ($metaentry{':packages'}) {
                   12033: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12034: 		    } else {
1.599     albertel 12035: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12036: 		    }
1.736     albertel 12037: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12038: 			my $part=$keyroot;
                   12039: 			$part=~s/^\_//;
1.736     albertel 12040: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12041: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12042: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12043: 			    # ignore package.tab specified default values
                   12044:                             # here &package_tab_default() will fetch those
                   12045: 			    if ($subp eq 'default') { next; }
1.736     albertel 12046: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12047: 			    my $unikey;
                   12048: 			    if ($pack =~ /_0$/) {
                   12049: 				$unikey='parameter_0_'.$name;
                   12050: 				$part=0;
                   12051: 			    } else {
                   12052: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12053: 			    }
1.339     albertel 12054: 			    if ($subp eq 'display') {
                   12055: 				$value.=' [Part: '.$part.']';
                   12056: 			    }
1.599     albertel 12057: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12058: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12059: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12060: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12061: 			    }
1.599     albertel 12062: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12063: 				$metaentry{':'.$unikey}=
                   12064: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12065: 			    }
1.339     albertel 12066: 			}
                   12067: 		    }
                   12068: 		} else {
1.172     www      12069: #
                   12070: # This is not a package - some other kind of start tag
1.339     albertel 12071: #
                   12072: 		    my $entry=$token->[1];
1.1068    www      12073: 		    my $unikey='';
1.175     www      12074: 
1.339     albertel 12075: 		    if ($entry eq 'import') {
1.175     www      12076: #
                   12077: # Importing a library here
1.339     albertel 12078: #
1.1067    www      12079:                         my $location=$parser->get_text('/import');
                   12080:                         my $dir=$filename;
                   12081:                         $dir=~s|[^/]*$||;
                   12082:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12083: 
                   12084:                         my $importid=$token->[2]->{'id'};
1.1068    www      12085:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12086: #
                   12087: # Check metadata for imported file to
                   12088: # see if it contained response items
                   12089: #
1.1372    raeburn  12090:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12091:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12092:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12093:                                                            $depthcount+1));
                   12094:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12095:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12096:                                                              undef,$depthcount+1);
                   12097:                             if ($libresponseorder ne '') {
                   12098:                                 if ($#origfiletagids<0) {
                   12099:                                     undef(%importedrespids);
                   12100:                                     undef(%importedpartids);
                   12101:                                 }
1.1373    raeburn  12102:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12103:                                 if (@respids) {
                   12104:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12105:                                 }
                   12106:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12107:                                     $importedresponses = 1;
1.1369    raeburn  12108: # We need to get the original file and the imported file to get the response order correct
                   12109: # Load and inspect original file
1.1372    raeburn  12110:                                     if ($#origfiletagids<0) {
                   12111:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12112:                                         $origfile=&getfile($origfilelocation);
                   12113:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12114:                                     }
1.1369    raeburn  12115:                                 }
                   12116:                             }
                   12117:                         }
1.1370    raeburn  12118: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12119: # hash populated for imported library file
                   12120:                         %metaentry = %currmetaentry;
                   12121:                         undef(%currmetaentry);
1.1374    raeburn  12122:                         if ($importmode eq 'part') {
1.1068    www      12123: # Import as part(s)
1.1069    www      12124:                            $importedparts=1;
                   12125: # We need to get the original file and the imported file to get the part order correct
                   12126: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12127: # Load and inspect original file if we didn't do that already
                   12128:                            if ($#origfiletagids<0) {
                   12129:                                undef(%importedrespids);
                   12130:                                undef(%importedpartids);
                   12131:                                if ($origfile eq '') {
                   12132:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12133:                                    $origfile=&getfile($origfilelocation);
                   12134:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12135:                                }
1.1070    www      12136:                            }
1.1372    raeburn  12137:                            my @impfilepartids;
                   12138: # If <partorder> tag is included in metadata for the imported file
                   12139: # get the parts in the imported file from that.
                   12140:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12141:                                %currmetaentry = %metaentry;
                   12142:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12143:                                                             $depthcount+1);
                   12144:                                %metaentry = %currmetaentry;
                   12145:                                undef(%currmetaentry);
                   12146:                                if ($libpartorder ne '') {
                   12147:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12148:                                }
                   12149:                            } else {
                   12150: # If no <partorder> tag available, load and inspect imported file
                   12151:                                my $impfile=&getfile($location);
                   12152:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12153:                            }
1.1069    www      12154:                            if ($#impfilepartids>=0) {
                   12155: # This problem had parts
1.1070    www      12156:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12157:                            } else {
                   12158: # Importing by turning a single problem into a problem part
                   12159: # It gets the import-tags ID as part-ID
                   12160:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12161:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12162:                            }
1.1068    www      12163:                         } else {
1.1374    raeburn  12164: # Import as problem or as normal import
                   12165:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12166:                             unless ($importmode eq 'problem') {
1.1068    www      12167: # Normal import
1.1374    raeburn  12168:                                 if (defined($token->[2]->{'id'})) {
                   12169:                                     $unikey.='_'.$token->[2]->{'id'};
                   12170:                                 }
                   12171:                             }
                   12172: # Check metadata for imported file to
                   12173: # see if it contained parts
                   12174:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12175:                                 %currmetaentry = %metaentry;
                   12176:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12177:                                                              $depthcount+1);
                   12178:                                 %metaentry = %currmetaentry;
                   12179:                                 undef(%currmetaentry);
                   12180:                                 if ($libpartorder ne '') {
                   12181:                                     $importedparts = 1;
                   12182:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12183:                                 }
                   12184:                             }
1.1067    www      12185:                         }
1.339     albertel 12186: 			if ($depthcount<20) {
1.736     albertel 12187: 			    my $metadata = 
1.1362    raeburn  12188: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12189: 					  $depthcount+1);
                   12190: 			    foreach my $meta (split(',',$metadata)) {
                   12191: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12192: 				$metathesekeys{$meta}=1;
1.339     albertel 12193: 			    }
1.1068    www      12194:                         }
1.1067    www      12195: 		    } else {
                   12196: #
                   12197: # Not importing, some other kind of non-package, non-library start tag
                   12198: # 
                   12199:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12200:                         if (defined($token->[2]->{'id'})) {
                   12201:                             $unikey.='_'.$token->[2]->{'id'};
                   12202:                         }
1.339     albertel 12203: 			if (defined($token->[2]->{'name'})) { 
                   12204: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12205: 			}
                   12206: 			$metathesekeys{$unikey}=1;
1.736     albertel 12207: 			foreach my $param (@{$token->[3]}) {
                   12208: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12209: 				$token->[2]->{$param};
1.339     albertel 12210: 			}
                   12211: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12212: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12213: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12214: 		 # only ws inside the tag, and not in default, so use default
                   12215: 		 # as value
1.599     albertel 12216: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12217: 			} elsif ( $internaltext =~ /\S/ ) {
                   12218: 		  # something interesting inside the tag
                   12219: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12220: 			} else {
1.908     albertel 12221: 		  # no interesting values, don't set a default
1.339     albertel 12222: 			}
1.172     www      12223: # end of not-a-package not-a-library import
1.339     albertel 12224: 		    }
1.172     www      12225: # end of not-a-package start tag
1.339     albertel 12226: 		}
1.172     www      12227: # the next is the end of "start tag"
1.339     albertel 12228: 	    }
                   12229: 	}
1.483     albertel 12230: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12231: 	$extension = lc($extension);
                   12232: 	if ($extension eq 'htm') { $extension='html'; }
                   12233: 
1.737     albertel 12234: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12235: 	    #no specific packages #how's our extension
                   12236: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12237: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12238: 					 \%metathesekeys);
                   12239: 	}
1.883     albertel 12240: 
                   12241: 	if (!exists($metaentry{':packages'})
                   12242: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12243: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12244: 		#no specific packages well let's get default then
                   12245: 		if ($key!~/^default&/) { next; }
1.488     albertel 12246: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12247: 					     \%metathesekeys);
                   12248: 	    }
                   12249: 	}
1.338     www      12250: # are there custom rights to evaluate
1.599     albertel 12251: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12252: 
1.338     www      12253:     #
                   12254:     # Importing a rights file here
1.339     albertel 12255:     #
                   12256: 	    unless ($depthcount) {
1.599     albertel 12257: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12258: 		my $dir=$filename;
                   12259: 		$dir=~s|[^/]*$||;
                   12260: 		$location=&filelocation($dir,$location);
1.736     albertel 12261: 		my $rights_metadata =
1.1362    raeburn  12262: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12263: 			      $depthcount+1);
                   12264: 		foreach my $rights (split(',',$rights_metadata)) {
                   12265: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12266: 		    $metathesekeys{$rights}=1;
1.339     albertel 12267: 		}
                   12268: 	    }
                   12269: 	}
1.737     albertel 12270: 	# uniqifiy package listing
                   12271: 	my %seen;
                   12272: 	my @uniq_packages =
                   12273: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12274: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12275: 
1.1369    raeburn  12276:         if (($importedresponses) || ($importedparts)) {
                   12277:             if ($importedparts) {
1.1070    www      12278: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12279:                 $metaentry{':partorder'}='';
                   12280:                 $metathesekeys{'partorder'}=1;
                   12281:             }
                   12282:             if ($importedresponses) {
                   12283: # We had imported responses and need to rebuil responseorder
                   12284:                 $metaentry{':responseorder'}='';
                   12285:                 $metathesekeys{'responseorder'}=1;
                   12286:             }
                   12287:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12288:                 my $origid = $origfiletagids[$index+1];
                   12289:                 if ($origfiletagids[$index] eq 'part') {
                   12290: # Original part, part of the problem
                   12291:                     if ($importedparts) {
                   12292:                         $metaentry{':partorder'}.=','.$origid;
                   12293:                     }
                   12294:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12295:                     if ($importedparts) {
                   12296: # We have imported parts at this position
1.1373    raeburn  12297:                         if ($importedpartids{$origid} ne '') {
                   12298:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12299:                         }
1.1369    raeburn  12300:                     }
                   12301:                     if ($importedresponses) {
                   12302: # We have imported responses at this position
1.1373    raeburn  12303:                         if ($importedrespids{$origid} ne '') {
                   12304:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12305:                         }
                   12306:                     }
                   12307:                 } else {
                   12308: # Original response item, part of the problem
                   12309:                     if ($importedresponses) {
                   12310:                         $metaentry{':responseorder'}.=','.$origid;
                   12311:                     }
                   12312:                 }
                   12313:             }
                   12314:             if ($importedparts) {
                   12315:                 $metaentry{':partorder'}=~s/^\,//;
                   12316:             }
                   12317:             if ($importedresponses) {
                   12318:                 $metaentry{':responseorder'}=~s/^\,//;
                   12319:             }
1.1070    www      12320:         }
1.737     albertel 12321: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12322: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12323: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12324:         unless ($liburi) {
                   12325: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12326:         }
1.177     www      12327: # this is the end of "was not already recently cached
1.71      www      12328:     }
1.599     albertel 12329:     return $metaentry{':'.$what};
1.261     albertel 12330: }
                   12331: 
1.488     albertel 12332: sub metadata_create_package_def {
1.483     albertel 12333:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12334:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12335:     if ($subp eq 'default') { next; }
                   12336:     
1.599     albertel 12337:     if (defined($metaentry{':packages'})) {
                   12338: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12339:     } else {
1.599     albertel 12340: 	$metaentry{':packages'}=$package;
1.483     albertel 12341:     }
                   12342:     my $value=$packagetab{$key};
                   12343:     my $unikey;
                   12344:     $unikey='parameter_0_'.$name;
1.599     albertel 12345:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12346:     $$metathesekeys{$unikey}=1;
1.599     albertel 12347:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12348: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12349:     }
1.599     albertel 12350:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12351: 	$metaentry{':'.$unikey}=
                   12352: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12353:     }
                   12354: }
                   12355: 
1.261     albertel 12356: sub metadata_generate_part0 {
                   12357:     my ($metadata,$metacache,$uri) = @_;
                   12358:     my %allnames;
1.737     albertel 12359:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12360: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12361: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12362: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12363: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12364: 	    $allnames{$name}=$part;
                   12365: 	  }
                   12366: 	}
                   12367:     }
                   12368:     foreach my $name (keys(%allnames)) {
                   12369:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12370:       my $key=":parameter_0_$name";
1.261     albertel 12371:       $$metacache{"$key.part"}='0';
                   12372:       $$metacache{"$key.name"}=$name;
1.428     albertel 12373:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12374: 					   $allnames{$name}.'_'.$name.
                   12375: 					   '.type'};
1.428     albertel 12376:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12377: 			     '.display'};
1.644     www      12378:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12379:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12380:       $$metacache{"$key.display"}=$olddis;
                   12381:     }
1.71      www      12382: }
                   12383: 
1.764     albertel 12384: # ------------------------------------------------------ Devalidate title cache
                   12385: 
                   12386: sub devalidate_title_cache {
                   12387:     my ($url)=@_;
                   12388:     if (!$env{'request.course.id'}) { return; }
                   12389:     my $symb=&symbread($url);
                   12390:     if (!$symb) { return; }
                   12391:     my $key=$env{'request.course.id'}."\0".$symb;
                   12392:     &devalidate_cache_new('title',$key);
                   12393: }
                   12394: 
1.1014    droeschl 12395: # ------------------------------------------------- Get the title of a course
                   12396: 
                   12397: sub current_course_title {
                   12398:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12399: }
1.301     www      12400: # ------------------------------------------------- Get the title of a resource
                   12401: 
                   12402: sub gettitle {
                   12403:     my $urlsymb=shift;
                   12404:     my $symb=&symbread($urlsymb);
1.534     albertel 12405:     if ($symb) {
1.620     albertel 12406: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12407: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12408: 	if (defined($cached)) { 
                   12409: 	    return $result;
                   12410: 	}
1.534     albertel 12411: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12412: 	my $title='';
1.907     albertel 12413: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12414: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12415: 	} else {
                   12416: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12417: 		    &GDBM_READER(),0640)) {
                   12418: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12419: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12420: 		untie(%bighash);
                   12421: 	    }
1.534     albertel 12422: 	}
                   12423: 	$title=~s/\&colon\;/\:/gs;
                   12424: 	if ($title) {
1.1159    www      12425: # Remember both $symb and $title for dynamic metadata
                   12426:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12427:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12428: # Cache this title and then return it
1.599     albertel 12429: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12430: 	}
                   12431: 	$urlsymb=$url;
                   12432:     }
                   12433:     my $title=&metadata($urlsymb,'title');
                   12434:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12435:     return $title;
1.301     www      12436: }
1.613     albertel 12437: 
1.614     albertel 12438: sub get_slot {
                   12439:     my ($which,$cnum,$cdom)=@_;
                   12440:     if (!$cnum || !$cdom) {
1.790     albertel 12441: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12442: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12443: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12444:     }
1.703     albertel 12445:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12446:     my %slotinfo;
                   12447:     if (exists($remembered{$key})) {
                   12448: 	$slotinfo{$which} = $remembered{$key};
                   12449:     } else {
                   12450: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12451: 	&Apache::lonhomework::showhash(%slotinfo);
                   12452: 	my ($tmp)=keys(%slotinfo);
                   12453: 	if ($tmp=~/^error:/) { return (); }
                   12454: 	$remembered{$key} = $slotinfo{$which};
                   12455:     }
1.616     albertel 12456:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12457: 	return %{$slotinfo{$which}};
                   12458:     }
                   12459:     return $slotinfo{$which};
1.614     albertel 12460: }
1.1150    raeburn  12461: 
                   12462: sub get_reservable_slots {
                   12463:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12464:     my $now = time;
                   12465:     my $reservable_info;
                   12466:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12467:     if (exists($remembered{$key})) {
                   12468:         $reservable_info = $remembered{$key};
                   12469:     } else {
                   12470:         my %resv;
                   12471:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12472:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12473:         $reservable_info = \%resv;
                   12474:         $remembered{$key} = $reservable_info;
                   12475:     }
                   12476:     return $reservable_info;
                   12477: }
                   12478: 
                   12479: sub get_course_slots {
                   12480:     my ($cnum,$cdom) = @_;
                   12481:     my $hashid=$cnum.':'.$cdom;
                   12482:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12483:     if (defined($cached)) {
                   12484:         if (ref($result) eq 'HASH') {
                   12485:             return %{$result};
                   12486:         }
                   12487:     } else {
                   12488:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12489:         my ($tmp) = keys(%slots);
                   12490:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12491:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12492:             return %slots;
                   12493:         }
                   12494:     }
                   12495:     return;
                   12496: }
                   12497: 
                   12498: sub devalidate_slots_cache {
                   12499:     my ($cnum,$cdom)=@_;
                   12500:     my $hashid=$cnum.':'.$cdom;
                   12501:     &devalidate_cache_new('allslots',$hashid);
                   12502: }
                   12503: 
1.1181    raeburn  12504: sub get_coursechange {
                   12505:     my ($cdom,$cnum) = @_;
                   12506:     if ($cdom eq '' || $cnum eq '') {
                   12507:         return unless ($env{'request.course.id'});
                   12508:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12509:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12510:     }
                   12511:     my $hashid=$cdom.'_'.$cnum;
                   12512:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12513:     if ((defined($cached)) && ($change ne '')) {
                   12514:         return $change;
                   12515:     } else {
                   12516:         my %crshash;
                   12517:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12518:         if ($crshash{'internal.contentchange'} eq '') {
                   12519:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12520:             if ($change eq '') {
                   12521:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12522:                 $change = $crshash{'internal.created'};
                   12523:             }
                   12524:         } else {
                   12525:             $change = $crshash{'internal.contentchange'};
                   12526:         }
                   12527:         my $cachetime = 600;
                   12528:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12529:     }
                   12530:     return $change;
                   12531: }
                   12532: 
                   12533: sub devalidate_coursechange_cache {
                   12534:     my ($cnum,$cdom)=@_;
                   12535:     my $hashid=$cnum.':'.$cdom;
                   12536:     &devalidate_cache_new('crschange',$hashid);
                   12537: }
                   12538: 
1.31      www      12539: # ------------------------------------------------- Update symbolic store links
                   12540: 
                   12541: sub symblist {
                   12542:     my ($mapname,%newhash)=@_;
1.438     www      12543:     $mapname=&deversion(&declutter($mapname));
1.31      www      12544:     my %hash;
1.620     albertel 12545:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12546:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12547:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12548: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12549: 		next if ($url eq 'last_known'
                   12550: 			 && $env{'form.no_update_last_known'});
                   12551: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12552: 						    $newhash{$url}->[1],
                   12553: 						    $newhash{$url}->[0]);
1.191     harris41 12554:             }
1.31      www      12555:             if (untie(%hash)) {
                   12556: 		return 'ok';
                   12557:             }
                   12558:         }
                   12559:     }
                   12560:     return 'error';
1.212     www      12561: }
                   12562: 
                   12563: # --------------------------------------------------------------- Verify a symb
                   12564: 
                   12565: sub symbverify {
1.1190    raeburn  12566:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12567:     my $thisfn=$thisurl;
1.439     www      12568:     $thisfn=&declutter($thisfn);
1.215     www      12569: # direct jump to resource in page or to a sequence - will construct own symbs
                   12570:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12571: # check URL part
1.409     www      12572:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12573: 
1.431     www      12574:     unless ($url eq $thisfn) { return 0; }
1.213     www      12575: 
1.216     www      12576:     $symb=&symbclean($symb);
1.510     www      12577:     $thisurl=&deversion($thisurl);
1.439     www      12578:     $thisfn=&deversion($thisfn);
1.213     www      12579: 
                   12580:     my %bighash;
                   12581:     my $okay=0;
1.431     www      12582: 
1.620     albertel 12583:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12584:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12585:         my $noclutter;
1.1032    raeburn  12586:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12587:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12588:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12589:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12590:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12591:                 $noclutter = 1;
                   12592:             }
                   12593:         }
                   12594:         my $ids;
                   12595:         if ($noclutter) {
                   12596:             $ids=$bighash{'ids_'.$thisurl};
                   12597:         } else {
                   12598:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12599:         }
1.1102    raeburn  12600:         unless ($ids) {
                   12601:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12602:             $ids=$bighash{$idkey};
1.216     www      12603:         }
                   12604:         if ($ids) {
                   12605: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12606:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12607:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12608:             }
1.800     albertel 12609: 	    foreach my $id (split(/\,/,$ids)) {
                   12610: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12611:                if (
                   12612:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12613:    eq $symb) {
                   12614:                    if (ref($encstate)) {
                   12615:                        $$encstate = $bighash{'encrypted_'.$id};
                   12616:                    }
1.620     albertel 12617: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12618: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12619:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12620: 		       $okay=1;
1.1202    raeburn  12621:                        last;
1.582     albertel 12622: 		   }
                   12623: 	       }
1.216     www      12624: 	   }
                   12625:         }
1.213     www      12626: 	untie(%bighash);
                   12627:     }
                   12628:     return $okay;
1.31      www      12629: }
                   12630: 
1.210     www      12631: # --------------------------------------------------------------- Clean-up symb
                   12632: 
                   12633: sub symbclean {
                   12634:     my $symb=shift;
1.568     albertel 12635:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12636: # remove version from map
                   12637:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12638: 
1.210     www      12639: # remove version from URL
                   12640:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12641: 
1.507     www      12642: # remove wrapper
                   12643: 
1.510     www      12644:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12645:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12646:     return $symb;
1.409     www      12647: }
                   12648: 
                   12649: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12650: 
                   12651: sub encode_symb {
                   12652:     my ($map,$resid,$url)=@_;
                   12653:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12654: }
1.409     www      12655: 
                   12656: sub decode_symb {
1.568     albertel 12657:     my $symb=shift;
                   12658:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12659:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12660:     return (&fixversion($map),$resid,&fixversion($url));
                   12661: }
                   12662: 
                   12663: sub fixversion {
                   12664:     my $fn=shift;
1.609     banghart 12665:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12666:     my %bighash;
                   12667:     my $uri=&clutter($fn);
1.620     albertel 12668:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12669: # is this cached?
1.599     albertel 12670:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12671:     if (defined($cached)) { return $result; }
                   12672: # unfortunately not cached, or expired
1.620     albertel 12673:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12674: 	    &GDBM_READER(),0640)) {
                   12675:  	if ($bighash{'version_'.$uri}) {
                   12676:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12677:  	    unless (($version eq 'mostrecent') || 
                   12678: 		    ($version==&getversion($uri))) {
1.440     www      12679:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12680:  	    }
                   12681:  	}
                   12682:  	untie %bighash;
1.413     www      12683:     }
1.599     albertel 12684:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12685: }
                   12686: 
                   12687: sub deversion {
                   12688:     my $url=shift;
                   12689:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12690:     return $url;
1.210     www      12691: }
                   12692: 
1.31      www      12693: # ------------------------------------------------------ Return symb list entry
                   12694: 
                   12695: sub symbread {
1.1282    raeburn  12696:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12697:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12698:     if (defined($env{$cache_str})) {
                   12699:         if ($ignorecachednull) {
                   12700:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12701:         } else {
                   12702:             return $env{$cache_str};
                   12703:         }
                   12704:     }
1.242     www      12705: # no filename provided? try from environment
1.1265    raeburn  12706:     unless ($thisfn) {
1.620     albertel 12707:         if ($env{'request.symb'}) {
                   12708: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12709: 	}
1.620     albertel 12710: 	$thisfn=$env{'request.filename'};
1.44      www      12711:     }
1.569     albertel 12712:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12713: # is that filename actually a symb? Verify, clean, and return
                   12714:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12715: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12716: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12717: 	}
1.242     www      12718:     }
1.44      www      12719:     $thisfn=declutter($thisfn);
1.31      www      12720:     my %hash;
1.37      www      12721:     my %bighash;
                   12722:     my $syval='';
1.620     albertel 12723:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12724:         my $targetfn = $thisfn;
1.609     banghart 12725:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12726:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12727:         }
1.687     albertel 12728: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12729: 	    $targetfn=$1;
                   12730: 	}
1.620     albertel 12731:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12732:                       &GDBM_READER(),0640)) {
1.481     raeburn  12733: 	    $syval=$hash{$targetfn};
1.37      www      12734:             untie(%hash);
                   12735:         }
                   12736: # ---------------------------------------------------------- There was an entry
                   12737:         if ($syval) {
1.601     albertel 12738: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12739: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12740: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12741: 		    #return $env{$cache_str}='';
1.601     albertel 12742: 		#}    
                   12743: 		#$syval.=$1;
                   12744: 	    #}
1.37      www      12745:         } else {
                   12746: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12747:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12748:                             &GDBM_READER(),0640)) {
1.37      www      12749: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12750:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12751:               unless ($ids) { 
                   12752:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12753:               }
                   12754:               unless ($ids) {
                   12755: # alias?
                   12756: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12757:               }
1.37      www      12758:               if ($ids) {
                   12759: # ------------------------------------------------------------------- Has ID(s)
                   12760:                  my @possibilities=split(/\,/,$ids);
1.39      www      12761:                  if ($#possibilities==0) {
                   12762: # ----------------------------------------------- There is only one possibility
1.37      www      12763: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12764: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12765: 						    $resid,$thisfn);
1.1282    raeburn  12766:                      if (ref($possibles) eq 'HASH') {
                   12767:                          $possibles->{$syval} = 1;    
                   12768:                      }
                   12769:                      if ($checkforblock) {
                   12770:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12771:                          if (@blockers) {
                   12772:                              $syval = '';
                   12773:                              return;
                   12774:                          }
                   12775:                      }
                   12776:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12777: # ------------------------------------------ There is more than one possibility
                   12778:                      my $realpossible=0;
1.800     albertel 12779:                      foreach my $id (@possibilities) {
                   12780: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12781:                          my $canaccess;
                   12782:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12783:                              $canaccess = 1;
                   12784:                          } else { 
                   12785:                              $canaccess = &allowed('bre',$file);
                   12786:                          }
                   12787:                          if ($canaccess) {
                   12788:          		     my ($mapid,$resid)=split(/\./,$id);
                   12789:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12790:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12791: 						             $resid,$thisfn);
                   12792:                                  if (ref($possibles) eq 'HASH') {
                   12793:                                      $possibles->{$syval} = 1;
                   12794:                                  }
                   12795:                                  if ($checkforblock) {
                   12796:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12797:                                      unless (@blockers > 0) {
                   12798:                                          $syval = $poss_syval;
                   12799:                                          $realpossible++;
                   12800:                                      }
                   12801:                                  } else {
                   12802:                                      $syval = $poss_syval;
                   12803:                                      $realpossible++;
                   12804:                                  }
                   12805:                              }
1.39      www      12806: 			 }
1.191     harris41 12807:                      }
1.39      www      12808: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12809:                  } else {
                   12810:                      $syval='';
1.37      www      12811:                  }
                   12812: 	      }
1.1282    raeburn  12813:               untie(%bighash);
1.481     raeburn  12814:            }
1.31      www      12815:         }
1.62      www      12816:         if ($syval) {
1.620     albertel 12817: 	    return $env{$cache_str}=$syval;
1.62      www      12818:         }
1.31      www      12819:     }
1.949     raeburn  12820:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12821:     return $env{$cache_str}='';
1.31      www      12822: }
                   12823: 
                   12824: # ---------------------------------------------------------- Return random seed
                   12825: 
1.32      www      12826: sub numval {
                   12827:     my $txt=shift;
                   12828:     $txt=~tr/A-J/0-9/;
                   12829:     $txt=~tr/a-j/0-9/;
                   12830:     $txt=~tr/K-T/0-9/;
                   12831:     $txt=~tr/k-t/0-9/;
                   12832:     $txt=~tr/U-Z/0-5/;
                   12833:     $txt=~tr/u-z/0-5/;
                   12834:     $txt=~s/\D//g;
1.564     albertel 12835:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12836:     return int($txt);
1.368     albertel 12837: }
                   12838: 
1.484     albertel 12839: sub numval2 {
                   12840:     my $txt=shift;
                   12841:     $txt=~tr/A-J/0-9/;
                   12842:     $txt=~tr/a-j/0-9/;
                   12843:     $txt=~tr/K-T/0-9/;
                   12844:     $txt=~tr/k-t/0-9/;
                   12845:     $txt=~tr/U-Z/0-5/;
                   12846:     $txt=~tr/u-z/0-5/;
                   12847:     $txt=~s/\D//g;
                   12848:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12849:     my $total;
                   12850:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12851:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12852:     return int($total);
                   12853: }
                   12854: 
1.575     albertel 12855: sub numval3 {
                   12856:     use integer;
                   12857:     my $txt=shift;
                   12858:     $txt=~tr/A-J/0-9/;
                   12859:     $txt=~tr/a-j/0-9/;
                   12860:     $txt=~tr/K-T/0-9/;
                   12861:     $txt=~tr/k-t/0-9/;
                   12862:     $txt=~tr/U-Z/0-5/;
                   12863:     $txt=~tr/u-z/0-5/;
                   12864:     $txt=~s/\D//g;
                   12865:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12866:     my $total;
                   12867:     foreach my $val (@txts) { $total+=$val; }
                   12868:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12869:     return $total;
                   12870: }
                   12871: 
1.675     albertel 12872: sub digest {
                   12873:     my ($data)=@_;
                   12874:     my $digest=&Digest::MD5::md5($data);
                   12875:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12876:     my ($e,$f);
                   12877:     {
                   12878:         use integer;
                   12879:         $e=($a+$b);
                   12880:         $f=($c+$d);
                   12881:         if ($_64bit) {
                   12882:             $e=(($e<<32)>>32);
                   12883:             $f=(($f<<32)>>32);
                   12884:         }
                   12885:     }
                   12886:     if (wantarray) {
                   12887: 	return ($e,$f);
                   12888:     } else {
                   12889: 	my $g;
                   12890: 	{
                   12891: 	    use integer;
                   12892: 	    $g=($e+$f);
                   12893: 	    if ($_64bit) {
                   12894: 		$g=(($g<<32)>>32);
                   12895: 	    }
                   12896: 	}
                   12897: 	return $g;
                   12898:     }
                   12899: }
                   12900: 
1.368     albertel 12901: sub latest_rnd_algorithm_id {
1.675     albertel 12902:     return '64bit5';
1.366     albertel 12903: }
1.32      www      12904: 
1.503     albertel 12905: sub get_rand_alg {
                   12906:     my ($courseid)=@_;
1.790     albertel 12907:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12908:     if ($courseid) {
1.620     albertel 12909: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12910:     }
                   12911:     return &latest_rnd_algorithm_id();
                   12912: }
                   12913: 
1.562     albertel 12914: sub validCODE {
                   12915:     my ($CODE)=@_;
                   12916:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12917:     return 0;
                   12918: }
                   12919: 
1.491     albertel 12920: sub getCODE {
1.620     albertel 12921:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12922:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12923: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12924: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12925: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12926:     }
                   12927:     return undef;
                   12928: }
1.1133    foxr     12929: #
                   12930: #  Determines the random seed for a specific context:
                   12931: #
                   12932: # parameters:
                   12933: #   symb      - in course context the symb for the seed.
                   12934: #   course_id - The course id of the form domain_coursenum.
                   12935: #   domain    - Domain for the user.
                   12936: #   course    - Course for the user.
                   12937: #   cenv      - environment of the course.
                   12938: #
                   12939: # NOTE:
                   12940: #   All parameters are picked out of the environment if missing
                   12941: #   or not defined.
                   12942: #   If a symb cannot be determined the current time is used instead.
                   12943: #
                   12944: #  For a given well defined symb, courside, domain, username,
                   12945: #  and course environment, the seed is reproducible.
                   12946: #
1.31      www      12947: sub rndseed {
1.1133    foxr     12948:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12949:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12950:     if (!defined($symb)) {
1.366     albertel 12951: 	unless ($symb=$wsymb) { return time; }
                   12952:     }
1.1146    foxr     12953:     if (!defined $courseid) { 
                   12954: 	$courseid=$wcourseid; 
                   12955:     }
                   12956:     if (!defined $domain) { $domain=$wdomain; }
                   12957:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12958: 
                   12959:     my $which;
                   12960:     if (defined($cenv->{'rndseed'})) {
                   12961: 	$which = $cenv->{'rndseed'};
                   12962:     } else {
                   12963: 	$which =&get_rand_alg($courseid);
                   12964:     }
1.491     albertel 12965:     if (defined(&getCODE())) {
1.1133    foxr     12966: 
1.675     albertel 12967: 	if ($which eq '64bit5') {
                   12968: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12969: 	} elsif ($which eq '64bit4') {
1.575     albertel 12970: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12971: 	} else {
                   12972: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12973: 	}
1.675     albertel 12974:     } elsif ($which eq '64bit5') {
                   12975: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12976:     } elsif ($which eq '64bit4') {
                   12977: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12978:     } elsif ($which eq '64bit3') {
                   12979: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12980:     } elsif ($which eq '64bit2') {
                   12981: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12982:     } elsif ($which eq '64bit') {
                   12983: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12984:     }
                   12985:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12986: }
                   12987: 
                   12988: sub rndseed_32bit {
                   12989:     my ($symb,$courseid,$domain,$username)=@_;
                   12990:     {
                   12991: 	use integer;
                   12992: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12993: 	my $symbseed=numval($symb) << 22;
                   12994: 	my $namechck=unpack("%32C*",$username) << 17;
                   12995: 	my $nameseed=numval($username) << 12;
                   12996: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12997: 	my $courseseed=unpack("%32C*",$courseid);
                   12998: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12999: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13000: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13001: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13002: 	return $num;
                   13003:     }
                   13004: }
                   13005: 
                   13006: sub rndseed_64bit {
                   13007:     my ($symb,$courseid,$domain,$username)=@_;
                   13008:     {
                   13009: 	use integer;
                   13010: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13011: 	my $symbseed=numval($symb) << 10;
                   13012: 	my $namechck=unpack("%32S*",$username);
                   13013: 	
                   13014: 	my $nameseed=numval($username) << 21;
                   13015: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13016: 	my $courseseed=unpack("%32S*",$courseid);
                   13017: 	
                   13018: 	my $num1=$symbchck+$symbseed+$namechck;
                   13019: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13020: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13021: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13022: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13023: 	return "$num1,$num2";
1.155     albertel 13024:     }
1.366     albertel 13025: }
                   13026: 
1.443     albertel 13027: sub rndseed_64bit2 {
                   13028:     my ($symb,$courseid,$domain,$username)=@_;
                   13029:     {
                   13030: 	use integer;
                   13031: 	# strings need to be an even # of cahracters long, it it is odd the
                   13032:         # last characters gets thrown away
                   13033: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13034: 	my $symbseed=numval($symb) << 10;
                   13035: 	my $namechck=unpack("%32S*",$username.' ');
                   13036: 	
                   13037: 	my $nameseed=numval($username) << 21;
1.501     albertel 13038: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13039: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13040: 	
                   13041: 	my $num1=$symbchck+$symbseed+$namechck;
                   13042: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13043: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13044: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13045: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13046: 	return "$num1,$num2";
                   13047:     }
                   13048: }
                   13049: 
                   13050: sub rndseed_64bit3 {
                   13051:     my ($symb,$courseid,$domain,$username)=@_;
                   13052:     {
                   13053: 	use integer;
                   13054: 	# strings need to be an even # of cahracters long, it it is odd the
                   13055:         # last characters gets thrown away
                   13056: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13057: 	my $symbseed=numval2($symb) << 10;
                   13058: 	my $namechck=unpack("%32S*",$username.' ');
                   13059: 	
                   13060: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13061: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13062: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13063: 	
                   13064: 	my $num1=$symbchck+$symbseed+$namechck;
                   13065: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13066: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13067: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13068: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13069: 	
1.503     albertel 13070: 	return "$num1:$num2";
1.443     albertel 13071:     }
                   13072: }
                   13073: 
1.575     albertel 13074: sub rndseed_64bit4 {
                   13075:     my ($symb,$courseid,$domain,$username)=@_;
                   13076:     {
                   13077: 	use integer;
                   13078: 	# strings need to be an even # of cahracters long, it it is odd the
                   13079:         # last characters gets thrown away
                   13080: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13081: 	my $symbseed=numval3($symb) << 10;
                   13082: 	my $namechck=unpack("%32S*",$username.' ');
                   13083: 	
                   13084: 	my $nameseed=numval3($username) << 21;
                   13085: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13086: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13087: 	
                   13088: 	my $num1=$symbchck+$symbseed+$namechck;
                   13089: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13090: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13091: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13092: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13093: 	
1.575     albertel 13094: 	return "$num1:$num2";
                   13095:     }
                   13096: }
                   13097: 
1.675     albertel 13098: sub rndseed_64bit5 {
                   13099:     my ($symb,$courseid,$domain,$username)=@_;
                   13100:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13101:     return "$num1:$num2";
                   13102: }
                   13103: 
1.366     albertel 13104: sub rndseed_CODE_64bit {
                   13105:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13106:     {
1.366     albertel 13107: 	use integer;
1.443     albertel 13108: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13109: 	my $symbseed=numval2($symb);
1.491     albertel 13110: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13111: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13112: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13113: 	my $num1=$symbseed+$CODEchck;
                   13114: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13115: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13116: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13117: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13118: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13119: 	return "$num1:$num2";
1.366     albertel 13120:     }
                   13121: }
                   13122: 
1.575     albertel 13123: sub rndseed_CODE_64bit4 {
                   13124:     my ($symb,$courseid,$domain,$username)=@_;
                   13125:     {
                   13126: 	use integer;
                   13127: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13128: 	my $symbseed=numval3($symb);
                   13129: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13130: 	my $CODEseed=numval3(&getCODE());
                   13131: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13132: 	my $num1=$symbseed+$CODEchck;
                   13133: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13134: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13135: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13136: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13137: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13138: 	return "$num1:$num2";
                   13139:     }
                   13140: }
                   13141: 
1.675     albertel 13142: sub rndseed_CODE_64bit5 {
                   13143:     my ($symb,$courseid,$domain,$username)=@_;
                   13144:     my $code = &getCODE();
                   13145:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13146:     return "$num1:$num2";
                   13147: }
                   13148: 
1.366     albertel 13149: sub setup_random_from_rndseed {
                   13150:     my ($rndseed)=@_;
1.503     albertel 13151:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13152:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13153:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13154:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13155:         } else {
                   13156:             &Math::Random::random_set_seed($num1,$num2);
                   13157:         }
1.366     albertel 13158:     } else {
                   13159: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13160:     }
1.36      albertel 13161: }
                   13162: 
1.474     albertel 13163: sub latest_receipt_algorithm_id {
1.835     albertel 13164:     return 'receipt3';
1.474     albertel 13165: }
                   13166: 
1.480     www      13167: sub recunique {
                   13168:     my $fucourseid=shift;
                   13169:     my $unique;
1.835     albertel 13170:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13171: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13172: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13173:     } else {
                   13174: 	$unique=$perlvar{'lonReceipt'};
                   13175:     }
                   13176:     return unpack("%32C*",$unique);
                   13177: }
                   13178: 
                   13179: sub recprefix {
                   13180:     my $fucourseid=shift;
                   13181:     my $prefix;
1.835     albertel 13182:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13183: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13184: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13185:     } else {
                   13186: 	$prefix=$perlvar{'lonHostID'};
                   13187:     }
                   13188:     return unpack("%32C*",$prefix);
                   13189: }
                   13190: 
1.76      www      13191: sub ireceipt {
1.474     albertel 13192:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13193: 
                   13194:     my $return =&recprefix($fucourseid).'-';
                   13195: 
                   13196:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13197: 	$env{'request.state'} eq 'construct') {
                   13198: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13199: 	return $return;
                   13200:     }
                   13201: 
1.76      www      13202:     my $cuname=unpack("%32C*",$funame);
                   13203:     my $cudom=unpack("%32C*",$fudom);
                   13204:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13205:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13206:     my $cunique=&recunique($fucourseid);
1.474     albertel 13207:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13208:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13209: 
1.790     albertel 13210: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13211: 			       
                   13212: 	$return.= ($cunique%$cuname+
                   13213: 		   $cunique%$cudom+
                   13214: 		   $cusymb%$cuname+
                   13215: 		   $cusymb%$cudom+
                   13216: 		   $cucourseid%$cuname+
                   13217: 		   $cucourseid%$cudom+
                   13218: 		   $cpart%$cuname+
                   13219: 		   $cpart%$cudom);
                   13220:     } else {
                   13221: 	$return.= ($cunique%$cuname+
                   13222: 		   $cunique%$cudom+
                   13223: 		   $cusymb%$cuname+
                   13224: 		   $cusymb%$cudom+
                   13225: 		   $cucourseid%$cuname+
                   13226: 		   $cucourseid%$cudom);
                   13227:     }
                   13228:     return $return;
1.76      www      13229: }
                   13230: 
                   13231: sub receipt {
1.474     albertel 13232:     my ($part)=@_;
1.790     albertel 13233:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13234:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13235: }
1.260     ng       13236: 
1.790     albertel 13237: sub whichuser {
                   13238:     my ($passedsymb)=@_;
                   13239:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13240:     if (defined($env{'form.grade_symb'})) {
                   13241: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13242: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13243: 	if (!$allowed &&
                   13244: 	    exists($env{'request.course.sec'}) &&
                   13245: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13246: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13247: 			      '/'.$env{'request.course.sec'});
                   13248: 	}
                   13249: 	if ($allowed) {
                   13250: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13251: 	    $courseid=$tmp_courseid;
                   13252: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13253: 	    ($name)=&get_env_multiple('form.grade_username');
                   13254: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13255: 	}
                   13256:     }
                   13257:     if (!$passedsymb) {
                   13258: 	$symb=&symbread();
                   13259:     } else {
                   13260: 	$symb=$passedsymb;
                   13261:     }
                   13262:     $courseid=$env{'request.course.id'};
                   13263:     $domain=$env{'user.domain'};
                   13264:     $name=$env{'user.name'};
                   13265:     if ($name eq 'public' && $domain eq 'public') {
                   13266: 	if (!defined($env{'form.username'})) {
                   13267: 	    $env{'form.username'}.=time.rand(10000000);
                   13268: 	}
                   13269: 	$name.=$env{'form.username'};
                   13270:     }
                   13271:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13272: 
                   13273: }
                   13274: 
1.36      albertel 13275: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13276: # returns either the contents of the file or 
                   13277: # -1 if the file doesn't exist
1.481     raeburn  13278: #
                   13279: # if the target is a file that was uploaded via DOCS, 
                   13280: # a check will be made to see if a current copy exists on the local server,
                   13281: # if it does this will be served, otherwise a copy will be retrieved from
                   13282: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13283: # the local server.   
1.472     albertel 13284: 
1.36      albertel 13285: sub getfile {
1.538     albertel 13286:     my ($file) = @_;
1.609     banghart 13287:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13288:     &repcopy($file);
                   13289:     return &readfile($file);
                   13290: }
                   13291: 
                   13292: sub repcopy_userfile {
                   13293:     my ($file)=@_;
1.1142    raeburn  13294:     my $londocroot = $perlvar{'lonDocRoot'};
                   13295:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13296:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13297:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13298: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13299:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13300:     if (-e "$file") {
1.828     www      13301: # we already have a local copy, check it out
1.538     albertel 13302: 	my @fileinfo = stat($file);
1.828     www      13303: 	my $rtncode;
                   13304: 	my $info;
1.538     albertel 13305: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13306: 	if ($lwpresp ne 'ok') {
1.828     www      13307: # there is no such file anymore, even though we had a local copy
1.482     albertel 13308: 	    if ($rtncode eq '404') {
1.538     albertel 13309: 		unlink($file);
1.482     albertel 13310: 	    }
                   13311: 	    return -1;
                   13312: 	}
                   13313: 	if ($info < $fileinfo[9]) {
1.828     www      13314: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13315: 	    return 'ok';
1.828     www      13316: 	} else {
                   13317: # the file is outdated, get rid of it
                   13318: 	    unlink($file);
1.482     albertel 13319: 	}
1.828     www      13320:     }
                   13321: # one way or the other, at this point, we don't have the file
                   13322: # construct the correct path for the file
                   13323:     my @parts = ($cdom,$cnum); 
                   13324:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13325: 	push @parts, split(/\//,$1);
                   13326:     }
                   13327:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13328:     foreach my $part (@parts) {
                   13329: 	$path .= '/'.$part;
                   13330: 	if (!-e $path) {
                   13331: 	    mkdir($path,0770);
1.482     albertel 13332: 	}
                   13333:     }
1.828     www      13334: # now the path exists for sure
                   13335: # get a user agent
                   13336:     my $transferfile=$file.'.in.transfer';
                   13337: # FIXME: this should flock
                   13338:     if (-e $transferfile) { return 'ok'; }
                   13339:     my $request;
                   13340:     $uri=~s/^\///;
1.980     raeburn  13341:     my $homeserver = &homeserver($cnum,$cdom);
                   13342:     my $protocol = $protocol{$homeserver};
                   13343:     $protocol = 'http' if ($protocol ne 'https');
                   13344:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13345:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13346: # did it work?
                   13347:     if ($response->is_error()) {
                   13348: 	unlink($transferfile);
                   13349: 	&logthis("Userfile repcopy failed for $uri");
                   13350: 	return -1;
                   13351:     }
                   13352: # worked, rename the transfer file
                   13353:     rename($transferfile,$file);
1.607     raeburn  13354:     return 'ok';
1.481     raeburn  13355: }
                   13356: 
1.517     albertel 13357: sub tokenwrapper {
                   13358:     my $uri=shift;
1.980     raeburn  13359:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13360:     $uri=~s|^/||;
1.620     albertel 13361:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13362:     my $token=$1;
1.552     albertel 13363:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13364:     if ($udom && $uname && $file) {
                   13365: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13366:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13367:         my $homeserver = &homeserver($uname,$udom);
                   13368:         my $protocol = $protocol{$homeserver};
                   13369:         $protocol = 'http' if ($protocol ne 'https');
                   13370:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13371:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13372:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13373:     } else {
                   13374:         return '/adm/notfound.html';
                   13375:     }
                   13376: }
                   13377: 
1.828     www      13378: # call with reqtype HEAD: get last modification time
                   13379: # call with reqtype GET: get the file contents
                   13380: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13381: #
1.481     raeburn  13382: sub getuploaded {
                   13383:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13384:     $uri=~s/^\///;
1.980     raeburn  13385:     my $homeserver = &homeserver($cnum,$cdom);
                   13386:     my $protocol = $protocol{$homeserver};
                   13387:     $protocol = 'http' if ($protocol ne 'https');
                   13388:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13389:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13390:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13391:     $$rtncode = $response->code;
1.482     albertel 13392:     if (! $response->is_success()) {
                   13393: 	return 'failed';
                   13394:     }      
                   13395:     if ($reqtype eq 'HEAD') {
1.486     www      13396: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13397:     } elsif ($reqtype eq 'GET') {
                   13398: 	$$info = $response->content;
1.472     albertel 13399:     }
1.482     albertel 13400:     return 'ok';
1.36      albertel 13401: }
                   13402: 
1.481     raeburn  13403: sub readfile {
                   13404:     my $file = shift;
                   13405:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13406:     my $fh;
1.1359    raeburn  13407:     open($fh,"<",$file);
1.481     raeburn  13408:     my $a='';
1.800     albertel 13409:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13410:     return $a;
                   13411: }
                   13412: 
1.36      albertel 13413: sub filelocation {
1.590     banghart 13414:     my ($dir,$file) = @_;
                   13415:     my $location;
                   13416:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13417: 
                   13418:     if ($file =~ m-^/adm/-) {
                   13419: 	$file=~s-^/adm/wrapper/-/-;
                   13420: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13421:     }
1.882     albertel 13422: 
1.1139    www      13423:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13424:         $location = $file;
1.609     banghart 13425:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13426:         my ($udom,$uname,$filename)=
1.811     albertel 13427:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13428:         my $home=&homeserver($uname,$udom);
                   13429:         my $is_me=0;
                   13430:         my @ids=&current_machine_ids();
                   13431:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13432:         if ($is_me) {
1.1117    foxr     13433:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13434:         } else {
                   13435:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13436:   	      $udom.'/'.$uname.'/'.$filename;
                   13437:         }
1.882     albertel 13438:     } elsif ($file =~ m-^/adm/-) {
                   13439: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13440:     } else {
                   13441:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13442:         $file=~s:^/(res|priv)/:/:;
                   13443:         my $space=$1;
1.590     banghart 13444:         if ( !( $file =~ m:^/:) ) {
                   13445:             $location = $dir. '/'.$file;
                   13446:         } else {
1.1142    raeburn  13447:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13448:         }
1.59      albertel 13449:     }
1.590     banghart 13450:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13451:     while ($location=~m{/\.\./}) {
                   13452: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13453: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13454: 	} else {
                   13455: 	    $location=~ s{/\.\./}{/}g;
                   13456: 	}
                   13457:     } #remove dir/..
1.590     banghart 13458:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13459:     return $location;
1.46      www      13460: }
1.36      albertel 13461: 
1.46      www      13462: sub hreflocation {
                   13463:     my ($dir,$file)=@_;
1.980     raeburn  13464:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13465: 	$file=filelocation($dir,$file);
1.700     albertel 13466:     } elsif ($file=~m-^/adm/-) {
                   13467: 	$file=~s-^/adm/wrapper/-/-;
                   13468: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13469:     }
                   13470:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13471: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13472:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13473: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13474: 	        {/uploaded/$1/$2/}x;
1.46      www      13475:     }
1.913     albertel 13476:     if ($file=~ m{^/userfiles/}) {
                   13477: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13478:     }
1.462     albertel 13479:     return $file;
1.465     albertel 13480: }
                   13481: 
1.1139    www      13482: 
                   13483: 
                   13484: 
                   13485: 
1.465     albertel 13486: sub current_machine_domains {
1.853     albertel 13487:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13488: }
                   13489: 
                   13490: sub machine_domains {
                   13491:     my ($hostname) = @_;
1.465     albertel 13492:     my @domains;
1.838     albertel 13493:     my %hostname = &all_hostnames();
1.465     albertel 13494:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13495: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13496: 	if ($hostname eq $name) {
1.844     albertel 13497: 	    push(@domains,&host_domain($id));
1.465     albertel 13498: 	}
                   13499:     }
                   13500:     return @domains;
                   13501: }
                   13502: 
                   13503: sub current_machine_ids {
1.853     albertel 13504:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13505: }
                   13506: 
                   13507: sub machine_ids {
                   13508:     my ($hostname) = @_;
                   13509:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13510:     my @ids;
1.888     albertel 13511:     my %name_to_host = &all_names();
1.889     albertel 13512:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13513: 	return @{ $name_to_host{$hostname} };
                   13514:     }
                   13515:     return;
1.31      www      13516: }
                   13517: 
1.824     raeburn  13518: sub additional_machine_domains {
                   13519:     my @domains;
1.1359    raeburn  13520:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13521:     while( my $line = <$fh>) {
                   13522:         $line =~ s/\s//g;
                   13523:         push(@domains,$line);
                   13524:     }
                   13525:     return @domains;
                   13526: }
                   13527: 
                   13528: sub default_login_domain {
                   13529:     my $domain = $perlvar{'lonDefDomain'};
                   13530:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13531:     foreach my $posdom (&current_machine_domains(),
                   13532:                         &additional_machine_domains()) {
                   13533:         if (lc($posdom) eq lc($testdomain)) {
                   13534:             $domain=$posdom;
                   13535:             last;
                   13536:         }
                   13537:     }
                   13538:     return $domain;
                   13539: }
                   13540: 
1.31      www      13541: # ------------------------------------------------------------- Declutters URLs
                   13542: 
                   13543: sub declutter {
                   13544:     my $thisfn=shift;
1.569     albertel 13545:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13546:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13547:         $thisfn=~s{^/home/httpd/html}{};
                   13548:     }
1.31      www      13549:     $thisfn=~s/^\///;
1.697     albertel 13550:     $thisfn=~s|^adm/wrapper/||;
                   13551:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13552:     $thisfn=~s/^res\///;
1.1172    bisitz   13553:     $thisfn=~s/^priv\///;
1.1032    raeburn  13554:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13555:         $thisfn=~s/\?.+$//;
                   13556:     }
1.268     www      13557:     return $thisfn;
                   13558: }
                   13559: 
                   13560: # ------------------------------------------------------------- Clutter up URLs
                   13561: 
                   13562: sub clutter {
                   13563:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13564:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13565: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13566:        $thisfn='/res'.$thisfn; 
                   13567:     }
1.1031    raeburn  13568:     if ($thisfn !~m|^/adm|) {
                   13569: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13570: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13571: 	} else {
                   13572: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13573: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13574: 	    if ($embstyle eq 'ssi'
                   13575: 		|| ($embstyle eq 'hdn')
                   13576: 		|| ($embstyle eq 'rat')
                   13577: 		|| ($embstyle eq 'prv')
                   13578: 		|| ($embstyle eq 'ign')) {
                   13579: 		#do nothing with these
                   13580: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13581: 		|| ($embstyle eq 'emb')
                   13582: 		|| ($embstyle eq 'wrp')) {
                   13583: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13584: 	    } elsif ($embstyle eq 'unk'
                   13585: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13586: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13587: 	    } else {
1.718     www      13588: #		&logthis("Got a blank emb style");
1.695     albertel 13589: 	    }
1.694     albertel 13590: 	}
1.1343    raeburn  13591:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13592:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13593:     }
1.31      www      13594:     return $thisfn;
1.12      www      13595: }
                   13596: 
1.787     albertel 13597: sub clutter_with_no_wrapper {
                   13598:     my $uri = &clutter(shift);
                   13599:     if ($uri =~ m-^/adm/-) {
                   13600: 	$uri =~ s-^/adm/wrapper/-/-;
                   13601: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13602:     }
                   13603:     return $uri;
                   13604: }
                   13605: 
1.557     albertel 13606: sub freeze_escape {
                   13607:     my ($value)=@_;
                   13608:     if (ref($value)) {
                   13609: 	$value=&nfreeze($value);
                   13610: 	return '__FROZEN__'.&escape($value);
                   13611:     }
                   13612:     return &escape($value);
                   13613: }
                   13614: 
1.11      www      13615: 
1.557     albertel 13616: sub thaw_unescape {
                   13617:     my ($value)=@_;
                   13618:     if ($value =~ /^__FROZEN__/) {
                   13619: 	substr($value,0,10,undef);
                   13620: 	$value=&unescape($value);
                   13621: 	return &thaw($value);
                   13622:     }
                   13623:     return &unescape($value);
                   13624: }
                   13625: 
1.436     albertel 13626: sub correct_line_ends {
                   13627:     my ($result)=@_;
                   13628:     $$result =~s/\r\n/\n/mg;
                   13629:     $$result =~s/\r/\n/mg;
1.415     albertel 13630: }
1.1       albertel 13631: # ================================================================ Main Program
                   13632: 
1.184     www      13633: sub goodbye {
1.204     albertel 13634:    &logthis("Starting Shut down");
1.443     albertel 13635: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13636:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13637: #converted
1.599     albertel 13638: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13639:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13640: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13641: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13642: #1.1 only
1.870     albertel 13643: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13644: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13645: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13646: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13647:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13648:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13649:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13650:    &flushcourselogs();
                   13651:    &logthis("Shutting down");
                   13652: }
                   13653: 
1.852     albertel 13654: sub get_dns {
1.1210    raeburn  13655:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13656:     if (!$ignore_cache) {
                   13657: 	my ($content,$cached)=
                   13658: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13659: 	if ($cached) {
1.1210    raeburn  13660: 	    &$func($content,$hashref);
1.869     albertel 13661: 	    return;
                   13662: 	}
                   13663:     }
                   13664: 
                   13665:     my %alldns;
1.1379    raeburn  13666:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13667:         foreach my $dns (<$config>) {
                   13668: 	    next if ($dns !~ /^\^(\S*)/x);
                   13669:             my $line = $1;
                   13670:             my ($host,$protocol) = split(/:/,$line);
                   13671:             if ($protocol ne 'https') {
                   13672:                 $protocol = 'http';
                   13673:             }
                   13674: 	    $alldns{$host} = $protocol;
1.979     raeburn  13675:         }
1.1379    raeburn  13676:         close($config);
1.869     albertel 13677:     }
                   13678:     while (%alldns) {
1.1263    raeburn  13679: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13680: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13681:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13682:         delete($alldns{$dns});
1.852     albertel 13683: 	next if ($response->is_error());
1.1379    raeburn  13684:         if ($url eq '/adm/dns/loncapaCRL') {
                   13685:             return &$func($response);
                   13686:         } else {
                   13687: 	    my @content = split("\n",$response->content);
                   13688: 	    unless ($nocache) {
                   13689: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   13690: 	    }
                   13691: 	    &$func(\@content,$hashref);
                   13692:             return;
                   13693:         }
                   13694:     }
                   13695:     my $which = (split('/',$url,4))[3];
                   13696:     if ($which eq 'loncapaCRL') {
                   13697:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   13698:         if (-e $diskfile) {
                   13699:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   13700:         } else {
                   13701:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   13702:         }
                   13703:     } else {
                   13704:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13705:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13706:             my @content = <$config>;
                   13707:             close($config);
                   13708:             &$func(\@content,$hashref);
                   13709:         }
1.852     albertel 13710:     }
1.1210    raeburn  13711:     return;
                   13712: }
                   13713: 
                   13714: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13715: sub parse_dns_checksums_tab {
1.1210    raeburn  13716:     my ($lines,$hashref) = @_;
1.1264    raeburn  13717:     my $lonhost = $perlvar{'lonHostID'};
                   13718:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13719:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13720:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13721:     my $webconfdir = '/etc/httpd/conf';
                   13722:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13723:         $webconfdir = '/etc/apache2';
                   13724:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13725:         if ($1 >= 10) {
                   13726:             $webconfdir = '/etc/apache2';
                   13727:         }
                   13728:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13729:         if ($1 >= 10.0) {
                   13730:             $webconfdir = '/etc/apache2';
                   13731:         }
                   13732:     }
1.1210    raeburn  13733:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13734:     my (%chksum,%revnum);
                   13735:     if (ref($lines) eq 'ARRAY') {
                   13736:         chomp(@{$lines});
1.1238    raeburn  13737:         my $version = shift(@{$lines});
                   13738:         if ($version eq $release) {  
1.1210    raeburn  13739:             foreach my $line (@{$lines}) {
1.1238    raeburn  13740:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13741:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13742:                     if ($webconfdir eq '/etc/apache2') {
                   13743:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13744:                     }
                   13745:                 }
1.1238    raeburn  13746:                 $chksum{$file} = $shasum;
                   13747:                 $revnum{$file} = $version;
1.1210    raeburn  13748:             }
                   13749:             if (ref($hashref) eq 'HASH') {
                   13750:                 %{$hashref} = (
                   13751:                                 sums     => \%chksum,
                   13752:                                 versions => \%revnum,
                   13753:                               );
                   13754:             }
                   13755:         }
                   13756:     }
1.869     albertel 13757:     return;
1.852     albertel 13758: }
1.1210    raeburn  13759: 
                   13760: sub fetch_dns_checksums {
1.1238    raeburn  13761:     my %checksums;
                   13762:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13763:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13764:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13765:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13766:              \%checksums);
1.1210    raeburn  13767:     return \%checksums;
                   13768: }
                   13769: 
1.1379    raeburn  13770: sub fetch_crl_pemfile {
                   13771:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   13772: }
                   13773: 
                   13774: sub save_crl_pem {
                   13775:     my ($response) = @_;
1.1380    raeburn  13776:     my ($msg,$hadchanges);
1.1379    raeburn  13777:     if (ref($response)) {
                   13778:         my $now = time;
                   13779:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   13780:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   13781:         if (open(my $fh,'>',"$tmpcrl")) {
                   13782:             print $fh $response->content;
                   13783:             close($fh);
                   13784:             if (-e $lonca) {
                   13785:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   13786:                     my $check = <PIPE>;
                   13787:                     close(PIPE);
                   13788:                     chomp($check);
                   13789:                     if ($check eq 'verify OK') {
                   13790:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  13791:                         my $backup;
1.1379    raeburn  13792:                         if (-e $dest) {
1.1380    raeburn  13793:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   13794:                                 $backup = 'ok';
                   13795:                             }
1.1379    raeburn  13796:                         }
                   13797:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   13798:                             $msg = 'ok';
1.1380    raeburn  13799:                             if ($backup) {
                   13800:                                 my (%oldnums,%newnums);
                   13801:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   13802:                                     while (<PIPE>) {
                   13803:                                         $oldnums{(split(/:/))[1]} = 1;
                   13804:                                     }
                   13805:                                     close(PIPE);
                   13806:                                 }
                   13807:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   13808:                                     while(<PIPE>) {
                   13809:                                         $newnums{(split(/:/))[1]} = 1;
                   13810:                                     }
                   13811:                                     close(PIPE);
                   13812:                                 }
                   13813:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   13814:                                     unless (exists($oldnums{$key})) {
                   13815:                                         $hadchanges = 1;
                   13816:                                         last;
                   13817:                                     }
                   13818:                                 }
                   13819:                                 unless ($hadchanges) {
                   13820:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   13821:                                         unless (exists($newnums{$key})) {
                   13822:                                             $hadchanges = 1;
                   13823:                                             last;
                   13824:                                         }
                   13825:                                     }
                   13826:                                 }
                   13827:                             }
1.1379    raeburn  13828:                         }
                   13829:                     } else {
                   13830:                         unlink($tmpcrl);
                   13831:                     }
                   13832:                 } else {
                   13833:                     unlink($tmpcrl);
                   13834:                 }
                   13835:             } else {
                   13836:                 unlink($tmpcrl);
                   13837:             }
                   13838:         }
                   13839:     }
1.1380    raeburn  13840:     return ($msg,$hadchanges);
1.1379    raeburn  13841: }
                   13842: 
1.327     albertel 13843: # ------------------------------------------------------------ Read domain file
                   13844: {
1.852     albertel 13845:     my $loaded;
1.846     albertel 13846:     my %domain;
                   13847: 
1.852     albertel 13848:     sub parse_domain_tab {
                   13849: 	my ($lines) = @_;
                   13850: 	foreach my $line (@$lines) {
                   13851: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13852: 
1.846     albertel 13853: 	    chomp($line);
1.852     albertel 13854: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13855: 	    my %this_domain;
                   13856: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13857: 			       'lang_def', 'city', 'longi', 'lati',
                   13858: 			       'primary') {
                   13859: 		$this_domain{$field} = shift(@elements);
                   13860: 	    }
                   13861: 	    $domain{$name} = \%this_domain;
1.852     albertel 13862: 	}
                   13863:     }
1.864     albertel 13864: 
                   13865:     sub reset_domain_info {
                   13866: 	undef($loaded);
                   13867: 	undef(%domain);
                   13868:     }
                   13869: 
1.852     albertel 13870:     sub load_domain_tab {
1.1293    raeburn  13871: 	my ($ignore_cache,$nocache) = @_;
                   13872: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13873: 	my $fh;
1.1359    raeburn  13874: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13875: 	    my @lines = <$fh>;
                   13876: 	    &parse_domain_tab(\@lines);
1.448     albertel 13877: 	}
1.852     albertel 13878: 	close($fh);
                   13879: 	$loaded = 1;
1.327     albertel 13880:     }
1.846     albertel 13881: 
                   13882:     sub domain {
1.852     albertel 13883: 	&load_domain_tab() if (!$loaded);
                   13884: 
1.846     albertel 13885: 	my ($name,$what) = @_;
                   13886: 	return if ( !exists($domain{$name}) );
                   13887: 
                   13888: 	if (!$what) {
                   13889: 	    return $domain{$name}{'description'};
                   13890: 	}
                   13891: 	return $domain{$name}{$what};
                   13892:     }
1.974     raeburn  13893: 
                   13894:     sub domain_info {
                   13895:         &load_domain_tab() if (!$loaded);
                   13896:         return %domain;
                   13897:     }
                   13898: 
1.327     albertel 13899: }
                   13900: 
                   13901: 
1.1       albertel 13902: # ------------------------------------------------------------- Read hosts file
                   13903: {
1.838     albertel 13904:     my %hostname;
1.844     albertel 13905:     my %hostdom;
1.845     albertel 13906:     my %libserv;
1.852     albertel 13907:     my $loaded;
1.888     albertel 13908:     my %name_to_host;
1.1074    raeburn  13909:     my %internetdom;
1.1107    raeburn  13910:     my %LC_dns_serv;
1.852     albertel 13911: 
                   13912:     sub parse_hosts_tab {
                   13913: 	my ($file) = @_;
                   13914: 	foreach my $configline (@$file) {
                   13915: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13916:             chomp($configline);
                   13917: 	    if ($configline =~ /^\^/) {
                   13918:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13919:                     $LC_dns_serv{$1} = 1;
                   13920:                 }
                   13921:                 next;
                   13922:             }
1.1074    raeburn  13923: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13924: 	    $name=~s/\s//g;
                   13925: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13926:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13927:                     my $curr = $hostname{$id};
                   13928:                     my $skip;
                   13929:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13930:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13931:                             $skip = 1;
                   13932:                         } else {
                   13933:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13934:                         }
                   13935:                     }
                   13936:                     unless ($skip) {
                   13937:                         push(@{$name_to_host{$name}},$id);
                   13938:                     }
                   13939:                 } else {
                   13940:                     push(@{$name_to_host{$name}},$id);
                   13941:                 }
1.852     albertel 13942: 		$hostname{$id}=$name;
                   13943: 		$hostdom{$id}=$domain;
                   13944: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13945:                 if (defined($protocol)) {
                   13946:                     if ($protocol eq 'https') {
                   13947:                         $protocol{$id} = $protocol;
                   13948:                     } else {
                   13949:                         $protocol{$id} = 'http'; 
                   13950:                     }
1.968     raeburn  13951:                 } else {
1.969     raeburn  13952:                     $protocol{$id} = 'http';
1.968     raeburn  13953:                 }
1.1074    raeburn  13954:                 if (defined($intdom)) {
                   13955:                     $internetdom{$id} = $intdom;
                   13956:                 }
1.852     albertel 13957: 	    }
                   13958: 	}
                   13959:     }
1.864     albertel 13960:     
                   13961:     sub reset_hosts_info {
1.897     albertel 13962: 	&purge_remembered();
1.864     albertel 13963: 	&reset_domain_info();
                   13964: 	&reset_hosts_ip_info();
1.1339    raeburn  13965:         undef(%internetdom);
1.892     albertel 13966: 	undef(%name_to_host);
1.864     albertel 13967: 	undef(%hostname);
                   13968: 	undef(%hostdom);
                   13969: 	undef(%libserv);
                   13970: 	undef($loaded);
                   13971:     }
1.1       albertel 13972: 
1.852     albertel 13973:     sub load_hosts_tab {
1.1293    raeburn  13974: 	my ($ignore_cache,$nocache) = @_;
                   13975: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13976: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13977: 	my @config = <$config>;
                   13978: 	&parse_hosts_tab(\@config);
                   13979: 	close($config);
                   13980: 	$loaded=1;
1.1       albertel 13981:     }
1.852     albertel 13982: 
1.838     albertel 13983:     sub hostname {
1.852     albertel 13984: 	&load_hosts_tab() if (!$loaded);
                   13985: 
1.838     albertel 13986: 	my ($lonid) = @_;
                   13987: 	return $hostname{$lonid};
                   13988:     }
1.845     albertel 13989: 
1.838     albertel 13990:     sub all_hostnames {
1.852     albertel 13991: 	&load_hosts_tab() if (!$loaded);
                   13992: 
1.838     albertel 13993: 	return %hostname;
                   13994:     }
1.845     albertel 13995: 
1.888     albertel 13996:     sub all_names {
1.1293    raeburn  13997:         my ($ignore_cache,$nocache) = @_;
                   13998: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13999: 
                   14000: 	return %name_to_host;
                   14001:     }
                   14002: 
1.974     raeburn  14003:     sub all_host_domain {
                   14004:         &load_hosts_tab() if (!$loaded);
                   14005:         return %hostdom;
                   14006:     }
                   14007: 
1.1339    raeburn  14008:     sub all_host_intdom {
                   14009:         &load_hosts_tab() if (!$loaded);
                   14010:         return %internetdom;
                   14011:     }
                   14012: 
1.845     albertel 14013:     sub is_library {
1.852     albertel 14014: 	&load_hosts_tab() if (!$loaded);
                   14015: 
1.845     albertel 14016: 	return exists($libserv{$_[0]});
                   14017:     }
                   14018: 
                   14019:     sub all_library {
1.852     albertel 14020: 	&load_hosts_tab() if (!$loaded);
                   14021: 
1.845     albertel 14022: 	return %libserv;
                   14023:     }
                   14024: 
1.1062    droeschl 14025:     sub unique_library {
                   14026: 	#2x reverse removes all hostnames that appear more than once
                   14027:         my %unique = reverse &all_library();
                   14028:         return reverse %unique;
                   14029:     }
                   14030: 
1.841     albertel 14031:     sub get_servers {
1.852     albertel 14032: 	&load_hosts_tab() if (!$loaded);
                   14033: 
1.841     albertel 14034: 	my ($domain,$type) = @_;
                   14035: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14036: 	                                          : %hostname;
                   14037: 	my %result;
1.842     albertel 14038: 	if (ref($domain) eq 'ARRAY') {
                   14039: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14040: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14041: 		    $result{$host} = $hostname;
                   14042: 		}
                   14043: 	    }
                   14044: 	} else {
                   14045: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14046: 		if ($hostdom{$host} eq $domain) {
                   14047: 		    $result{$host} = $hostname;
                   14048: 		}
1.841     albertel 14049: 	    }
                   14050: 	}
                   14051: 	return %result;
                   14052:     }
1.845     albertel 14053: 
1.1062    droeschl 14054:     sub get_unique_servers {
                   14055:         my %unique = reverse &get_servers(@_);
                   14056: 	return reverse %unique;
                   14057:     }
                   14058: 
1.844     albertel 14059:     sub host_domain {
1.852     albertel 14060: 	&load_hosts_tab() if (!$loaded);
                   14061: 
1.844     albertel 14062: 	my ($lonid) = @_;
                   14063: 	return $hostdom{$lonid};
                   14064:     }
                   14065: 
1.841     albertel 14066:     sub all_domains {
1.852     albertel 14067: 	&load_hosts_tab() if (!$loaded);
                   14068: 
1.841     albertel 14069: 	my %seen;
                   14070: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14071: 	return @uniq;
                   14072:     }
1.1074    raeburn  14073: 
                   14074:     sub internet_dom {
                   14075:         &load_hosts_tab() if (!$loaded);
                   14076: 
                   14077:         my ($lonid) = @_;
                   14078:         return $internetdom{$lonid};
                   14079:     }
1.1107    raeburn  14080: 
                   14081:     sub is_LC_dns {
                   14082:         &load_hosts_tab() if (!$loaded);
                   14083: 
                   14084:         my ($hostname) = @_;
                   14085:         return exists($LC_dns_serv{$hostname});
                   14086:     }
                   14087: 
1.1       albertel 14088: }
                   14089: 
1.847     albertel 14090: { 
                   14091:     my %iphost;
1.856     albertel 14092:     my %name_to_ip;
                   14093:     my %lonid_to_ip;
1.869     albertel 14094: 
1.847     albertel 14095:     sub get_hosts_from_ip {
                   14096: 	my ($ip) = @_;
                   14097: 	my %iphosts = &get_iphost();
                   14098: 	if (ref($iphosts{$ip})) {
                   14099: 	    return @{$iphosts{$ip}};
                   14100: 	}
                   14101: 	return;
1.839     albertel 14102:     }
1.864     albertel 14103:     
                   14104:     sub reset_hosts_ip_info {
                   14105: 	undef(%iphost);
                   14106: 	undef(%name_to_ip);
                   14107: 	undef(%lonid_to_ip);
                   14108:     }
1.856     albertel 14109: 
                   14110:     sub get_host_ip {
                   14111: 	my ($lonid) = @_;
                   14112: 	if (exists($lonid_to_ip{$lonid})) {
                   14113: 	    return $lonid_to_ip{$lonid};
                   14114: 	}
                   14115: 	my $name=&hostname($lonid);
                   14116:    	my $ip = gethostbyname($name);
                   14117: 	return if (!$ip || length($ip) ne 4);
                   14118: 	$ip=inet_ntoa($ip);
                   14119: 	$name_to_ip{$name}   = $ip;
                   14120: 	$lonid_to_ip{$lonid} = $ip;
                   14121: 	return $ip;
                   14122:     }
1.847     albertel 14123:     
                   14124:     sub get_iphost {
1.1293    raeburn  14125: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14126: 
1.869     albertel 14127: 	if (!$ignore_cache) {
                   14128: 	    if (%iphost) {
                   14129: 		return %iphost;
                   14130: 	    }
                   14131: 	    my ($ip_info,$cached)=
                   14132: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14133: 	    if ($cached) {
                   14134: 		%iphost      = %{$ip_info->[0]};
                   14135: 		%name_to_ip  = %{$ip_info->[1]};
                   14136: 		%lonid_to_ip = %{$ip_info->[2]};
                   14137: 		return %iphost;
                   14138: 	    }
                   14139: 	}
1.894     albertel 14140: 
                   14141: 	# get yesterday's info for fallback
                   14142: 	my %old_name_to_ip;
                   14143: 	my ($ip_info,$cached)=
                   14144: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14145: 	if ($cached) {
                   14146: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14147: 	}
                   14148: 
1.1293    raeburn  14149: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14150: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14151: 	    my $ip;
                   14152: 	    if (!exists($name_to_ip{$name})) {
                   14153: 		$ip = gethostbyname($name);
                   14154: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14155: 		    if (defined($old_name_to_ip{$name})) {
                   14156: 			$ip = $old_name_to_ip{$name};
                   14157: 			&logthis("Can't find $name defaulting to old $ip");
                   14158: 		    } else {
                   14159: 			&logthis("Name $name no IP found");
                   14160: 			next;
                   14161: 		    }
                   14162: 		} else {
                   14163: 		    $ip=inet_ntoa($ip);
1.847     albertel 14164: 		}
                   14165: 		$name_to_ip{$name} = $ip;
                   14166: 	    } else {
                   14167: 		$ip = $name_to_ip{$name};
1.653     albertel 14168: 	    }
1.888     albertel 14169: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14170: 		$lonid_to_ip{$id} = $ip;
                   14171: 	    }
                   14172: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14173: 	}
1.1293    raeburn  14174:         unless ($nocache) {
                   14175: 	    &do_cache_new('iphost','iphost',
                   14176: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14177: 		          48*60*60);
                   14178:         }
1.869     albertel 14179: 
1.847     albertel 14180: 	return %iphost;
1.598     albertel 14181:     }
                   14182: 
1.992     raeburn  14183:     #
                   14184:     #  Given a DNS returns the loncapa host name for that DNS 
                   14185:     # 
                   14186:     sub host_from_dns {
                   14187:         my ($dns) = @_;
                   14188:         my @hosts;
                   14189:         my $ip;
                   14190: 
1.993     raeburn  14191:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14192:             $ip = $name_to_ip{$dns};
                   14193:         }
                   14194:         if (!$ip) {
                   14195:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14196:             if (length($ip) == 4) { 
                   14197: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14198:             }
                   14199:         }
                   14200:         if ($ip) {
                   14201: 	    @hosts = get_hosts_from_ip($ip);
                   14202: 	    return $hosts[0];
                   14203:         }
                   14204:         return undef;
1.986     foxr     14205:     }
1.992     raeburn  14206: 
1.1074    raeburn  14207:     sub get_internet_names {
                   14208:         my ($lonid) = @_;
                   14209:         return if ($lonid eq '');
                   14210:         my ($idnref,$cached)=
                   14211:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14212:         if ($cached) {
                   14213:             return $idnref;
                   14214:         }
                   14215:         my $ip = &get_host_ip($lonid);
                   14216:         my @hosts = &get_hosts_from_ip($ip);
                   14217:         my %iphost = &get_iphost();
                   14218:         my (@idns,%seen);
                   14219:         foreach my $id (@hosts) {
                   14220:             my $dom = &host_domain($id);
                   14221:             my $prim_id = &domain($dom,'primary');
                   14222:             my $prim_ip = &get_host_ip($prim_id);
                   14223:             next if ($seen{$prim_ip});
                   14224:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14225:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14226:                     my $intdom = &internet_dom($id);
                   14227:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14228:                         push(@idns,$intdom);
                   14229:                     }
                   14230:                 }
                   14231:             }
                   14232:             $seen{$prim_ip} = 1;
                   14233:         }
1.1219    raeburn  14234:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14235:     }
                   14236: 
1.986     foxr     14237: }
                   14238: 
1.1079    raeburn  14239: sub all_loncaparevs {
1.1249    raeburn  14240:     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  14241: }
                   14242: 
1.1227    raeburn  14243: # ---------------------------------------------------------- Read loncaparev table
                   14244: {
                   14245:     sub load_loncaparevs { 
                   14246:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14247:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14248:                 while (my $configline=<$config>) {
                   14249:                     chomp($configline);
                   14250:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14251:                     $loncaparevs{$hostid}=$loncaparev;
                   14252:                 }
                   14253:                 close($config);
                   14254:             }
                   14255:         }
                   14256:     }
                   14257: }
                   14258: 
                   14259: # ---------------------------------------------------------- Read serverhostID table
                   14260: {
                   14261:     sub load_serverhomeIDs {
                   14262:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14263:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14264:                 while (my $configline=<$config>) {
                   14265:                     chomp($configline);
                   14266:                     my ($name,$id)=split(/:/,$configline);
                   14267:                     $serverhomeIDs{$name}=$id;
                   14268:                 }
                   14269:                 close($config);
                   14270:             }
                   14271:         }
                   14272:     }
                   14273: }
                   14274: 
                   14275: 
1.862     albertel 14276: BEGIN {
                   14277: 
                   14278: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14279:     unless ($readit) {
                   14280: {
                   14281:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14282:     %perlvar = (%perlvar,%{$configvars});
                   14283: }
                   14284: 
                   14285: 
1.1       albertel 14286: # ------------------------------------------------------ Read spare server file
                   14287: {
1.1359    raeburn  14288:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14289: 
                   14290:     while (my $configline=<$config>) {
                   14291:        chomp($configline);
1.284     matthew  14292:        if ($configline) {
1.784     albertel 14293: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14294: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14295: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14296:        }
                   14297:     }
1.448     albertel 14298:     close($config);
1.1       albertel 14299: }
1.11      www      14300: # ------------------------------------------------------------ Read permissions
                   14301: {
1.1359    raeburn  14302:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14303: 
                   14304:     while (my $configline=<$config>) {
1.448     albertel 14305: 	chomp($configline);
                   14306: 	if ($configline) {
                   14307: 	    my ($role,$perm)=split(/ /,$configline);
                   14308: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14309: 	}
1.11      www      14310:     }
1.448     albertel 14311:     close($config);
1.11      www      14312: }
                   14313: 
                   14314: # -------------------------------------------- Read plain texts for permissions
                   14315: {
1.1359    raeburn  14316:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14317: 
                   14318:     while (my $configline=<$config>) {
1.448     albertel 14319: 	chomp($configline);
                   14320: 	if ($configline) {
1.742     raeburn  14321: 	    my ($short,@plain)=split(/:/,$configline);
                   14322:             %{$prp{$short}} = ();
                   14323: 	    if (@plain > 0) {
                   14324:                 $prp{$short}{'std'} = $plain[0];
                   14325:                 for (my $i=1; $i<@plain; $i++) {
                   14326:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14327:                 }
                   14328:             }
1.448     albertel 14329: 	}
1.135     www      14330:     }
1.448     albertel 14331:     close($config);
1.135     www      14332: }
                   14333: 
                   14334: # ---------------------------------------------------------- Read package table
                   14335: {
1.1359    raeburn  14336:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14337: 
                   14338:     while (my $configline=<$config>) {
1.483     albertel 14339: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14340: 	chomp($configline);
                   14341: 	my ($short,$plain)=split(/:/,$configline);
                   14342: 	my ($pack,$name)=split(/\&/,$short);
                   14343: 	if ($plain ne '') {
                   14344: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14345: 	    $packagetab{$short}=$plain; 
                   14346: 	}
1.11      www      14347:     }
1.448     albertel 14348:     close($config);
1.329     matthew  14349: }
                   14350: 
1.1073    raeburn  14351: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14352: 
                   14353: &load_loncaparevs();
1.1073    raeburn  14354: 
1.1074    raeburn  14355: # ---------------------------------------------------------- Read serverhostID table
                   14356: 
1.1227    raeburn  14357: &load_serverhomeIDs();
                   14358: 
                   14359: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14360: {
                   14361:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14362:     if (-e $file) {
                   14363:         my $parser = HTML::LCParser->new($file);
                   14364:         while (my $token = $parser->get_token()) {
                   14365:             if ($token->[0] eq 'S') {
                   14366:                 my $item = $token->[1];
                   14367:                 my $name = $token->[2]{'name'};
                   14368:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14369:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14370:                 my $namematch = $token->[2]{'namematch'};
                   14371:                 if ($item eq 'parameter') {
                   14372:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14373:                         my $release = $parser->get_text();
                   14374:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14375:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14376:                     }
                   14377:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14378:                     my $release = $parser->get_text();
                   14379:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14380:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14381:                 }
                   14382:             }
                   14383:         }
                   14384:     }
1.1073    raeburn  14385: }
                   14386: 
1.1138    raeburn  14387: # ---------------------------------------------------------- Read managers table
                   14388: {
                   14389:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14390:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14391:             while (my $configline=<$config>) {
                   14392:                 chomp($configline);
                   14393:                 next if ($configline =~ /^\#/);
                   14394:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14395:                     $managerstab{$configline} = 1;
                   14396:                 }
                   14397:             }
                   14398:             close($config);
                   14399:         }
                   14400:     }
                   14401: }
                   14402: 
1.329     matthew  14403: # ------------- set up temporary directory
                   14404: {
1.1117    foxr     14405:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14406: 
1.11      www      14407: }
                   14408: 
1.794     albertel 14409: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14410: 				'compress_threshold'=> 20_000,
                   14411:  			        });
1.185     www      14412: 
1.281     www      14413: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14414: $dumpcount=0;
1.958     www      14415: $locknum=0;
1.22      www      14416: 
1.163     harris41 14417: &logtouch();
1.672     albertel 14418: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14419: $readit=1;
1.564     albertel 14420:     {
                   14421: 	use integer;
                   14422: 	my $test=(2**32)+1;
1.568     albertel 14423: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14424: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14425:     }
1.195     www      14426: }
1.1       albertel 14427: }
1.179     www      14428: 
1.1       albertel 14429: 1;
1.191     harris41 14430: __END__
                   14431: 
1.243     albertel 14432: =pod
                   14433: 
1.191     harris41 14434: =head1 NAME
                   14435: 
1.243     albertel 14436: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14437: 
                   14438: =head1 SYNOPSIS
                   14439: 
1.243     albertel 14440: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14441: 
                   14442:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14443: 
1.243     albertel 14444: Common parameters:
                   14445: 
                   14446: =over 4
                   14447: 
                   14448: =item *
                   14449: 
                   14450: $uname : an internal username (if $cname expecting a course Id specifically)
                   14451: 
                   14452: =item *
                   14453: 
                   14454: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14455: 
                   14456: =item *
                   14457: 
                   14458: $symb : a resource instance identifier
                   14459: 
                   14460: =item *
                   14461: 
                   14462: $namespace : the name of a .db file that contains the data needed or
                   14463: being set.
                   14464: 
                   14465: =back
                   14466: 
1.394     bowersj2 14467: =head1 OVERVIEW
1.191     harris41 14468: 
1.394     bowersj2 14469: lonnet provides subroutines which interact with the
                   14470: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14471: about classes, users, and resources.
1.243     albertel 14472: 
                   14473: For many of these objects you can also use this to store data about
                   14474: them or modify them in various ways.
1.191     harris41 14475: 
1.394     bowersj2 14476: =head2 Symbs
1.191     harris41 14477: 
1.394     bowersj2 14478: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14479: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14480: map, the resource number of the resource in the map, and the URL of
                   14481: the resource itself. The latter is somewhat redundant, but might help
                   14482: if maps change.
                   14483: 
                   14484: An example is
                   14485: 
                   14486:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14487: 
                   14488: The respective map entry is
                   14489: 
                   14490:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14491:   title="Problem 2">
                   14492:  </resource>
                   14493: 
                   14494: Symbs are used by the random number generator, as well as to store and
                   14495: restore data specific to a certain instance of for example a problem.
                   14496: 
                   14497: =head2 Storing And Retrieving Data
                   14498: 
                   14499: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14500: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14501: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14502: is is the non-critical message twin of cstore. These functions are for
                   14503: handlers to store a perl hash to a user's permanent data space in an
                   14504: easy manner, and to retrieve it again on another call. It is expected
                   14505: that a handler would use this once at the beginning to retrieve data,
                   14506: and then again once at the end to send only the new data back.
                   14507: 
                   14508: The data is stored in the user's data directory on the user's
                   14509: homeserver under the ID of the course.
                   14510: 
                   14511: The hash that is returned by restore will have all of the previous
                   14512: value for all of the elements of the hash.
                   14513: 
                   14514: Example:
                   14515: 
                   14516:  #creating a hash
                   14517:  my %hash;
                   14518:  $hash{'foo'}='bar';
                   14519: 
                   14520:  #storing it
                   14521:  &Apache::lonnet::cstore(\%hash);
                   14522: 
                   14523:  #changing a value
                   14524:  $hash{'foo'}='notbar';
                   14525: 
                   14526:  #adding a new value
                   14527:  $hash{'bar'}='foo';
                   14528:  &Apache::lonnet::cstore(\%hash);
                   14529: 
                   14530:  #retrieving the hash
                   14531:  my %history=&Apache::lonnet::restore();
                   14532: 
                   14533:  #print the hash
                   14534:  foreach my $key (sort(keys(%history))) {
                   14535:    print("\%history{$key} = $history{$key}");
                   14536:  }
                   14537: 
                   14538: Will print out:
1.191     harris41 14539: 
1.394     bowersj2 14540:  %history{1:foo} = bar
                   14541:  %history{1:keys} = foo:timestamp
                   14542:  %history{1:timestamp} = 990455579
                   14543:  %history{2:bar} = foo
                   14544:  %history{2:foo} = notbar
                   14545:  %history{2:keys} = foo:bar:timestamp
                   14546:  %history{2:timestamp} = 990455580
                   14547:  %history{bar} = foo
                   14548:  %history{foo} = notbar
                   14549:  %history{timestamp} = 990455580
                   14550:  %history{version} = 2
                   14551: 
                   14552: Note that the special hash entries C<keys>, C<version> and
                   14553: C<timestamp> were added to the hash. C<version> will be equal to the
                   14554: total number of versions of the data that have been stored. The
                   14555: C<timestamp> attribute will be the UNIX time the hash was
                   14556: stored. C<keys> is available in every historical section to list which
                   14557: keys were added or changed at a specific historical revision of a
                   14558: hash.
                   14559: 
                   14560: B<Warning>: do not store the hash that restore returns directly. This
                   14561: will cause a mess since it will restore the historical keys as if the
                   14562: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14563: 
1.394     bowersj2 14564: Calling convention:
1.191     harris41 14565: 
1.1225    raeburn  14566:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14567:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14568: 
1.394     bowersj2 14569: For more detailed information, see lonnet specific documentation.
1.191     harris41 14570: 
1.394     bowersj2 14571: =head1 RETURN MESSAGES
1.191     harris41 14572: 
1.394     bowersj2 14573: =over 4
1.191     harris41 14574: 
1.394     bowersj2 14575: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14576: 
1.394     bowersj2 14577: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14578: when the connection is brought back up
1.191     harris41 14579: 
1.394     bowersj2 14580: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14581: for later delivery
1.191     harris41 14582: 
1.967     bisitz   14583: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14584: 
1.394     bowersj2 14585: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14586: that was requested
1.191     harris41 14587: 
1.243     albertel 14588: =back
1.191     harris41 14589: 
1.243     albertel 14590: =head1 PUBLIC SUBROUTINES
1.191     harris41 14591: 
1.243     albertel 14592: =head2 Session Environment Functions
1.191     harris41 14593: 
1.243     albertel 14594: =over 4
1.191     harris41 14595: 
1.394     bowersj2 14596: =item * 
                   14597: X<appenv()>
1.949     raeburn  14598: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14599: the user envirnoment file, and will be restored for each access this
1.620     albertel 14600: user makes during this session, also modifies the %env for the current
1.949     raeburn  14601: process. Optional rolesarrayref - if defined contains a reference to an array
                   14602: of roles which are exempt from the restriction on modifying user.role entries 
                   14603: in the user's environment.db and in %env.    
1.191     harris41 14604: 
                   14605: =item *
1.394     bowersj2 14606: X<delenv()>
1.987     raeburn  14607: B<delenv($delthis,$regexp)>: removes all items from the session
                   14608: environment file that begin with $delthis. If the 
                   14609: optional second arg - $regexp - is true, $delthis is treated as a 
                   14610: regular expression, otherwise \Q$delthis\E is used. 
                   14611: The values are also deleted from the current processes %env.
1.191     harris41 14612: 
1.795     albertel 14613: =item * get_env_multiple($name) 
                   14614: 
                   14615: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14616: values may be defined and end up as an array ref.
                   14617: 
                   14618: returns an array of values
                   14619: 
1.243     albertel 14620: =back
                   14621: 
                   14622: =head2 User Information
1.191     harris41 14623: 
1.243     albertel 14624: =over 4
1.191     harris41 14625: 
                   14626: =item *
1.394     bowersj2 14627: X<queryauthenticate()>
                   14628: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14629: authentication scheme
                   14630: 
                   14631: =item *
1.394     bowersj2 14632: X<authenticate()>
1.1073    raeburn  14633: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14634: authenticate user from domain's lib servers (first use the current
                   14635: one). C<$upass> should be the users password.
1.1073    raeburn  14636: $checkdefauth is optional (value is 1 if a check should be made to
                   14637:    authenticate user using default authentication method, and allow
                   14638:    account creation if username does not have account in the domain).
                   14639: $clientcancheckhost is optional (value is 1 if checking whether the
                   14640:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14641: 
                   14642: =item *
1.394     bowersj2 14643: X<homeserver()>
                   14644: B<homeserver($uname,$udom)>: find the server which has
                   14645: the user's directory and files (there must be only one), this caches
                   14646: the answer, and also caches if there is a borken connection.
1.191     harris41 14647: 
                   14648: =item *
1.394     bowersj2 14649: X<idget()>
1.1300    raeburn  14650: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14651: a list of student/employee IDs or clicker IDs
                   14652: (student/employee IDs are a unique resource in a domain, there must be 
                   14653: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14654: clickerIDs are not necessarily unique, as students might share clickers.
                   14655: (returns hash: id=>name,id=>name)
1.191     harris41 14656: 
                   14657: =item *
1.394     bowersj2 14658: X<idrget()>
                   14659: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14660: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14661: 
                   14662: =item *
1.394     bowersj2 14663: X<idput()>
1.1300    raeburn  14664: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14665: names and associated student/employee IDs or clicker IDs.
                   14666: 
                   14667: =item *
                   14668: X<iddel()>
                   14669: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14670: student/employee ID or clicker ID username look-ups from domain.
                   14671: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14672: If no $uhome is provided, it will be determined usig &homeserver()
                   14673: for each user.  If no $namespace is provided, the default is ids.
                   14674: 
                   14675: =item *
                   14676: X<updateclickers()>
                   14677: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14678: clicker ID-to-username look-ups in clickers.db on library server.
                   14679: Permitted actions are add or del (i.e., add or delete). The 
                   14680: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14681: value is an escaped comma-separated list of usernames (for whom the
                   14682: library server is the homeserver), who registered that particular ID.
                   14683: If $critical is true, the update will be sent via &critical, otherwise
                   14684: &reply() will be used.
1.191     harris41 14685: 
                   14686: =item *
1.394     bowersj2 14687: X<rolesinit()>
1.1169    droeschl 14688: B<rolesinit($udom,$username)>: get user privileges.
                   14689: returns user role, first access and timer interval hashes
1.243     albertel 14690: 
                   14691: =item *
1.1171    droeschl 14692: X<privileged()>
                   14693: B<privileged($username,$domain)>: returns a true if user has a
                   14694: privileged and active role (i.e. su or dc), false otherwise.
                   14695: 
                   14696: =item *
1.551     albertel 14697: X<getsection()>
                   14698: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14699: course $cname, return section name/number or '' for "not in course"
                   14700: and '-1' for "no section"
                   14701: 
                   14702: =item *
1.394     bowersj2 14703: X<userenvironment()>
                   14704: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14705: passed in @what from the requested user's environment, returns a hash
                   14706: 
1.858     raeburn  14707: =item * 
                   14708: X<userlog_query()>
1.859     albertel 14709: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14710: activity.log file. %filters defines filters applied when parsing the
                   14711: log file. These can be start or end timestamps, or the type of action
                   14712: - log to look for Login or Logout events, check for Checkin or
                   14713: Checkout, role for role selection. The response is in the form
                   14714: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14715: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14716: 
1.243     albertel 14717: =back
                   14718: 
                   14719: =head2 User Roles
                   14720: 
                   14721: =over 4
                   14722: 
                   14723: =item *
                   14724: 
1.1284    raeburn  14725: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14726: returns codes for allowed actions.
                   14727: 
                   14728: The first argument is required, all others are optional.
                   14729: 
                   14730: $priv is the privilege being checked.
                   14731: $uri contains additional information about what is being checked for access (e.g.,
                   14732: URL, course ID etc.). 
                   14733: $symb is the unique resource instance identifier in a course; if needed,
                   14734: but not provided, it will be retrieved via a call to &symbread(). 
                   14735: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14736: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14737: files).
                   14738: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14739: prevents recursive calls to &allowed.
                   14740: 
1.243     albertel 14741:  F: full access
                   14742:  U,I,K: authentication modes (cxx only)
                   14743:  '': forbidden
                   14744:  1: user needs to choose course
                   14745:  2: browse allowed
1.766     albertel 14746:  A: passphrase authentication needed
1.1284    raeburn  14747:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14748: 
                   14749: =item *
                   14750: 
1.1192    raeburn  14751: constructaccess($url,$setpriv) : check for access to construction space URL
                   14752: 
                   14753: See if the owner domain and name in the URL match those in the
                   14754: expected environment.  If so, return three element list
                   14755: ($ownername,$ownerdomain,$ownerhome).
                   14756: 
                   14757: Otherwise return the null string.
                   14758: 
                   14759: If second argument 'setpriv' is true, it assigns the privileges,
                   14760: and returns the same three element list, unless the owner has
                   14761: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14762: in which case the null string is returned.
                   14763: 
                   14764: =item *
                   14765: 
1.1326    raeburn  14766: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14767: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14768: for system, domain, and course level. $uname and $udom are optional (current
                   14769: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14770: 
                   14771: =item *
                   14772: 
1.988     raeburn  14773: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14774: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14775: $type is Course (default) or Community.
1.988     raeburn  14776: If $forcedefault evaluates to true, text returned will be default 
                   14777: text for $type. Otherwise, if this is a course, the text returned 
                   14778: will be a custom name for the role (if defined in the course's 
                   14779: environment).  If no custom name is defined the default is returned.
                   14780:    
1.832     raeburn  14781: =item *
                   14782: 
1.1219    raeburn  14783: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14784: All arguments are optional. Returns a hash of a roles, either for
                   14785: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14786: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14787: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14788: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14789: For each key, value is set to colon-separated start and end times for
                   14790: the role.  If no username and domain are specified, will default to
1.934     raeburn  14791: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14792: of role statuses (active, future or previous), roles 
                   14793: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14794: to restrict the list of roles reported. If no array ref is 
                   14795: provided for types, will default to return only active roles.
1.834     albertel 14796: 
1.1195    raeburn  14797: =item *
                   14798: 
                   14799: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14800: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14801: 
                   14802: Additional optional arguments are: $type (if role checking is to be restricted 
                   14803: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14804: available roles) or future (roles available in the future), and
                   14805: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14806: have active Domain Coordinator role in course's domain or in additional
                   14807: domains (specified in 'Domains to check for privileged users' in course
                   14808: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14809: 
                   14810: =item *
                   14811: 
                   14812: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14813: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14814: $possdomains and $possroles are optional array refs -- to domains to check and
                   14815: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14816: users' roles.db to check for a dc or su role in any domain. This can be
                   14817: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14818: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14819: this then allows &privileged_by_domain() to be used, which caches the identity
                   14820: of privileged users, eliminating the need for repeated calls to &dump().
                   14821: 
                   14822: =item *
                   14823: 
                   14824: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14825: where the outer hash keys are domains specified in the $possdomains array ref,
                   14826: next inner hash keys are privileged roles specified in the $roles array ref,
                   14827: and the innermost hash contains key = value pairs for username:domain = end:start
                   14828: for active or future "privileged" users with that role in that domain. To avoid
                   14829: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14830: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14831: 
1.243     albertel 14832: =back
                   14833: 
                   14834: =head2 User Modification
                   14835: 
                   14836: =over 4
                   14837: 
                   14838: =item *
                   14839: 
1.957     raeburn  14840: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14841: user for the level given by URL.  Optional start and end dates (leave empty
                   14842: string or zero for "no date")
1.191     harris41 14843: 
                   14844: =item *
                   14845: 
1.243     albertel 14846: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14847: change a users, password, possible return values are: ok,
                   14848: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14849: refused
1.191     harris41 14850: 
                   14851: =item *
                   14852: 
1.243     albertel 14853: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14854: 
                   14855: =item *
                   14856: 
1.1058    raeburn  14857: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14858:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14859: 
                   14860: will update user information (firstname,middlename,lastname,generation,
                   14861: permanentemail), and if forceid is true, student/employee ID also.
                   14862: A user's institutional affiliation(s) can also be updated.
                   14863: User information fields will not be overwritten with empty entries 
                   14864: unless the field is included in the $candelete array reference.
                   14865: This array is included when a single user is modified via "Manage Users",
                   14866: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14867: 
                   14868: =item *
                   14869: 
1.286     matthew  14870: modifystudent
                   14871: 
1.957     raeburn  14872: modify a student's enrollment and identification information.
1.1235    raeburn  14873: The course id is resolved based on the current user's environment.  
                   14874: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14875: associated with a course.
                   14876: 
1.297     matthew  14877: This call is essentially a wrapper for lonnet::modifyuser and
                   14878: lonnet::modify_student_enrollment
1.286     matthew  14879: 
                   14880: Inputs: 
                   14881: 
                   14882: =over 4
                   14883: 
1.957     raeburn  14884: =item B<$udom> Student's loncapa domain
1.286     matthew  14885: 
1.957     raeburn  14886: =item B<$uname> Student's loncapa login name
1.286     matthew  14887: 
1.964     bisitz   14888: =item B<$uid> Student/Employee ID
1.286     matthew  14889: 
1.957     raeburn  14890: =item B<$umode> Student's authentication mode
1.286     matthew  14891: 
1.957     raeburn  14892: =item B<$upass> Student's password
1.286     matthew  14893: 
1.957     raeburn  14894: =item B<$first> Student's first name
1.286     matthew  14895: 
1.957     raeburn  14896: =item B<$middle> Student's middle name
1.286     matthew  14897: 
1.957     raeburn  14898: =item B<$last> Student's last name
1.286     matthew  14899: 
1.957     raeburn  14900: =item B<$gene> Student's generation
1.286     matthew  14901: 
1.957     raeburn  14902: =item B<$usec> Student's section in course
1.286     matthew  14903: 
                   14904: =item B<$end> Unix time of the roles expiration
                   14905: 
                   14906: =item B<$start> Unix time of the roles start date
                   14907: 
                   14908: =item B<$forceid> If defined, allow $uid to be changed
                   14909: 
                   14910: =item B<$desiredhome> server to use as home server for student
                   14911: 
1.957     raeburn  14912: =item B<$email> Student's permanent e-mail address
                   14913: 
                   14914: =item B<$type> Type of enrollment (auto or manual)
                   14915: 
1.963     raeburn  14916: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14917: 
                   14918: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14919: 
1.963     raeburn  14920: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14921: 
1.963     raeburn  14922: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14923: 
1.1216    raeburn  14924: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14925: 
                   14926: =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  14927: 
1.286     matthew  14928: =back
1.297     matthew  14929: 
                   14930: =item *
                   14931: 
                   14932: modify_student_enrollment
                   14933: 
1.1235    raeburn  14934: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14935: 'role.request.course' must be defined for this function to proceed.
                   14936: 
                   14937: Inputs:
                   14938: 
                   14939: =over 4
                   14940: 
1.1235    raeburn  14941: =item $udom, student's domain
1.297     matthew  14942: 
1.1235    raeburn  14943: =item $uname, student's name
1.297     matthew  14944: 
1.1235    raeburn  14945: =item $uid, student's user id
1.297     matthew  14946: 
1.1235    raeburn  14947: =item $first, student's first name
1.297     matthew  14948: 
                   14949: =item $middle
                   14950: 
                   14951: =item $last
                   14952: 
                   14953: =item $gene
                   14954: 
                   14955: =item $usec
                   14956: 
                   14957: =item $end
                   14958: 
                   14959: =item $start
                   14960: 
1.957     raeburn  14961: =item $type
                   14962: 
                   14963: =item $locktype
                   14964: 
                   14965: =item $cid
                   14966: 
                   14967: =item $selfenroll
                   14968: 
                   14969: =item $context
                   14970: 
1.1216    raeburn  14971: =item $credits, number of credits student will earn from this class
                   14972: 
1.1314    raeburn  14973: =item $instsec, institutional course section code for student
                   14974: 
1.297     matthew  14975: =back
                   14976: 
1.191     harris41 14977: 
                   14978: =item *
                   14979: 
1.243     albertel 14980: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14981: custom role; give a custom role to a user for the level given by URL.  Specify
                   14982: name and domain of role author, and role name
1.191     harris41 14983: 
                   14984: =item *
                   14985: 
1.243     albertel 14986: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14987: 
                   14988: =item *
                   14989: 
1.243     albertel 14990: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14991: 
                   14992: =back
                   14993: 
                   14994: =head2 Course Infomation
                   14995: 
                   14996: =over 4
1.191     harris41 14997: 
                   14998: =item *
                   14999: 
1.1118    foxr     15000: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15001: specified course id, including all environment settings for the
                   15002: course, the description of the course will be in the hash under the
                   15003: key 'description'
1.191     harris41 15004: 
1.1118    foxr     15005: $options is an optional parameter that if supplied is a hash reference that controls
                   15006: what how this function works.  It has the following key/values:
                   15007: 
                   15008: =over 4
                   15009: 
                   15010: =item freshen_cache
                   15011: 
                   15012: If defined, and the environment cache for the course is valid, it is 
                   15013: returned in the returned hash.
                   15014: 
                   15015: =item one_time
                   15016: 
                   15017: If defined, the last cache time is set to _now_
                   15018: 
                   15019: =item user
                   15020: 
                   15021: If defined, the supplied username is used instead of the current user.
                   15022: 
                   15023: 
                   15024: =back
                   15025: 
1.191     harris41 15026: =item *
                   15027: 
1.624     albertel 15028: resdata($name,$domain,$type,@which) : request for current parameter
                   15029: setting for a specific $type, where $type is either 'course' or 'user',
                   15030: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15031: answers for 10 minutes.
1.243     albertel 15032: 
1.877     foxr     15033: =item *
                   15034: 
                   15035: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15036: data base, returning a hash that is keyed by the resource name and has
                   15037: values that are the resource value.  I believe that the timestamps and
                   15038: versions are also returned.
                   15039: 
1.1236    raeburn  15040: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15041: supplemental content area. This routine caches the number of files for 
                   15042: 10 minutes.
                   15043: 
1.243     albertel 15044: =back
                   15045: 
                   15046: =head2 Course Modification
                   15047: 
                   15048: =over 4
1.191     harris41 15049: 
                   15050: =item *
                   15051: 
1.243     albertel 15052: writecoursepref($courseid,%prefs) : write preferences (environment
                   15053: database) for a course
1.191     harris41 15054: 
                   15055: =item *
                   15056: 
1.1011    raeburn  15057: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15058: 
                   15059: =item *
                   15060: 
1.1038    raeburn  15061: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15062: 
1.1167    droeschl 15063: =item *
                   15064: 
                   15065: is_course($courseid), is_course($cdom, $cnum)
                   15066: 
                   15067: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15068: two component version $cdom, $cnum. It checks if the specified course exists.
                   15069: 
                   15070: Returns:
                   15071:     undef if the course doesn't exist, otherwise
                   15072:     in scalar context the combined courseid.
                   15073:     in list context the two components of the course identifier, domain and 
                   15074:     courseid.    
                   15075: 
1.243     albertel 15076: =back
                   15077: 
                   15078: =head2 Resource Subroutines
                   15079: 
                   15080: =over 4
1.191     harris41 15081: 
                   15082: =item *
                   15083: 
1.243     albertel 15084: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15085: 
                   15086: =item *
                   15087: 
1.243     albertel 15088: repcopy($filename) : subscribes to the requested file, and attempts to
                   15089: replicate from the owning library server, Might return
1.607     raeburn  15090: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15091: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15092: resource. Expects the local filesystem pathname
                   15093: (/home/httpd/html/res/....)
                   15094: 
                   15095: =back
                   15096: 
                   15097: =head2 Resource Information
                   15098: 
                   15099: =over 4
1.191     harris41 15100: 
                   15101: =item *
                   15102: 
1.1228    raeburn  15103: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15104: and returns the value of a variety of different possible values,
                   15105: $varname should be a request string, and the other parameters can be
                   15106: used to specify who and what one is asking about. Ordinarily, $cid 
                   15107: does not need to be specified, as it is retrived from 
                   15108: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15109: within lonuserstate::loadmap() when initializing a course, before
                   15110: $env{'request.course.id'} has been set, so it needs to be provided
                   15111: in that one case.
1.243     albertel 15112: 
                   15113: Possible values for $varname are environment.lastname (or other item
                   15114: from the envirnment hash), user.name (or someother aspect about the
                   15115: user), resource.0.maxtries (or some other part and parameter of a
                   15116: resource)
1.204     albertel 15117: 
                   15118: =item *
                   15119: 
1.243     albertel 15120: directcondval($number) : get current value of a condition; reads from a state
                   15121: string
1.204     albertel 15122: 
                   15123: =item *
                   15124: 
1.243     albertel 15125: condval($condidx) : value of condition index based on state
1.204     albertel 15126: 
                   15127: =item *
                   15128: 
1.1362    raeburn  15129: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15130: resource's metadata, $what should be either a specific key, or either
                   15131: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15132: packages that this resource currently uses, the last 3 arguments are 
                   15133: only used internally for recursive metadata.
                   15134: 
                   15135: the toolsymb is only used where the uri is for an external tool (for which
                   15136: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15137: 
1.1371    raeburn  15138: this function automatically caches all requests except any made recursively
                   15139: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15140: defined).
1.191     harris41 15141: 
                   15142: =item *
                   15143: 
1.243     albertel 15144: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15145: network of library servers; returns file handle of where SQL and regex results
                   15146: will be stored for query
1.191     harris41 15147: 
                   15148: =item *
                   15149: 
1.1282    raeburn  15150: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15151: return symbolic list entry (all arguments optional). 
                   15152: 
                   15153: Args: filename is the filename (including path) for the file for which a symb 
                   15154: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15155: to check access status if more than one resource was found in the bighash 
                   15156: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15157: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15158: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15159: cause possible symbs to be checked to determine if they are subject to content
                   15160: blocking, if so they will not be included as possible symbs; possibles is a
                   15161: ref to a hash, which, as a side effect, will be populated with all possible 
                   15162: symbs (content blocking not tested).
                   15163:  
1.243     albertel 15164: returns the data handle
1.191     harris41 15165: 
                   15166: =item *
                   15167: 
1.1190    raeburn  15168: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15169: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15170: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15171: on failure, user must be in a course, as it assumes the existence of
                   15172: the course initial hash, and uses $env('request.course.id'}.  The third
                   15173: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15174: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15175: encrypted; otherwise it will be null.  
1.191     harris41 15176: 
                   15177: =item *
                   15178: 
1.243     albertel 15179: symbclean($symb) : removes versions numbers from a symb, returns the
                   15180: cleaned symb
1.191     harris41 15181: 
                   15182: =item *
                   15183: 
1.243     albertel 15184: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15185: course map, user must be in a course for it to work.
1.191     harris41 15186: 
                   15187: =item *
                   15188: 
1.243     albertel 15189: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15190: 
                   15191: =item *
                   15192: 
1.243     albertel 15193: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15194: a random seed, all arguments are optional, if they aren't sent it uses the
                   15195: environment to derive them. Note: if symb isn't sent and it can't get one
                   15196: from &symbread it will use the current time as its return value
1.191     harris41 15197: 
                   15198: =item *
                   15199: 
1.243     albertel 15200: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15201: unfakeable, receipt
1.191     harris41 15202: 
                   15203: =item *
                   15204: 
1.620     albertel 15205: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15206: 
                   15207: =item *
                   15208: 
1.243     albertel 15209: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15210: 
                   15211: =item *
                   15212: 
1.243     albertel 15213: 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 15214: 
                   15215: =item *
                   15216: 
1.243     albertel 15217: 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 15218: 
                   15219: =item *
                   15220: 
1.243     albertel 15221: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15222: 
                   15223: =item *
                   15224: 
1.243     albertel 15225: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15226: forcing spreadsheet to reevaluate the resource scores next time.
                   15227: 
1.1195    raeburn  15228: =item * 
                   15229: 
1.1196    raeburn  15230: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15231: when viewing in course context.
1.1195    raeburn  15232: 
1.1196    raeburn  15233:  input: six args -- filename (decluttered), course number, course domain,
                   15234:                     url, symb (if registered) and group (if this is a 
                   15235:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15236: 
1.1196    raeburn  15237:  output: array of five scalars --
1.1195    raeburn  15238:          $cfile -- url for file editing if editable on current server
                   15239:          $home -- homeserver of resource (i.e., for author if published,
                   15240:                                           or course if uploaded.).
                   15241:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15242:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15243:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15244: 
                   15245: =item *
                   15246: 
                   15247: is_course_upload($file,$cnum,$cdom)
                   15248: 
                   15249: Used in course context to determine if current file was uploaded to 
                   15250: the course (i.e., would be found in /userfiles/docs on the course's 
                   15251: homeserver.
                   15252: 
                   15253:   input: 3 args -- filename (decluttered), course number and course domain.
                   15254:   output: boolean -- 1 if file was uploaded.
                   15255: 
1.243     albertel 15256: =back
                   15257: 
                   15258: =head2 Storing/Retreiving Data
                   15259: 
                   15260: =over 4
1.191     harris41 15261: 
                   15262: =item *
                   15263: 
1.1269    raeburn  15264: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15265: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15266: the remaining args aren't required and if they aren't passed or are '' they will
                   15267: be derived from the env (with the exception of $laststore, which is an 
                   15268: optional arg used when a user's submission is stored in grading).
                   15269: $laststore is $version=$timestamp, where $version is the most recent version
                   15270: number retrieved for the corresponding $symb in the $namespace db file, and
                   15271: $timestamp is the timestamp for that transaction (UNIX time).
                   15272: $laststore is currently only passed when cstore() is called by 
                   15273: structuretags::finalize_storage().
1.191     harris41 15274: 
                   15275: =item *
                   15276: 
1.1269    raeburn  15277: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15278: but uses critical subroutine
1.191     harris41 15279: 
                   15280: =item *
                   15281: 
1.243     albertel 15282: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15283: all args are optional
1.191     harris41 15284: 
                   15285: =item *
                   15286: 
1.717     albertel 15287: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15288: dumps the complete (or key matching regexp) namespace into a hash
                   15289: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15290: normally &store()ed into
                   15291: 
                   15292: $range should be either an integer '100' (give me the first 100
                   15293:                                            matching records)
                   15294:               or be  two integers sperated by a - with no spaces
                   15295:                  '30-50' (give me the 30th through the 50th matching
                   15296:                           records)
                   15297: 
                   15298: 
                   15299: =item *
                   15300: 
1.1269    raeburn  15301: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15302: replaces a &store() version of data with a replacement set of data
                   15303: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15304: reference. If $tolog is true, the transaction is logged in the courselog
                   15305: with an action=PUTSTORE.
1.717     albertel 15306: 
                   15307: =item *
                   15308: 
1.243     albertel 15309: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15310: works very similar to store/cstore, but all data is stored in a
                   15311: temporary location and can be reset using tmpreset, $storehash should
                   15312: be a hash reference, returns nothing on success
1.191     harris41 15313: 
                   15314: =item *
                   15315: 
1.243     albertel 15316: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15317: similar to restore, but all data is stored in a temporary location and
                   15318: can be reset using tmpreset. Returns a hash of values on success,
                   15319: error string otherwise.
1.191     harris41 15320: 
                   15321: =item *
                   15322: 
1.243     albertel 15323: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15324: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15325: 
                   15326: =item *
                   15327: 
1.243     albertel 15328: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15329: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15330: 
                   15331: =item *
                   15332: 
1.243     albertel 15333: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15334: namesp ($udom and $uname are optional)
1.191     harris41 15335: 
                   15336: =item *
                   15337: 
1.702     albertel 15338: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15339: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15340: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15341: 
1.702     albertel 15342: $range should be either an integer '100' (give me the first 100
                   15343:                                            matching records)
                   15344:               or be  two integers sperated by a - with no spaces
                   15345:                  '30-50' (give me the 30th through the 50th matching
                   15346:                           records)
1.449     matthew  15347: =item *
                   15348: 
                   15349: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15350: $store can be a scalar, an array reference, or if the amount to be 
                   15351: incremented is > 1, a hash reference.
                   15352: 
                   15353: ($udom and $uname are optional)
1.191     harris41 15354: 
                   15355: =item *
                   15356: 
1.243     albertel 15357: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15358: ($udom and $uname are optional)
1.191     harris41 15359: 
                   15360: =item *
                   15361: 
1.243     albertel 15362: cput($namespace,$storehash,$udom,$uname) : critical put
                   15363: ($udom and $uname are optional)
1.191     harris41 15364: 
                   15365: =item *
                   15366: 
1.748     albertel 15367: newput($namespace,$storehash,$udom,$uname) :
                   15368: 
                   15369: Attempts to store the items in the $storehash, but only if they don't
                   15370: currently exist, if this succeeds you can be certain that you have 
                   15371: successfully created a new key value pair in the $namespace db.
                   15372: 
                   15373: 
                   15374: Args:
                   15375:  $namespace: name of database to store values to
                   15376:  $storehash: hashref to store to the db
                   15377:  $udom: (optional) domain of user containing the db
                   15378:  $uname: (optional) name of user caontaining the db
                   15379: 
                   15380: Returns:
                   15381:  'ok' -> succeeded in storing all keys of $storehash
                   15382:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15383:                         least <key> already existed in the db (other
                   15384:                         requested keys may also already exist)
1.967     bisitz   15385:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15386:  'con_lost' -> unable to contact request server
                   15387:  'refused' -> action was not allowed by remote machine
                   15388: 
                   15389: 
                   15390: =item *
                   15391: 
1.243     albertel 15392: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15393: reference filled in from namesp (encrypts the return communication)
                   15394: ($udom and $uname are optional)
1.191     harris41 15395: 
                   15396: =item *
                   15397: 
1.243     albertel 15398: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15399: critical subroutine
                   15400: 
1.806     raeburn  15401: =item *
                   15402: 
1.860     raeburn  15403: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15404: array reference filled in from namespace found in domain level on either
                   15405: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15406: 
                   15407: =item *
                   15408: 
1.860     raeburn  15409: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15410: domain level either on specified domain server ($uhome) or primary domain 
                   15411: server ($udom and $uhome are optional)
1.806     raeburn  15412: 
1.943     raeburn  15413: =item * 
                   15414: 
1.1240    raeburn  15415: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15416: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15417: the target domain.
                   15418: 
                   15419: May also include additional key => value pairs for the following groups:
                   15420: 
                   15421: =over
                   15422: 
                   15423: =item
                   15424: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15425: 
                   15426: =over
                   15427: 
                   15428: =item defaultquota, authorquota
                   15429: 
                   15430: =back
                   15431: 
                   15432: =item
                   15433: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15434: portfolio for users).
                   15435: 
                   15436: =over
                   15437: 
                   15438: =item
                   15439: aboutme, blog, webdav, portfolio
                   15440: 
                   15441: =back
                   15442: 
                   15443: =item
                   15444: requestcourses: ability to request courses, and how requests are processed.
                   15445: 
                   15446: =over
                   15447: 
                   15448: =item
1.1305    raeburn  15449: official, unofficial, community, textbook, placement
1.1240    raeburn  15450: 
                   15451: =back
                   15452: 
                   15453: =item
                   15454: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15455: 
                   15456: =over
                   15457: 
                   15458: =item
1.1256    raeburn  15459: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15460: 
                   15461: =back
                   15462: 
                   15463: =item
                   15464: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15465: for course's uploaded content.
                   15466: 
                   15467: =over
                   15468: 
                   15469: =item
1.1246    raeburn  15470: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15471: communityquota, textbookquota, placementquota
1.1240    raeburn  15472: 
                   15473: =back
                   15474: 
                   15475: =item
                   15476: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15477: on your servers.
                   15478: 
                   15479: =over
                   15480: 
                   15481: =item 
                   15482: remotesessions, hostedsessions
                   15483: 
                   15484: =back
                   15485: 
                   15486: =back
                   15487: 
                   15488: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15489: utility to create a configuration.db file on a domain's primary library server 
                   15490: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15491: -- corresponding values are authentication type (internal, krb4, krb5,
                   15492: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15493: will be available. Values are retrieved from cache (if current), unless the
                   15494: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15495: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15496: 
                   15497: Typical usage:
1.943     raeburn  15498: 
1.1240    raeburn  15499: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15500: 
1.243     albertel 15501: =back
                   15502: 
                   15503: =head2 Network Status Functions
                   15504: 
                   15505: =over 4
1.191     harris41 15506: 
                   15507: =item *
                   15508: 
1.1137    raeburn  15509: dirlist() : return directory list based on URI (first arg).
                   15510: 
                   15511: Inputs: 1 required, 5 optional.
                   15512: 
                   15513: =over
                   15514: 
                   15515: =item 
                   15516: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15517: 
                   15518: =item
                   15519: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15520: 
                   15521: =item
                   15522: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15523: 
                   15524: =item
                   15525: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15526: 
                   15527: =item
                   15528: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15529: 
                   15530: =item 
                   15531: $alternateRoot - path to prepend in place of path from $uri.
                   15532: 
                   15533: =back
                   15534: 
                   15535: Returns: Array of up to two items.
                   15536: 
                   15537: =over
                   15538: 
                   15539: a reference to an array of files/subdirectories
                   15540: 
                   15541: =over
                   15542: 
                   15543: Each element in the array of files/subdirectories is a & separated list of
                   15544: item name and the result of running stat on the item.  If dirlist was requested
                   15545: for a file instead of a directory, the item name will be ''. For a directory 
                   15546: listing, if the item is a metadata file, the element will end &N&M 
                   15547: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15548: default copyright set (1).  
                   15549: 
                   15550: =back
                   15551: 
                   15552: a scalar containing error condition (if encountered).
                   15553: 
                   15554: =over
                   15555: 
                   15556: =item 
                   15557: no_host (no homeserver identified for $username:$domain).
                   15558: 
                   15559: =item 
                   15560: no_such_host (server contacted for listing not identified as valid host).
                   15561: 
                   15562: =item 
                   15563: con_lost (connection to remote server failed).
                   15564: 
                   15565: =item 
                   15566: refused (invalid $username:$domain received on lond side).
                   15567: 
                   15568: =item 
                   15569: no_such_dir (directory at specified path on lond side does not exist). 
                   15570: 
                   15571: =item 
                   15572: empty (directory at specified path on lond side is empty).
                   15573: 
                   15574: =over
                   15575: 
                   15576: This is currently not encountered because the &ls3, &ls2, 
                   15577: &ls (_handler) routines on the lond side do not filter out
                   15578: . and .. from a directory listing. 
                   15579: 
                   15580: =back
                   15581: 
                   15582: =back
                   15583: 
                   15584: =back
1.191     harris41 15585: 
                   15586: =item *
                   15587: 
1.243     albertel 15588: spareserver() : find server with least workload from spare.tab
                   15589: 
1.986     foxr     15590: 
                   15591: =item *
                   15592: 
                   15593: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15594: if there is no corresponding loncapa host.
                   15595: 
1.243     albertel 15596: =back
                   15597: 
1.986     foxr     15598: 
1.243     albertel 15599: =head2 Apache Request
                   15600: 
                   15601: =over 4
1.191     harris41 15602: 
                   15603: =item *
                   15604: 
1.243     albertel 15605: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15606: localhost, posts hash
                   15607: 
                   15608: =back
                   15609: 
                   15610: =head2 Data to String to Data
                   15611: 
                   15612: =over 4
1.191     harris41 15613: 
                   15614: =item *
                   15615: 
1.243     albertel 15616: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15617: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15618: 
                   15619: =item *
                   15620: 
1.243     albertel 15621: hashref2str($hashref) : convert a hashref into a string complete with
                   15622: escaping and '=' and '&' separators, supports elements that are
                   15623: arrayrefs and hashrefs
1.191     harris41 15624: 
                   15625: =item *
                   15626: 
1.243     albertel 15627: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15628: with escaping and '&' separators, supports elements that are arrayrefs
                   15629: and hashrefs
1.191     harris41 15630: 
                   15631: =item *
                   15632: 
1.243     albertel 15633: str2hash($string) : convert string to hash using unescaping and
                   15634: splitting on '=' and '&', supports elements that are arrayrefs and
                   15635: hashrefs
1.191     harris41 15636: 
                   15637: =item *
                   15638: 
1.243     albertel 15639: str2array($string) : convert string to hash using unescaping and
                   15640: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15641: 
                   15642: =back
                   15643: 
                   15644: =head2 Logging Routines
                   15645: 
                   15646: 
                   15647: These routines allow one to make log messages in the lonnet.log and
                   15648: lonnet.perm logfiles.
1.191     harris41 15649: 
1.1119    foxr     15650: =over 4
                   15651: 
1.191     harris41 15652: =item *
                   15653: 
1.243     albertel 15654: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15655: 
                   15656: =item *
                   15657: 
1.243     albertel 15658: logthis() : append message to the normal lonnet.log file, it gets
                   15659: preiodically rolled over and deleted.
1.191     harris41 15660: 
                   15661: =item *
                   15662: 
1.243     albertel 15663: logperm() : append a permanent message to lonnet.perm.log, this log
                   15664: file never gets deleted by any automated portion of the system, only
                   15665: messages of critical importance should go in here.
                   15666: 
1.1119    foxr     15667: 
1.243     albertel 15668: =back
                   15669: 
                   15670: =head2 General File Helper Routines
                   15671: 
                   15672: =over 4
1.191     harris41 15673: 
                   15674: =item *
                   15675: 
1.481     raeburn  15676: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15677: (a) files in /uploaded
                   15678:   (i) If a local copy of the file exists - 
                   15679:       compares modification date of local copy with last-modified date for 
                   15680:       definitive version stored on home server for course. If local copy is 
                   15681:       stale, requests a new version from the home server and stores it. 
                   15682:       If the original has been removed from the home server, then local copy 
                   15683:       is unlinked.
                   15684:   (ii) If local copy does not exist -
                   15685:       requests the file from the home server and stores it. 
                   15686:   
                   15687:   If $caller is 'uploadrep':  
                   15688:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15689:     for request for files originally uploaded via DOCS. 
                   15690:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15691:   
                   15692:   Otherwise:
                   15693:      This indicates a call from the content generation phase of the request.
                   15694:      -  returns the entire contents of the file or -1.
                   15695:      
                   15696: (b) files in /res
                   15697:    - returns the entire contents of a file or -1; 
                   15698:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15699: 
1.712     albertel 15700: 
                   15701: =item *
                   15702: 
                   15703: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15704:                   reference
                   15705: 
                   15706: returns either a stat() list of data about the file or an empty list
                   15707: if the file doesn't exist or couldn't find out about it (connection
                   15708: problems or user unknown)
                   15709: 
1.191     harris41 15710: =item *
                   15711: 
1.243     albertel 15712: filelocation($dir,$file) : returns file system location of a file
                   15713: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15714: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15715: and a file of ../bob will become /a/bob)
1.191     harris41 15716: 
                   15717: =item *
                   15718: 
                   15719: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15720: filelocation except for hrefs
                   15721: 
                   15722: =item *
                   15723: 
1.1261    raeburn  15724: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15725: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15726: 
1.243     albertel 15727: =back
                   15728: 
1.608     albertel 15729: =head2 Usererfile file routines (/uploaded*)
                   15730: 
                   15731: =over 4
                   15732: 
                   15733: =item *
                   15734: 
                   15735: userfileupload(): main rotine for putting a file in a user or course's
                   15736:                   filespace, arguments are,
                   15737: 
1.620     albertel 15738:  formname - required - this is the name of the element in $env where the
1.608     albertel 15739:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15740:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15741:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15742:  context - if coursedoc, store the file in the course of the active role
                   15743:              of the current user; 
                   15744:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15745:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15746:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15747:          if undefined, it will be placed in "unknown"
                   15748: 
                   15749:  (This routine calls clean_filename() to remove any dangerous
                   15750:  characters from the filename, and then calls finuserfileupload() to
                   15751:  complete the transaction)
                   15752: 
                   15753:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15754:  and /adm/notfound.html if unsuccessful
                   15755: 
                   15756: =item *
                   15757: 
                   15758: clean_filename(): routine for cleaing a filename up for storage in
                   15759:                  userfile space, argument is:
                   15760: 
                   15761:  filename - proposed filename
                   15762: 
                   15763: returns: the new clean filename
                   15764: 
                   15765: =item *
                   15766: 
1.1090    raeburn  15767: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15768: userspace, probably shouldn't be called directly
                   15769: 
                   15770:   docuname: username or courseid of destination for the file
                   15771:   docudom: domain of user/course of destination for the file
                   15772:   formname: same as for userfileupload()
1.1090    raeburn  15773:   fname: filename (including subdirectories) for the file
                   15774:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15775:   allfiles: reference to hash used to store objects found by parser
                   15776:   codebase: reference to hash used for codebases of java objects found by parser
                   15777:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15778:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15779:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15780:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15781:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15782:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15783:   mimetype: reference to scalar to accommodate mime type determined
                   15784:             from File::MMagic if $parser = parse.
1.608     albertel 15785: 
                   15786:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15787:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15788:  was 'overwrite').
                   15789:  
1.608     albertel 15790: 
                   15791: =item *
                   15792: 
                   15793: renameuserfile(): renames an existing userfile to a new name
                   15794: 
                   15795:   Args:
                   15796:    docuname: username or courseid of destination for the file
                   15797:    docudom: domain of user/course of destination for the file
                   15798:    old: current file name (including any subdirs under userfiles)
                   15799:    new: desired file name (including any subdirs under userfiles)
                   15800: 
                   15801: =item *
                   15802: 
                   15803: mkdiruserfile(): creates a directory is a userfiles dir
                   15804: 
                   15805:   Args:
                   15806:    docuname: username or courseid of destination for the file
                   15807:    docudom: domain of user/course of destination for the file
                   15808:    dir: dir to create (including any subdirs under userfiles)
                   15809: 
                   15810: =item *
                   15811: 
                   15812: removeuserfile(): removes a file that exists in userfiles
                   15813: 
                   15814:   Args:
                   15815:    docuname: username or courseid of destination for the file
                   15816:    docudom: domain of user/course of destination for the file
                   15817:    fname: filname to delete (including any subdirs under userfiles)
                   15818: 
                   15819: =item *
                   15820: 
                   15821: removeuploadedurl(): convience function for removeuserfile()
                   15822: 
                   15823:   Args:
                   15824:    url:  a full /uploaded/... url to delete
                   15825: 
1.747     albertel 15826: =item * 
                   15827: 
                   15828: get_portfile_permissions():
                   15829:   Args:
                   15830:     domain: domain of user or course contain the portfolio files
                   15831:     user: name of user or num of course contain the portfolio files
                   15832:   Returns:
                   15833:     hashref of a dump of the proper file_permissions.db
                   15834:    
                   15835: 
                   15836: =item * 
                   15837: 
                   15838: get_access_controls():
                   15839: 
                   15840: Args:
                   15841:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15842:   group: (optional) the group you want the files associated with
                   15843:   file: (optional) the file you want access info on
                   15844: 
                   15845: Returns:
1.749     raeburn  15846:     a hash (keys are file names) of hashes containing
                   15847:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15848:         values are XML containing access control settings (see below) 
1.747     albertel 15849: 
                   15850: Internal notes:
                   15851: 
1.749     raeburn  15852:  access controls are stored in file_permissions.db as key=value pairs.
                   15853:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15854:         where scope -> public,guest,course,group,domains or users.
                   15855:               end -> UNIX time for end of access (0 -> no end date)
                   15856:               start -> UNIX time for start of access
                   15857: 
                   15858:     value -> XML description of access control
                   15859:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15860:             <start></start>
                   15861:             <end></end>
                   15862: 
                   15863:             <password></password>  for scope type = guest
                   15864: 
                   15865:             <domain></domain>     for scope type = course or group
                   15866:             <number></number>
                   15867:             <roles id="">
                   15868:              <role></role>
                   15869:              <access></access>
                   15870:              <section></section>
                   15871:              <group></group>
                   15872:             </roles>
                   15873: 
                   15874:             <dom></dom>         for scope type = domains
                   15875: 
                   15876:             <users>             for scope type = users
                   15877:              <user>
                   15878:               <uname></uname>
                   15879:               <udom></udom>
                   15880:              </user>
                   15881:             </users>
                   15882:            </scope> 
                   15883:               
                   15884:  Access data is also aggregated for each file in an additional key=value pair:
                   15885:  key -> path to file/file_name\0accesscontrol 
                   15886:  value -> reference to hash
                   15887:           hash contains key = value pairs
                   15888:           where key = uniqueID:scope_end_start
                   15889:                 value = UNIX time record was last updated
                   15890: 
                   15891:           Used to improve speed of look-ups of access controls for each file.  
                   15892:  
                   15893:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15894: 
1.1198    raeburn  15895: =item *
                   15896: 
1.749     raeburn  15897: modify_access_controls():
                   15898: 
                   15899: Modifies access controls for a portfolio file
                   15900: Args
                   15901: 1. file name
                   15902: 2. reference to hash of required changes,
                   15903: 3. domain
                   15904: 4. username
                   15905:   where domain,username are the domain of the portfolio owner 
                   15906:   (either a user or a course) 
                   15907: 
                   15908: Returns:
                   15909: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15910: 2. result of deletions ('ok' or 'error', with error message).
                   15911: 3. reference to hash of any new or updated access controls.
                   15912: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15913:    key = integer (inbound ID)
1.1198    raeburn  15914:    value = uniqueID
                   15915: 
                   15916: =item *
                   15917: 
                   15918: get_timebased_id():
                   15919: 
                   15920: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15921: course via the Course Editor (e.g., folders, composite pages, 
                   15922: group bulletin boards).
                   15923: 
                   15924: Args: (first three required; six others optional)
                   15925: 
                   15926: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15927:    docssequence, or name of group
                   15928: 
                   15929: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15930:    e.g., num, boardids
                   15931: 
                   15932: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15933:    file will be named nohist_namespace.db
                   15934: 
                   15935: 4. cdom: domain of course; default is current course domain from %env
                   15936: 
                   15937: 5. cnum: course number; default is current course number from %env
                   15938: 
                   15939: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15940:    unix timestamp to form the suffix, if the plain timestamp is already
                   15941:    in use.  Default is to not do this, but simply increment the unix 
                   15942:    timestamp by 1 until a unique key is obtained.
                   15943: 
                   15944: 7. who: holder of locking key; defaults to user:domain for user.
                   15945: 
                   15946: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15947:    retrying); default is 3.
                   15948: 
                   15949: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15950: 
                   15951: Returns:
                   15952: 
                   15953: 1. suffix obtained (numeric)
                   15954: 
                   15955: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15956: 
                   15957: 3. error: contains (localized) error message if an error occurred.
                   15958: 
1.747     albertel 15959: 
1.608     albertel 15960: =back
                   15961: 
1.243     albertel 15962: =head2 HTTP Helper Routines
                   15963: 
                   15964: =over 4
                   15965: 
1.191     harris41 15966: =item *
                   15967: 
                   15968: escape() : unpack non-word characters into CGI-compatible hex codes
                   15969: 
                   15970: =item *
                   15971: 
                   15972: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15973: 
1.243     albertel 15974: =back
                   15975: 
                   15976: =head1 PRIVATE SUBROUTINES
                   15977: 
                   15978: =head2 Underlying communication routines (Shouldn't call)
                   15979: 
                   15980: =over 4
                   15981: 
                   15982: =item *
                   15983: 
                   15984: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15985: 
                   15986: =item *
                   15987: 
                   15988: reply() : uses subreply to send a message to remote machine, logs all failures
                   15989: 
                   15990: =item *
                   15991: 
                   15992: critical() : passes a critical message to another server; if cannot
                   15993: get through then place message in connection buffer directory and
                   15994: returns con_delayed, if incapable of saving message, returns
                   15995: con_failed
                   15996: 
                   15997: =item *
                   15998: 
                   15999: reconlonc() : tries to reconnect lonc client processes.
                   16000: 
                   16001: =back
                   16002: 
                   16003: =head2 Resource Access Logging
                   16004: 
                   16005: =over 4
                   16006: 
                   16007: =item *
                   16008: 
                   16009: flushcourselogs() : flush (save) buffer logs and access logs
                   16010: 
                   16011: =item *
                   16012: 
                   16013: courselog($what) : save message for course in hash
                   16014: 
                   16015: =item *
                   16016: 
                   16017: courseacclog($what) : save message for course using &courselog().  Perform
                   16018: special processing for specific resource types (problems, exams, quizzes, etc).
                   16019: 
1.191     harris41 16020: =item *
                   16021: 
                   16022: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16023: as a PerlChildExitHandler
1.243     albertel 16024: 
                   16025: =back
                   16026: 
                   16027: =head2 Other
                   16028: 
                   16029: =over 4
                   16030: 
                   16031: =item *
                   16032: 
                   16033: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16034: 
                   16035: =back
                   16036: 
                   16037: =cut
1.877     foxr     16038: 

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