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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1392  ! raeburn     4: # $Id: lonnet.pm,v 1.1391 2018/11/28 05:05:36 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'})) {
                    714: 	return undef;
                    715:     }
1.1245    raeburn   716: 
                    717:     if (ref($userhashref) eq 'HASH') {
                    718:         $userhashref->{'name'} = $disk_env{'user.name'};
                    719:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   720:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   721:         if ($userhashref->{'lti'}) {
                    722:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    723:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    724:         }
1.1212    raeburn   725:     }
1.1245    raeburn   726: 
1.916     albertel  727:     return $handle;
                    728: }
                    729: 
1.830     albertel  730: sub timed_flock {
                    731:     my ($file,$lock_type) = @_;
                    732:     my $failed=0;
                    733:     eval {
                    734: 	local $SIG{__DIE__}='DEFAULT';
                    735: 	local $SIG{ALRM}=sub {
                    736: 	    $failed=1;
                    737: 	    die("failed lock");
                    738: 	};
                    739: 	alarm(13);
                    740: 	flock($file,$lock_type);
                    741: 	alarm(0);
                    742:     };
                    743:     if ($failed) {
                    744: 	return undef;
                    745:     } else {
                    746: 	return 1;
                    747:     }
                    748: }
                    749: 
1.1392  ! raeburn   750: sub get_sessionfile_vars {
        !           751:     my ($handle,$lonidsdir,$storearr) = @_;
        !           752:     my %returnhash;
        !           753:     unless (ref($storearr) eq 'ARRAY') {
        !           754:         return %returnhash;
        !           755:     }
        !           756:     if (-l "$lonidsdir/$handle.id") {
        !           757:         my $link = readlink("$lonidsdir/$handle.id");
        !           758:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
        !           759:             $handle = $1;
        !           760:         }
        !           761:     }
        !           762:     if ((-e "$lonidsdir/$handle.id") &&
        !           763:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
        !           764:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
        !           765:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
        !           766:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
        !           767:                 flock($idf,LOCK_SH);
        !           768:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
        !           769:                         &GDBM_READER(),0640)) {
        !           770:                     foreach my $item (@{$storearr}) {
        !           771:                         $returnhash{$item} = $disk_env{$item};
        !           772:                     }
        !           773:                     untie(%disk_env);
        !           774:                 }
        !           775:             }
        !           776:         }
        !           777:     }
        !           778:     return %returnhash;
        !           779: }
        !           780: 
1.5       www       781: # ---------------------------------------------------------- Append Environment
                    782: 
                    783: sub appenv {
1.949     raeburn   784:     my ($newenv,$roles) = @_;
                    785:     if (ref($newenv) eq 'HASH') {
                    786:         foreach my $key (keys(%{$newenv})) {
                    787:             my $refused = 0;
                    788: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    789:                 $refused = 1;
                    790:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   791:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   792:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    793:                         $refused = 0;
                    794:                     }
                    795:                 }
                    796:             }
                    797:             if ($refused) {
                    798:                 &logthis("<font color=\"blue\">WARNING: ".
                    799:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    800:                          .'</font>');
                    801: 	        delete($newenv->{$key});
                    802:             } else {
                    803:                 $env{$key}=$newenv->{$key};
                    804:             }
                    805:         }
1.1376    raeburn   806:         my $lonids = $perlvar{'lonIDsDir'};
                    807:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    808:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    809:             if ($opened
                    810: 	        && &timed_flock($env_file,LOCK_EX)
                    811: 	        &&
                    812: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    813: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    814: 	        while (my ($key,$value) = each(%{$newenv})) {
                    815: 	            $disk_env{$key} = $value;
                    816: 	        }
                    817: 	        untie(%disk_env);
                    818:             }
1.35      www       819:         }
1.191     harris41  820:     }
1.56      www       821:     return 'ok';
                    822: }
                    823: # ----------------------------------------------------- Delete from Environment
                    824: 
                    825: sub delenv {
1.1104    raeburn   826:     my ($delthis,$regexp,$roles) = @_;
                    827:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    828:         my $refused = 1;
                    829:         if (ref($roles) eq 'ARRAY') {
                    830:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    831:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    832:                 $refused = 0;
                    833:             }
                    834:         }
                    835:         if ($refused) {
                    836:             &logthis("<font color=\"blue\">WARNING: ".
                    837:                      "Attempt to delete from environment ".$delthis);
                    838:             return 'error';
                    839:         }
1.56      www       840:     }
1.917     albertel  841:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    842:     if ($opened
1.915     albertel  843: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  844: 	&&
                    845: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    846: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  847: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   848: 	    if ($regexp) {
                    849:                 if ($key=~/^$delthis/) {
                    850:                     delete($env{$key});
                    851:                     delete($disk_env{$key});
                    852:                 } 
                    853:             } else {
                    854:                 if ($key=~/^\Q$delthis\E/) {
                    855: 		    delete($env{$key});
                    856: 		    delete($disk_env{$key});
                    857: 	        }
                    858:             }
1.448     albertel  859: 	}
1.783     albertel  860: 	untie(%disk_env);
1.5       www       861:     }
                    862:     return 'ok';
1.369     albertel  863: }
                    864: 
1.790     albertel  865: sub get_env_multiple {
                    866:     my ($name) = @_;
                    867:     my @values;
                    868:     if (defined($env{$name})) {
                    869:         # exists is it an array
                    870:         if (ref($env{$name})) {
                    871:             @values=@{ $env{$name} };
                    872:         } else {
                    873:             $values[0]=$env{$name};
                    874:         }
                    875:     }
                    876:     return(@values);
                    877: }
                    878: 
1.958     www       879: # ------------------------------------------------------------------- Locking
                    880: 
                    881: sub set_lock {
                    882:     my ($text)=@_;
                    883:     $locknum++;
                    884:     my $id=$$.'-'.$locknum;
                    885:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    886:              'session.lock.'.$id => $text});
                    887:     return $id;
                    888: }
                    889: 
                    890: sub get_locks {
                    891:     my $num=0;
                    892:     my %texts=();
                    893:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    894:        if ($lock=~/\w/) {
                    895:           $num++;
                    896:           $texts{$lock}=$env{'session.lock.'.$lock};
                    897:        }
                    898:    }
                    899:    return ($num,%texts);
                    900: }
                    901: 
                    902: sub remove_lock {
                    903:     my ($id)=@_;
                    904:     my $newlocks='';
                    905:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    906:        if (($lock=~/\w/) && ($lock ne $id)) {
                    907:           $newlocks.=','.$lock;
                    908:        }
                    909:     }
                    910:     &appenv({'session.locks' => $newlocks});
                    911:     &delenv('session.lock.'.$id);
                    912: }
                    913: 
                    914: sub remove_all_locks {
                    915:     my $activelocks=$env{'session.locks'};
                    916:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    917:        if ($lock=~/\w/) {
                    918:           &remove_lock($lock);
                    919:        }
                    920:     }
                    921: }
                    922: 
                    923: 
1.369     albertel  924: # ------------------------------------------ Find out current server userload
                    925: sub userload {
                    926:     my $numusers=0;
                    927:     {
                    928: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    929: 	my $filename;
                    930: 	my $curtime=time;
                    931: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  932: 	    next if ($filename eq '.' || $filename eq '..');
                    933: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   934:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  935: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  936: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  937: 	}
                    938: 	closedir(LONIDS);
                    939:     }
                    940:     my $userloadpercent=0;
                    941:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    942:     if ($maxuserload) {
1.371     albertel  943: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  944:     }
1.372     albertel  945:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  946:     return $userloadpercent;
1.283     www       947: }
                    948: 
1.1       albertel  949: # ------------------------------ Find server with least workload from spare.tab
1.11      www       950: 
1.1       albertel  951: sub spareserver {
1.1083    raeburn   952:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  953:     my $spare_server;
1.370     albertel  954:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  955:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    956:                                                      :  $userloadpercent;
1.1083    raeburn   957:     my ($uint_dom,$remotesessions);
                    958:     if (($udom ne '') && (&domain($udom) ne '')) {
                    959:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    960:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    961:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    962:         $remotesessions = $udomdefaults{'remotesessions'};
                    963:     }
1.1123    raeburn   964:     my $spareshash = &this_host_spares($udom);
                    965:     if (ref($spareshash) eq 'HASH') {
                    966:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    967:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   968:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    969:                                              $try_server));
1.1123    raeburn   970: 	        ($spare_server, $lowest_load) =
                    971: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    972:             }
1.1083    raeburn   973:         }
1.784     albertel  974: 
1.1123    raeburn   975:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    976: 
                    977:         if (!$found_server) {
                    978:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    979: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   980:                     next unless (&spare_can_host($udom,$uint_dom,
                    981:                                                  $remotesessions,$try_server));
1.1123    raeburn   982: 	            ($spare_server, $lowest_load) =
                    983: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    984:                 }
                    985: 	    }
                    986:         }
1.784     albertel  987:     }
                    988: 
                    989:     if (!$want_server_name) {
1.968     raeburn   990:         my $protocol = 'http';
                    991:         if ($protocol{$spare_server} eq 'https') {
                    992:             $protocol = $protocol{$spare_server};
                    993:         }
1.1001    raeburn   994:         if (defined($spare_server)) {
                    995:             my $hostname = &hostname($spare_server);
1.1083    raeburn   996:             if (defined($hostname)) {
1.1001    raeburn   997: 	        $spare_server = $protocol.'://'.$hostname;
                    998:             }
                    999:         }
1.784     albertel 1000:     }
                   1001:     return $spare_server;
                   1002: }
                   1003: 
                   1004: sub compare_server_load {
1.1253    raeburn  1005:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1006: 
                   1007:     if ($required) {
                   1008:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1009:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1010:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1011:         if (($major eq '' && $minor eq '') ||
                   1012:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1013:             return ($spare_server,$lowest_load);
                   1014:         }
                   1015:     }
1.784     albertel 1016: 
                   1017:     my $loadans     = &reply('load',    $try_server);
                   1018:     my $userloadans = &reply('userload',$try_server);
                   1019: 
                   1020:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1021: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1022:     }
                   1023: 
                   1024:     my $load;
                   1025:     if ($loadans =~ /\d/) {
                   1026: 	if ($userloadans =~ /\d/) {
                   1027: 	    #both are numbers, pick the bigger one
                   1028: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1029: 		                              : $userloadans;
1.411     albertel 1030: 	} else {
1.784     albertel 1031: 	    $load = $loadans;
1.411     albertel 1032: 	}
1.784     albertel 1033:     } else {
                   1034: 	$load = $userloadans;
                   1035:     }
                   1036: 
                   1037:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1038: 	$spare_server = $try_server;
                   1039: 	$lowest_load  = $load;
1.370     albertel 1040:     }
1.784     albertel 1041:     return ($spare_server,$lowest_load);
1.202     matthew  1042: }
1.914     albertel 1043: 
                   1044: # --------------------------- ask offload servers if user already has a session
                   1045: sub find_existing_session {
                   1046:     my ($udom,$uname) = @_;
1.1123    raeburn  1047:     my $spareshash = &this_host_spares($udom);
                   1048:     if (ref($spareshash) eq 'HASH') {
                   1049:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1050:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1051:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1052:             }
                   1053:         }
                   1054:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1055:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1056:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1057:             }
                   1058:         }
1.914     albertel 1059:     }
                   1060:     return;
                   1061: }
                   1062: 
1.1389    raeburn  1063: # check if user's browser sent load balancer cookie and server still has session
                   1064: # and is not overloaded.
                   1065: sub check_for_balancer_cookie {
                   1066:     my ($r,$update_mtime) = @_;
                   1067:     my ($otherserver,$cookie);
                   1068:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1069:     if (exists($cookies{'balanceID'})) {
                   1070:         my $balid = $cookies{'balanceID'};
                   1071:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1072:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1073:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1074:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1075:                 my ($possudom,$possuname) = ($1,$2);
                   1076:                 my $has_session = 0;
                   1077:                 if ((&domain($possudom) ne '') &&
                   1078:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1079:                     my $try_server;
                   1080:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1081:                     if ($opened) {
                   1082:                         flock($idf,LOCK_SH);
                   1083:                         while (my $line = <$idf>) {
                   1084:                             chomp($line);
                   1085:                             if (&hostname($line) ne '') {
                   1086:                                 $try_server = $line;
                   1087:                                 last;
                   1088:                             }
                   1089:                         }
                   1090:                         close($idf);
                   1091:                         if (($try_server) &&
                   1092:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1093:                             my $lowest_load = 30000;
                   1094:                             ($otherserver,$lowest_load) =
                   1095:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1096:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1097:                                 $has_session = 1;
                   1098:                             } else {
                   1099:                                 undef($otherserver);
                   1100:                             }
                   1101:                         }
                   1102:                     }
                   1103:                 }
                   1104:                 if ($has_session) {
                   1105:                     if ($update_mtime) {
                   1106:                         my $atime = my $mtime = time;
                   1107:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1108:                     }
                   1109:                 } else {
                   1110:                     unlink("$balancedir/$cookie.id");
                   1111:                 }
                   1112:             }
                   1113:         }
                   1114:     }
                   1115:     return ($otherserver,$cookie);
                   1116: }
                   1117: 
                   1118: sub delbalcookie {
                   1119:     my ($cookie,$balancer) =@_;
                   1120:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1121:         my ($udom,$uname) = ($1,$2);
                   1122:         my $uprimary_id = &domain($udom,'primary');
                   1123:         my $uintdom = &internet_dom($uprimary_id);
                   1124:         my $intdom = &internet_dom($balancer);
                   1125:         my $serverhomedom = &host_domain($balancer);
                   1126:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1127:             return &reply("delbalcookie:$cookie",$balancer);
                   1128:         }
                   1129:     }
                   1130: }
                   1131: 
1.914     albertel 1132: # -------------------------------- ask if server already has a session for user
                   1133: sub has_user_session {
                   1134:     my ($lonid,$udom,$uname) = @_;
                   1135:     my $result = &reply(join(':','userhassession',
                   1136: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1137:     return 1 if ($result eq 'ok');
                   1138: 
                   1139:     return 0;
                   1140: }
                   1141: 
1.1076    raeburn  1142: # --------- determine least loaded server in a user's domain which allows login
                   1143: 
                   1144: sub choose_server {
1.1259    raeburn  1145:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1146:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1147:     my %servers = &get_servers($udom);
1.1076    raeburn  1148:     my $lowest_load = 30000;
1.1259    raeburn  1149:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1150:     if ($skiploadbal) {
                   1151:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1152:         unless (defined($cached)) {
                   1153:             my $cachetime = 60*60*24;
                   1154:             my %domconfig =
                   1155:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1156:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1157:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1158:                                            $cachetime);
                   1159:             }
                   1160:         }
                   1161:     }
1.1076    raeburn  1162:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1163:         if ($skiploadbal) {
                   1164:             if (ref($balancers) eq 'HASH') {
                   1165:                 next if (exists($balancers->{$lonhost}));
                   1166:             }
1.1389    raeburn  1167:         }
1.1115    raeburn  1168:         my $loginvia;
                   1169:         if ($checkloginvia) {
                   1170:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1171:             if ($loginvia) {
                   1172:                 my ($server,$path) = split(/:/,$loginvia);
                   1173:                 ($login_host, $lowest_load) =
1.1253    raeburn  1174:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1175:                 if ($login_host eq $server) {
                   1176:                     $portal_path = $path;
1.1151    raeburn  1177:                     $isredirect = 1;
1.1116    raeburn  1178:                 }
                   1179:             } else {
                   1180:                 ($login_host, $lowest_load) =
1.1253    raeburn  1181:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1182:                 if ($login_host eq $lonhost) {
                   1183:                     $portal_path = '';
1.1151    raeburn  1184:                     $isredirect = ''; 
1.1116    raeburn  1185:                 }
                   1186:             }
                   1187:         } else {
1.1076    raeburn  1188:             ($login_host, $lowest_load) =
1.1253    raeburn  1189:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1190:         }
                   1191:     }
                   1192:     if ($login_host ne '') {
1.1116    raeburn  1193:         $hostname = &hostname($login_host);
1.1076    raeburn  1194:     }
1.1331    raeburn  1195:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1196: }
                   1197: 
1.202     matthew  1198: # --------------------------------------------- Try to change a user's password
                   1199: 
                   1200: sub changepass {
1.799     raeburn  1201:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1202:     $currentpass = &escape($currentpass);
                   1203:     $newpass     = &escape($newpass);
1.1030    raeburn  1204:     my $lonhost = $perlvar{'lonHostID'};
                   1205:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1206: 		       $server);
                   1207:     if (! $answer) {
                   1208: 	&logthis("No reply on password change request to $server ".
                   1209: 		 "by $uname in domain $udom.");
                   1210:     } elsif ($answer =~ "^ok") {
                   1211:         &logthis("$uname in $udom successfully changed their password ".
                   1212: 		 "on $server.");
                   1213:     } elsif ($answer =~ "^pwchange_failure") {
                   1214: 	&logthis("$uname in $udom was unable to change their password ".
                   1215: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1216: 		 "or pwchange");
                   1217:     } elsif ($answer =~ "^non_authorized") {
                   1218:         &logthis("$uname in $udom did not get their password correct when ".
                   1219: 		 "attempting to change it on $server.");
                   1220:     } elsif ($answer =~ "^auth_mode_error") {
                   1221:         &logthis("$uname in $udom attempted to change their password despite ".
                   1222: 		 "not being locally or internally authenticated on $server.");
                   1223:     } elsif ($answer =~ "^unknown_user") {
                   1224:         &logthis("$uname in $udom attempted to change their password ".
                   1225: 		 "on $server but were unable to because $server is not ".
                   1226: 		 "their home server.");
                   1227:     } elsif ($answer =~ "^refused") {
                   1228: 	&logthis("$server refused to change $uname in $udom password because ".
                   1229: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1230:     } elsif ($answer =~ "invalid_client") {
                   1231:         &logthis("$server refused to change $uname in $udom password because ".
                   1232:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1233:     }
                   1234:     return $answer;
1.1       albertel 1235: }
                   1236: 
1.169     harris41 1237: # ----------------------- Try to determine user's current authentication scheme
                   1238: 
                   1239: sub queryauthenticate {
                   1240:     my ($uname,$udom)=@_;
1.456     albertel 1241:     my $uhome=&homeserver($uname,$udom);
                   1242:     if (!$uhome) {
                   1243: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1244: 	return 'no_host';
                   1245:     }
                   1246:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1247:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1248: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1249:     }
1.456     albertel 1250:     return $answer;
1.169     harris41 1251: }
                   1252: 
1.1       albertel 1253: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1254: 
1.1       albertel 1255: sub authenticate {
1.1073    raeburn  1256:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1257:     $upass=&escape($upass);
                   1258:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1259:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1260:     my $newhome;
1.836     www      1261:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1262: # Maybe the machine was offline and only re-appeared again recently?
                   1263:         &reconlonc();
                   1264: # One more
1.952     raeburn  1265: 	$uhome=&homeserver($uname,$udom,1);
                   1266:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1267:             if (defined(&domain($udom,'primary'))) {
                   1268:                 $newhome=&domain($udom,'primary');
                   1269:             }
                   1270:             if ($newhome ne '') {
                   1271:                 $uhome = $newhome;
                   1272:             }
                   1273:         }
1.836     www      1274: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1275: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1276: 	    return 'no_host';
                   1277:         }
1.1       albertel 1278:     }
1.1073    raeburn  1279:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1280:     if ($answer eq 'authorized') {
1.952     raeburn  1281:         if ($newhome) {
                   1282:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1283:             return 'no_account_on_host'; 
                   1284:         } else {
                   1285:             &logthis("User $uname at $udom authorized by $uhome");
                   1286:             return $uhome;
                   1287:         }
1.471     albertel 1288:     }
                   1289:     if ($answer eq 'non_authorized') {
                   1290: 	&logthis("User $uname at $udom rejected by $uhome");
                   1291: 	return 'no_host'; 
1.9       www      1292:     }
1.471     albertel 1293:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1294:     return 'no_host';
                   1295: }
                   1296: 
1.1073    raeburn  1297: sub can_host_session {
1.1074    raeburn  1298:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1299:     my $canhost = 1;
1.1074    raeburn  1300:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1301:     if (ref($remotesessions) eq 'HASH') {
                   1302:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1303:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1304:                 $canhost = 0;
                   1305:             } else {
                   1306:                 $canhost = 1;
                   1307:             }
                   1308:         }
                   1309:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1310:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1311:                 $canhost = 1;
                   1312:             } else {
                   1313:                 $canhost = 0;
                   1314:             }
                   1315:         }
                   1316:         if ($canhost) {
                   1317:             if ($remotesessions->{'version'} ne '') {
                   1318:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1319:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1320:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1321:                         my $major = $1;
                   1322:                         my $minor = $2;
                   1323:                         if (($major < $reqmajor ) ||
                   1324:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1325:                             $canhost = 0;
                   1326:                         }
                   1327:                     } else {
                   1328:                         $canhost = 0;
                   1329:                     }
                   1330:                 }
                   1331:             }
                   1332:         }
                   1333:     }
                   1334:     if ($canhost) {
                   1335:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1336:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1337:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1338:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1339:                 if (($uint_dom ne '') && 
                   1340:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1341:                     $canhost = 0;
                   1342:                 } else {
                   1343:                     $canhost = 1;
                   1344:                 }
                   1345:             }
                   1346:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1347:                 if (($uint_dom ne '') && 
                   1348:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1349:                     $canhost = 1;
                   1350:                 } else {
                   1351:                     $canhost = 0;
                   1352:                 }
                   1353:             }
                   1354:         }
                   1355:     }
                   1356:     return $canhost;
                   1357: }
                   1358: 
1.1083    raeburn  1359: sub spare_can_host {
                   1360:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1361:     my $canhost=1;
1.1279    raeburn  1362:     my $try_server_hostname = &hostname($try_server);
                   1363:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1364:     my $serverhomedom = &host_domain($serverhomeID);
                   1365:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1366:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1367:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1368:             $canhost = 0;
                   1369:         }
                   1370:     }
                   1371:     if (($canhost) && ($uint_dom)) {
                   1372:         my @intdoms;
                   1373:         my $internet_names = &get_internet_names($try_server);
                   1374:         if (ref($internet_names) eq 'ARRAY') {
                   1375:             @intdoms = @{$internet_names};
                   1376:         }
                   1377:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1378:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1379:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1380:                                          $remotesessions,
                   1381:                                          $defdomdefaults{'hostedsessions'});
                   1382:         }
1.1083    raeburn  1383:     }
                   1384:     return $canhost;
                   1385: }
                   1386: 
1.1123    raeburn  1387: sub this_host_spares {
                   1388:     my ($dom) = @_;
1.1126    raeburn  1389:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1390:     my @hosts = &current_machine_ids();
                   1391:     foreach my $lonhost (@hosts) {
                   1392:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1393:             $dom_in_use = $dom;
                   1394:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1395:             last;
                   1396:         }
                   1397:     }
1.1126    raeburn  1398:     if ($dom_in_use ne '') {
                   1399:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1400:     }
                   1401:     if (ref($result) ne 'HASH') {
                   1402:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1403:         $dom_in_use = &host_domain($lonhost_in_use);
                   1404:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1405:         if (ref($result) ne 'HASH') {
                   1406:             $result = \%spareid;
                   1407:         }
                   1408:     }
                   1409:     return $result;
                   1410: }
                   1411: 
                   1412: sub spares_for_offload  {
                   1413:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1414:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1415:     if (defined($cached)) {
                   1416:         return $result;
                   1417:     } else {
1.1126    raeburn  1418:         my $cachetime = 60*60*24;
                   1419:         my %domconfig =
                   1420:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1421:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1422:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1423:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1424:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1425:                 }
                   1426:             }
                   1427:         }
                   1428:     }
1.1126    raeburn  1429:     return;
1.1123    raeburn  1430: }
                   1431: 
1.1129    raeburn  1432: sub get_lonbalancer_config {
                   1433:     my ($servers) = @_;
                   1434:     my ($currbalancer,$currtargets);
                   1435:     if (ref($servers) eq 'HASH') {
                   1436:         foreach my $server (keys(%{$servers})) {
                   1437:             my %what = (
                   1438:                          spareid => 1,
                   1439:                          perlvar => 1,
                   1440:                        );
                   1441:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1442:             if ($result eq 'ok') {
                   1443:                 if (ref($returnhash) eq 'HASH') {
                   1444:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1445:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1446:                             $currbalancer = $server;
                   1447:                             $currtargets = {};
                   1448:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1449:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1450:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1451:                                 }
                   1452:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1453:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1454:                                 }
                   1455:                             }
                   1456:                             last;
                   1457:                         }
                   1458:                     }
                   1459:                 }
                   1460:             }
                   1461:         }
                   1462:     }
                   1463:     return ($currbalancer,$currtargets);
                   1464: }
                   1465: 
                   1466: sub check_loadbalancing {
1.1331    raeburn  1467:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1468:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1469:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1470:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1471:     my @hosts = &current_machine_ids();
1.1129    raeburn  1472:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1473:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1474:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1475:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1476:     my $domneedscache;
1.1129    raeburn  1477:     my $cachetime = 60*60*24;
                   1478: 
                   1479:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1480:         $dom_in_use = $udom;
                   1481:         $homeintdom = 1;
                   1482:     } else {
                   1483:         $dom_in_use = $serverhomedom;
                   1484:     }
                   1485:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1486:     unless (defined($cached)) {
                   1487:         my %domconfig =
                   1488:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1489:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1490:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1491:         } else {
                   1492:             $domneedscache = $dom_in_use;
1.1129    raeburn  1493:         }
                   1494:     }
                   1495:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1496:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1497:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1498:         if ($is_balancer) {
                   1499:             if (ref($currrules) eq 'HASH') {
                   1500:                 if ($homeintdom) {
                   1501:                     if ($uname ne '') {
                   1502:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1503:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1504:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1505:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1506:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1507:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1508:                             }
                   1509:                         }
                   1510:                         if ($rule_in_effect eq '') {
                   1511:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1512:                             if ($userenv{'inststatus'} ne '') {
                   1513:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1514:                                 my ($othertitle,$usertypes,$types) =
                   1515:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1516:                                 if (ref($types) eq 'ARRAY') {
                   1517:                                     foreach my $type (@{$types}) {
                   1518:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1519:                                             if (exists($currrules->{$type})) {
                   1520:                                                 $rule_in_effect = $currrules->{$type};
                   1521:                                             }
                   1522:                                         }
                   1523:                                     }
                   1524:                                 }
                   1525:                             } else {
                   1526:                                 if (exists($currrules->{'default'})) {
                   1527:                                     $rule_in_effect = $currrules->{'default'};
                   1528:                                 }
                   1529:                             }
                   1530:                         }
                   1531:                     } else {
                   1532:                         if (exists($currrules->{'default'})) {
                   1533:                             $rule_in_effect = $currrules->{'default'};
                   1534:                         }
                   1535:                     }
                   1536:                 } else {
                   1537:                     if ($currrules->{'_LC_external'} ne '') {
                   1538:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1539:                     }
                   1540:                 }
                   1541:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1542:                                                        $uname,$udom);
                   1543:             }
                   1544:         }
                   1545:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1546:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1547:         unless (defined($cached)) {
                   1548:             my %domconfig =
                   1549:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1550:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1551:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1552:             } else {
                   1553:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1554:             }
                   1555:         }
                   1556:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1557:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1558:                 &check_balancer_result($result,@hosts);
                   1559:             if ($is_balancer) {
1.1129    raeburn  1560:                 if (ref($currrules) eq 'HASH') {
                   1561:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1562:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1563:                     }
                   1564:                 }
                   1565:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1566:                                                        $uname,$udom);
                   1567:             }
                   1568:         } else {
                   1569:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1570:                 $is_balancer = 1;
                   1571:                 $offloadto = &this_host_spares($dom_in_use);
                   1572:             }
1.1307    raeburn  1573:             unless (defined($cached)) {
                   1574:                 $domneedscache = $serverhomedom;
                   1575:             }
1.1129    raeburn  1576:         }
                   1577:     } else {
                   1578:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1579:             $is_balancer = 1;
                   1580:             $offloadto = &this_host_spares($dom_in_use);
                   1581:         }
1.1307    raeburn  1582:         unless (defined($cached)) {
                   1583:             $domneedscache = $serverhomedom;
                   1584:         }
                   1585:     }
                   1586:     if ($domneedscache) {
                   1587:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1588:     }
1.1176    raeburn  1589:     if ($is_balancer) {
                   1590:         my $lowest_load = 30000;
                   1591:         if (ref($offloadto) eq 'HASH') {
                   1592:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1593:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1594:                     ($otherserver,$lowest_load) =
                   1595:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1596:                 }
1.1129    raeburn  1597:             }
1.1176    raeburn  1598:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1599: 
1.1176    raeburn  1600:             if (!$found_server) {
                   1601:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1602:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1603:                         ($otherserver,$lowest_load) =
                   1604:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1605:                     }
                   1606:                 }
                   1607:             }
                   1608:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1609:             if (@{$offloadto} == 1) {
                   1610:                 $otherserver = $offloadto->[0];
                   1611:             } elsif (@{$offloadto} > 1) {
                   1612:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1613:                     ($otherserver,$lowest_load) =
                   1614:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1615:                 }
                   1616:             }
                   1617:         }
1.1331    raeburn  1618:         unless ($caller eq 'login') {
                   1619:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1620:                 $is_balancer = 0;
                   1621:                 if ($uname ne '' && $udom ne '') {
                   1622:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1623:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1624:                                  'user.loadbalcheck.time' => time});
                   1625:                     }
1.1176    raeburn  1626:                 }
1.1129    raeburn  1627:             }
                   1628:         }
1.1389    raeburn  1629:         unless ($homeintdom) {
                   1630:             undef($setcookie);
                   1631:         }
1.1129    raeburn  1632:     }
1.1391    raeburn  1633:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1634: }
                   1635: 
1.1191    raeburn  1636: sub check_balancer_result {
                   1637:     my ($result,@hosts) = @_;
1.1391    raeburn  1638:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1639:     if (ref($result) eq 'HASH') {
                   1640:         if ($result->{'lonhost'} ne '') {
                   1641:             my $currbalancer = $result->{'lonhost'};
                   1642:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1643:                 $is_balancer = 1;
                   1644:                 $currtargets = $result->{'targets'};
                   1645:                 $currrules = $result->{'rules'};
1.1391    raeburn  1646:                 $dom_balancers = $currbalancer;
1.1191    raeburn  1647:             }
1.1391    raeburn  1648:             $dom_balancers = $currbalancer;
1.1191    raeburn  1649:         } else {
1.1391    raeburn  1650:             if (keys(%{$result})) {
                   1651:                 foreach my $key (keys(%{$result})) {
                   1652:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1653:                         (ref($result->{$key}) eq 'HASH')) {
                   1654:                         $is_balancer = 1;
                   1655:                         $currrules = $result->{$key}{'rules'};
                   1656:                         $currtargets = $result->{$key}{'targets'};
                   1657:                         $setcookie = $result->{$key}{'cookie'};
                   1658:                         last;
                   1659:                     }
1.1191    raeburn  1660:                 }
1.1391    raeburn  1661:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1662:             }
                   1663:         }
                   1664:     }
1.1391    raeburn  1665:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1666: }
                   1667: 
1.1129    raeburn  1668: sub get_loadbalancer_targets {
                   1669:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1670:     my $offloadto;
1.1175    raeburn  1671:     if ($rule_in_effect eq 'none') {
                   1672:         return [$perlvar{'lonHostID'}];
                   1673:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1674:         $offloadto = $currtargets;
                   1675:     } else {
                   1676:         if ($rule_in_effect eq 'homeserver') {
                   1677:             my $homeserver = &homeserver($uname,$udom);
                   1678:             if ($homeserver ne 'no_host') {
                   1679:                 $offloadto = [$homeserver];
                   1680:             }
                   1681:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1682:             my %domconfig =
                   1683:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1684:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1685:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1686:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1687:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1688:                     }
                   1689:                 }
                   1690:             } else {
1.1178    raeburn  1691:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1692:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1693:                 if (&hostname($remotebalancer) ne '') {
                   1694:                     $offloadto = [$remotebalancer];
                   1695:                 }
                   1696:             }
                   1697:         } elsif (&hostname($rule_in_effect) ne '') {
                   1698:             $offloadto = [$rule_in_effect];
                   1699:         }
                   1700:     }
                   1701:     return $offloadto;
                   1702: }
                   1703: 
1.1127    raeburn  1704: sub internet_dom_servers {
                   1705:     my ($dom) = @_;
                   1706:     my (%uniqservers,%servers);
                   1707:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1708:     my @machinedoms = &machine_domains($primaryserver);
                   1709:     foreach my $mdom (@machinedoms) {
                   1710:         my %currservers = %servers;
                   1711:         my %server = &get_servers($mdom);
                   1712:         %servers = (%currservers,%server);
                   1713:     }
                   1714:     my %by_hostname;
                   1715:     foreach my $id (keys(%servers)) {
                   1716:         push(@{$by_hostname{$servers{$id}}},$id);
                   1717:     }
                   1718:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1719:         if (@{$by_hostname{$hostname}} > 1) {
                   1720:             my $match = 0;
                   1721:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1722:                 if (&host_domain($id) eq $dom) {
                   1723:                     $uniqservers{$id} = $hostname;
                   1724:                     $match = 1;
                   1725:                 }
                   1726:             }
                   1727:             unless ($match) {
                   1728:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1729:             }
                   1730:         } else {
                   1731:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1732:         }
                   1733:     }
                   1734:     return %uniqservers;
                   1735: }
                   1736: 
1.1347    raeburn  1737: sub trusted_domains {
                   1738:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1739:     my ($trusted,$untrusted);
1.1347    raeburn  1740:     if (&domain($calldom) eq '') {
1.1349    raeburn  1741:         return ($trusted,$untrusted);
1.1347    raeburn  1742:     }
                   1743:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1744:         return ($trusted,$untrusted);
1.1347    raeburn  1745:     }
                   1746:     my $callprimary = &domain($calldom,'primary');
                   1747:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1748:     if ($intcalldom eq '') {
1.1349    raeburn  1749:         return ($trusted,$untrusted);
1.1347    raeburn  1750:     }
                   1751: 
                   1752:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1753:     unless (defined($cached)) {
                   1754:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1755:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1756:         $trustconfig = $domconfig{'trust'};
                   1757:     }
                   1758:     if (ref($trustconfig)) {
                   1759:         my (%possexc,%possinc,@allexc,@allinc); 
                   1760:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1761:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1762:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1763:             }
                   1764:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1765:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1766:             }
                   1767:         }
                   1768:         if (keys(%possexc)) {
                   1769:             if (keys(%possinc)) {
                   1770:                 foreach my $key (sort(keys(%possexc))) {
                   1771:                     next if ($key eq $intcalldom);
                   1772:                     unless ($possinc{$key}) {
                   1773:                         push(@allexc,$key);
                   1774:                     }
                   1775:                 }
                   1776:             } else {
                   1777:                 @allexc = sort(keys(%possexc));
                   1778:             }
                   1779:         }
                   1780:         if (keys(%possinc)) {
                   1781:             $possinc{$intcalldom} = 1;
                   1782:             @allinc = sort(keys(%possinc));
                   1783:         }
                   1784:         if ((@allexc > 0) || (@allinc > 0)) {
                   1785:             my %doms_by_intdom;
                   1786:             my %allintdoms = &all_host_intdom();
                   1787:             my %alldoms = &all_host_domain();
                   1788:             foreach my $key (%allintdoms) {
                   1789:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1790:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1791:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1792:                     }
                   1793:                 } else {
                   1794:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1795:                 }
                   1796:             }
                   1797:             foreach my $exc (@allexc) {
                   1798:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349    raeburn  1799:                     $untrusted = $doms_by_intdom{$exc};
1.1347    raeburn  1800:                 }
                   1801:             }
                   1802:             foreach my $inc (@allinc) {
                   1803:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349    raeburn  1804:                     $trusted = $doms_by_intdom{$inc};
1.1347    raeburn  1805:                 }
                   1806:             }
                   1807:         }
                   1808:     }
1.1349    raeburn  1809:     return ($trusted,$untrusted);
1.1347    raeburn  1810: }
                   1811: 
                   1812: sub will_trust {
                   1813:     my ($cmdtype,$domain,$possdom) = @_;
                   1814:     return 1 if ($domain eq $possdom);
                   1815:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1816:     my $willtrust; 
                   1817:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1818:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1819:             $willtrust = 1;
                   1820:         }
                   1821:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1822:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1823:             $willtrust = 1;
                   1824:         }
                   1825:     } else {
                   1826:         $willtrust = 1;
                   1827:     }
                   1828:     return $willtrust;
                   1829: }
                   1830: 
1.1       albertel 1831: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1832: 
1.599     albertel 1833: my %homecache;
1.1       albertel 1834: sub homeserver {
1.230     stredwic 1835:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1836:     my $index="$uname:$udom";
1.426     albertel 1837: 
1.599     albertel 1838:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1839: 
                   1840:     my %servers = &get_servers($udom,'library');
                   1841:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1842:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1843: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1844: 
                   1845: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1846: 	if ($answer eq 'found') {
                   1847: 	    delete($badServerCache{$tryserver}); 
                   1848: 	    return $homecache{$index}=$tryserver;
                   1849: 	} elsif ($answer eq 'no_host') {
                   1850: 	    $badServerCache{$tryserver}=1;
                   1851: 	}
1.1       albertel 1852:     }    
                   1853:     return 'no_host';
1.70      www      1854: }
                   1855: 
1.1300    raeburn  1856: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1857: 
                   1858: sub idget {
1.1300    raeburn  1859:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1860:     my %returnhash=();
1.1300    raeburn  1861:     my @ids=(); 
                   1862:     if (ref($idsref) eq 'ARRAY') {
                   1863:         @ids = @{$idsref};
                   1864:     } else {
                   1865:         return %returnhash; 
                   1866:     }
                   1867:     if ($namespace eq '') {
                   1868:         $namespace = 'ids';
                   1869:     }
1.70      www      1870:     
1.841     albertel 1871:     my %servers = &get_servers($udom,'library');
                   1872:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1873: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1874: 	if ($namespace eq 'ids') {
                   1875: 	    $idlist=~tr/A-Z/a-z/;
                   1876: 	}
                   1877: 	my $reply;
                   1878: 	if ($namespace eq 'ids') {
                   1879: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1880: 	} else {
                   1881: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1882: 	}
1.841     albertel 1883: 	my @answer=();
                   1884: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1885: 	    @answer=split(/\&/,$reply);
                   1886: 	}                    ;
                   1887: 	my $i;
                   1888: 	for ($i=0;$i<=$#ids;$i++) {
                   1889: 	    if ($answer[$i]) {
1.1299    raeburn  1890: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1891: 	    }
1.841     albertel 1892: 	}
1.1300    raeburn  1893:     }
1.70      www      1894:     return %returnhash;
                   1895: }
                   1896: 
                   1897: # ------------------------------------- Find the IDs behind a list of usernames
                   1898: 
                   1899: sub idrget {
                   1900:     my ($udom,@unames)=@_;
                   1901:     my %returnhash=();
1.800     albertel 1902:     foreach my $uname (@unames) {
                   1903:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1904:     }
1.70      www      1905:     return %returnhash;
                   1906: }
                   1907: 
1.1300    raeburn  1908: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1909: 
                   1910: sub idput {
1.1300    raeburn  1911:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1912:     my %servers=();
1.1300    raeburn  1913:     my %ids=();
                   1914:     my %byid = ();
                   1915:     if (ref($idsref) eq 'HASH') {
                   1916:         %ids=%{$idsref};
                   1917:     }
                   1918:     if ($namespace eq '') {
                   1919:         $namespace = 'ids'; 
                   1920:     }
1.800     albertel 1921:     foreach my $uname (keys(%ids)) {
                   1922: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1923:         if ($uhom eq '') {
                   1924:             $uhom=&homeserver($uname,$udom);
                   1925:         }
1.70      www      1926:         if ($uhom ne 'no_host') {
1.800     albertel 1927:             my $esc_unam=&escape($uname);
1.1300    raeburn  1928:             if ($namespace eq 'ids') {
                   1929:                 my $id=&escape($ids{$uname});
                   1930:                 $id=~tr/A-Z/a-z/;
                   1931:                 my $esc_unam=&escape($uname);
                   1932:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1933:             } else {
1.1300    raeburn  1934:                 my @currids = split(/,/,$ids{$uname});
                   1935:                 foreach my $id (@currids) {
                   1936:                     $byid{$uhom}{$id} .= $uname.',';
                   1937:                 }
                   1938:             }
                   1939:         }
                   1940:     }
                   1941:     if ($namespace eq 'clickers') {
                   1942:         foreach my $server (keys(%byid)) {
                   1943:             if (ref($byid{$server}) eq 'HASH') {
                   1944:                 foreach my $id (keys(%{$byid{$server}})) {
                   1945:                     $byid{$server} =~ s/,$//;
                   1946:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1947:                 }
1.70      www      1948:             }
                   1949:         }
1.191     harris41 1950:     }
1.800     albertel 1951:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1952:         $servers{$server} =~ s/\&$//;
                   1953:         if ($namespace eq 'ids') {     
                   1954:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1955:         } else {
                   1956:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1957:         }
1.191     harris41 1958:     }
1.344     www      1959: }
                   1960: 
1.1300    raeburn  1961: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1962: 
                   1963: sub iddel {
1.1300    raeburn  1964:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1965:     my %result=();
1.1300    raeburn  1966:     my %ids=();
                   1967:     my %byid = ();
                   1968:     if (ref($idshashref) eq 'HASH') {
                   1969:         %ids=%{$idshashref};
                   1970:     } else {
1.1231    raeburn  1971:         return %result;
                   1972:     }
1.1300    raeburn  1973:     if ($namespace eq '') {
                   1974:         $namespace = 'ids';
                   1975:     }
1.1231    raeburn  1976:     my %servers=();
1.1300    raeburn  1977:     while (my ($id,$unamestr) = each(%ids)) {
                   1978:         if ($namespace eq 'ids') {
                   1979:             my $uhom = $uhome;
                   1980:             if ($uhom eq '') { 
                   1981:                 $uhom=&homeserver($unamestr,$udom);
                   1982:             }
                   1983:             if ($uhom ne 'no_host') {
                   1984:                 $servers{$uhom}.='&'.&escape($id);
                   1985:             }
                   1986:          } else {
                   1987:             my @curritems = split(/,/,$ids{$id});
                   1988:             foreach my $uname (@curritems) {
                   1989:                 my $uhom = $uhome;
                   1990:                 if ($uhom eq '') {
                   1991:                     $uhom=&homeserver($uname,$udom);
                   1992:                 }
                   1993:                 if ($uhom ne 'no_host') { 
                   1994:                     $byid{$uhom}{$id} .= $uname.',';
                   1995:                 }
                   1996:             }
1.1231    raeburn  1997:         }
1.1300    raeburn  1998:     }
                   1999:     if ($namespace eq 'clickers') {
                   2000:         foreach my $server (keys(%byid)) {
                   2001:             if (ref($byid{$server}) eq 'HASH') {
                   2002:                 foreach my $id (keys(%{$byid{$server}})) {
                   2003:                     $byid{$server}{$id} =~ s/,$//;
                   2004:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2005:                 }
1.1231    raeburn  2006:             }
                   2007:         }
                   2008:     }
                   2009:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2010:         $servers{$server} =~ s/\&$//;
                   2011:         if ($namespace eq 'ids') {
                   2012:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2013:         } elsif ($namespace eq 'clickers') {
                   2014:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2015:         }
1.1231    raeburn  2016:     }
                   2017:     return %result;
                   2018: }
                   2019: 
1.1300    raeburn  2020: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2021: 
                   2022: sub updateclickers {
                   2023:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2024:     my %clickers;
                   2025:     if (ref($idshashref) eq 'HASH') {
                   2026:         %clickers=%{$idshashref};
                   2027:     } else {
                   2028:         return;
                   2029:     }
                   2030:     my $items='';
                   2031:     foreach my $item (keys(%clickers)) {
                   2032:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2033:     }
                   2034:     $items=~s/\&$//;
                   2035:     my $request = "updateclickers:$udom:$action:$items";
                   2036:     if ($critical) {
                   2037:         return &critical($request,$uhome);
                   2038:     } else {
                   2039:         return &reply($request,$uhome);
                   2040:     }
                   2041: }
                   2042: 
1.1023    raeburn  2043: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2044: sub dump_dom {
1.1165    droeschl 2045:     my ($namespace, $udom, $regexp) = @_;
                   2046: 
                   2047:     $udom ||= $env{'user.domain'};
                   2048: 
                   2049:     return () unless $udom;
                   2050: 
                   2051:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2052: }
                   2053: 
1.1023    raeburn  2054: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2055: 
                   2056: sub get_dom {
1.860     raeburn  2057:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2058:     return if ($udom eq 'public');
1.806     raeburn  2059:     my $items='';
                   2060:     foreach my $item (@$storearr) {
                   2061:         $items.=&escape($item).'&';
                   2062:     }
                   2063:     $items=~s/\&$//;
1.860     raeburn  2064:     if (!$udom) {
                   2065:         $udom=$env{'user.domain'};
1.1267    raeburn  2066:         return if ($udom eq 'public');
1.860     raeburn  2067:         if (defined(&domain($udom,'primary'))) {
                   2068:             $uhome=&domain($udom,'primary');
                   2069:         } else {
1.874     albertel 2070:             undef($uhome);
1.860     raeburn  2071:         }
                   2072:     } else {
                   2073:         if (!$uhome) {
                   2074:             if (defined(&domain($udom,'primary'))) {
                   2075:                 $uhome=&domain($udom,'primary');
                   2076:             }
                   2077:         }
                   2078:     }
                   2079:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2080:         my $rep;
                   2081:         if ($namespace =~ /^enc/) {
                   2082:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2083:         } else {
                   2084:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2085:         }
1.866     raeburn  2086:         my %returnhash;
1.875     albertel 2087:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2088:             return %returnhash;
                   2089:         }
1.806     raeburn  2090:         my @pairs=split(/\&/,$rep);
                   2091:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2092:             return @pairs;
                   2093:         }
                   2094:         my $i=0;
                   2095:         foreach my $item (@$storearr) {
                   2096:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2097:             $i++;
                   2098:         }
                   2099:         return %returnhash;
                   2100:     } else {
1.880     banghart 2101:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2102:     }
                   2103: }
                   2104: 
                   2105: # -------------------------------------------- put items in domain db files 
                   2106: 
                   2107: sub put_dom {
1.860     raeburn  2108:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2109:     if (!$udom) {
                   2110:         $udom=$env{'user.domain'};
                   2111:         if (defined(&domain($udom,'primary'))) {
                   2112:             $uhome=&domain($udom,'primary');
                   2113:         } else {
1.874     albertel 2114:             undef($uhome);
1.860     raeburn  2115:         }
                   2116:     } else {
                   2117:         if (!$uhome) {
                   2118:             if (defined(&domain($udom,'primary'))) {
                   2119:                 $uhome=&domain($udom,'primary');
                   2120:             }
                   2121:         }
                   2122:     } 
                   2123:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2124:         my $items='';
                   2125:         foreach my $item (keys(%$storehash)) {
                   2126:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2127:         }
                   2128:         $items=~s/\&$//;
1.1344    raeburn  2129:         if ($namespace =~ /^enc/) {
                   2130:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2131:         } else {
                   2132:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2133:         }
1.806     raeburn  2134:     } else {
1.860     raeburn  2135:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2136:     }
                   2137: }
                   2138: 
1.1023    raeburn  2139: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2140: sub newput_dom {
1.1023    raeburn  2141:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2142:     my $result;
                   2143:     if (!$udom) {
                   2144:         $udom=$env{'user.domain'};
                   2145:     }
1.1023    raeburn  2146:     if ($udom) {
                   2147:         my $uname = &get_domainconfiguser($udom);
                   2148:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2149:     }
                   2150:     return $result;
                   2151: }
                   2152: 
1.1023    raeburn  2153: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2154: sub del_dom {
1.1023    raeburn  2155:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2156:     if (ref($storearr) eq 'ARRAY') {
                   2157:         if (!$udom) {
                   2158:             $udom=$env{'user.domain'};
                   2159:         }
1.1023    raeburn  2160:         if ($udom) {
                   2161:             my $uname = &get_domainconfiguser($udom); 
                   2162:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2163:         }
                   2164:     }
                   2165: }
                   2166: 
1.1023    raeburn  2167: # ----------------------------------construct domainconfig user for a domain 
                   2168: sub get_domainconfiguser {
                   2169:     my ($udom) = @_;
                   2170:     return $udom.'-domainconfig';
                   2171: }
                   2172: 
1.837     raeburn  2173: sub retrieve_inst_usertypes {
                   2174:     my ($udom) = @_;
                   2175:     my (%returnhash,@order);
1.989     raeburn  2176:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2177:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2178:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2179:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2180:     } else {
                   2181:         if (defined(&domain($udom,'primary'))) {
                   2182:             my $uhome=&domain($udom,'primary');
                   2183:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2184:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2185:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2186:                 return (\%returnhash,\@order);
                   2187:             }
                   2188:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2189:             my @pairs=split(/\&/,$hashitems);
                   2190:             foreach my $item (@pairs) {
                   2191:                 my ($key,$value)=split(/=/,$item,2);
                   2192:                 $key = &unescape($key);
                   2193:                 next if ($key =~ /^error: 2 /);
                   2194:                 $returnhash{$key}=&thaw_unescape($value);
                   2195:             }
                   2196:             my @esc_order = split(/\&/,$orderitems);
                   2197:             foreach my $item (@esc_order) {
                   2198:                 push(@order,&unescape($item));
                   2199:             }
                   2200:         } else {
1.1256    raeburn  2201:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2202:         }
1.1256    raeburn  2203:         return (\%returnhash,\@order);
1.837     raeburn  2204:     }
                   2205: }
                   2206: 
1.868     raeburn  2207: sub is_domainimage {
                   2208:     my ($url) = @_;
1.1306    raeburn  2209:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2210:         if (&domain($1) ne '') {
                   2211:             return '1';
                   2212:         }
                   2213:     }
                   2214:     return;
                   2215: }
                   2216: 
1.899     raeburn  2217: sub inst_directory_query {
                   2218:     my ($srch) = @_;
                   2219:     my $udom = $srch->{'srchdomain'};
                   2220:     my %results;
                   2221:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2222:     my $outcome;
1.899     raeburn  2223:     if ($homeserver ne '') {
1.1357    raeburn  2224:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2225:             if ($srch->{'srchby'} eq 'email') {
                   2226:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2227:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2228:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2229:                     (($major == 2) && ($minor < 12))) {
                   2230:                     return;
                   2231:                 }
                   2232:             }
                   2233:         }
1.904     albertel 2234: 	my $queryid=&reply("querysend:instdirsearch:".
                   2235: 			   &escape($srch->{'srchby'}).':'.
                   2236: 			   &escape($srch->{'srchterm'}).':'.
                   2237: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2238: 	my $host=&hostname($homeserver);
                   2239: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2240: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2241: 	    return;
                   2242: 	}
                   2243: 	my $response = &get_query_reply($queryid);
                   2244: 	my $maxtries = 5;
                   2245: 	my $tries = 1;
                   2246: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2247: 	    $response = &get_query_reply($queryid);
                   2248: 	    $tries ++;
                   2249: 	}
                   2250: 
                   2251:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2252:             if ($response eq 'unavailable') {
                   2253:                 $outcome = $response;
                   2254:             } else {
                   2255:                 $outcome = 'ok';
                   2256:                 my @matches = split(/\n/,$response);
                   2257:                 foreach my $match (@matches) {
                   2258:                     my ($key,$value) = split(/=/,$match);
                   2259:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2260:                 }
1.899     raeburn  2261:             }
                   2262:         }
                   2263:     }
1.909     raeburn  2264:     return ($outcome,%results);
1.899     raeburn  2265: }
                   2266: 
                   2267: sub usersearch {
                   2268:     my ($srch) = @_;
                   2269:     my $dom = $srch->{'srchdomain'};
                   2270:     my %results;
                   2271:     my %libserv = &all_library();
                   2272:     my $query = 'usersearch';
                   2273:     foreach my $tryserver (keys(%libserv)) {
                   2274:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2275:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2276:                 if ($srch->{'srchby'} eq 'email') {
                   2277:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2278:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2279:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2280:                              (($major == 2) && ($minor < 12)));
                   2281:                 }
                   2282:             }
1.899     raeburn  2283:             my $host=&hostname($tryserver);
                   2284:             my $queryid=
1.911     raeburn  2285:                 &reply("querysend:".&escape($query).':'.
                   2286:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2287:                        &escape($srch->{'srchtype'}).':'.
                   2288:                        &escape($srch->{'srchterm'}),$tryserver);
                   2289:             if ($queryid !~/^\Q$host\E\_/) {
                   2290:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2291:                 next;
1.899     raeburn  2292:             }
                   2293:             my $reply = &get_query_reply($queryid);
                   2294:             my $maxtries = 1;
                   2295:             my $tries = 1;
                   2296:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2297:                 $reply = &get_query_reply($queryid);
                   2298:                 $tries ++;
                   2299:             }
                   2300:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2301:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2302:             } else {
1.911     raeburn  2303:                 my @matches;
                   2304:                 if ($reply =~ /\n/) {
                   2305:                     @matches = split(/\n/,$reply);
                   2306:                 } else {
                   2307:                     @matches = split(/\&/,$reply);
                   2308:                 }
1.899     raeburn  2309:                 foreach my $match (@matches) {
                   2310:                     my ($uname,$udom,%userhash);
1.911     raeburn  2311:                     foreach my $entry (split(/:/,$match)) {
                   2312:                         my ($key,$value) =
                   2313:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2314:                         $userhash{$key} = $value;
                   2315:                         if ($key eq 'username') {
                   2316:                             $uname = $value;
                   2317:                         } elsif ($key eq 'domain') {
                   2318:                             $udom = $value;
1.911     raeburn  2319:                         }
1.899     raeburn  2320:                     }
                   2321:                     $results{$uname.':'.$udom} = \%userhash;
                   2322:                 }
                   2323:             }
                   2324:         }
                   2325:     }
                   2326:     return %results;
                   2327: }
                   2328: 
1.912     raeburn  2329: sub get_instuser {
                   2330:     my ($udom,$uname,$id) = @_;
                   2331:     my $homeserver = &domain($udom,'primary');
                   2332:     my ($outcome,%results);
                   2333:     if ($homeserver ne '') {
                   2334:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2335:                            &escape($id).':'.&escape($udom),$homeserver);
                   2336:         my $host=&hostname($homeserver);
                   2337:         if ($queryid !~/^\Q$host\E\_/) {
                   2338:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2339:             return;
                   2340:         }
                   2341:         my $response = &get_query_reply($queryid);
                   2342:         my $maxtries = 5;
                   2343:         my $tries = 1;
                   2344:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2345:             $response = &get_query_reply($queryid);
                   2346:             $tries ++;
                   2347:         }
                   2348:         if (!&error($response) && $response ne 'refused') {
                   2349:             if ($response eq 'unavailable') {
                   2350:                 $outcome = $response;
                   2351:             } else {
                   2352:                 $outcome = 'ok';
                   2353:                 my @matches = split(/\n/,$response);
                   2354:                 foreach my $match (@matches) {
                   2355:                     my ($key,$value) = split(/=/,$match);
                   2356:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2357:                 }
                   2358:             }
                   2359:         }
                   2360:     }
                   2361:     my %userinfo;
                   2362:     if (ref($results{$uname}) eq 'HASH') {
                   2363:         %userinfo = %{$results{$uname}};
                   2364:     } 
                   2365:     return ($outcome,%userinfo);
                   2366: }
                   2367: 
1.1290    raeburn  2368: sub get_multiple_instusers {
                   2369:     my ($udom,$users,$caller) = @_;
                   2370:     my ($outcome,$results);
                   2371:     if (ref($users) eq 'HASH') {
                   2372:         my $count = keys(%{$users}); 
                   2373:         my $requested = &freeze_escape($users);
                   2374:         my $homeserver = &domain($udom,'primary');
                   2375:         if ($homeserver ne '') {
                   2376:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2377:             my $host=&hostname($homeserver);
                   2378:             if ($queryid !~/^\Q$host\E\_/) {
                   2379:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2380:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2381:                 return ($outcome,$results);
                   2382:             }
                   2383:             my $response = &get_query_reply($queryid);
                   2384:             my $maxtries = 5;
                   2385:             if ($count > 100) {
                   2386:                 $maxtries = 1+int($count/20);
                   2387:             }
                   2388:             my $tries = 1;
                   2389:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2390:                 $response = &get_query_reply($queryid);
                   2391:                 $tries ++;
                   2392:             }
                   2393:             if ($response eq '') {
                   2394:                 $results = {};
                   2395:                 foreach my $key (keys(%{$users})) {
                   2396:                     my ($uname,$id);
                   2397:                     if ($caller eq 'id') {
                   2398:                         $id = $key;
                   2399:                     } else {
                   2400:                         $uname = $key;
                   2401:                     }
                   2402:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2403:                     $outcome = $resp;
1.1290    raeburn  2404:                     if ($resp eq 'ok') {
                   2405:                         %{$results} = (%{$results}, %info);
                   2406:                     } else {
                   2407:                         last;
                   2408:                     }
                   2409:                 }
                   2410:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2411:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2412:                     $outcome = $response;
                   2413:                 } else {
1.1291    raeburn  2414:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2415:                     if ($outcome eq 'ok') {
                   2416:                         $results = &thaw_unescape($userdata); 
                   2417:                     }
                   2418:                 }
                   2419:             }
                   2420:         }
                   2421:     }
                   2422:     return ($outcome,$results);
                   2423: }
                   2424: 
1.912     raeburn  2425: sub inst_rulecheck {
1.923     raeburn  2426:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2427:     my %returnhash;
                   2428:     if ($udom ne '') {
                   2429:         if (ref($rules) eq 'ARRAY') {
                   2430:             @{$rules} = map {&escape($_);} (@{$rules});
                   2431:             my $rulestr = join(':',@{$rules});
                   2432:             my $homeserver=&domain($udom,'primary');
                   2433:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2434:                 my $response;
                   2435:                 if ($item eq 'username') {                
                   2436:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2437:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2438:                                               $homeserver));
1.923     raeburn  2439:                 } elsif ($item eq 'id') {
                   2440:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2441:                                               ':'.&escape($id).':'.$rulestr,
                   2442:                                               $homeserver));
1.945     raeburn  2443:                 } elsif ($item eq 'selfcreate') {
                   2444:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2445:                                                &escape($udom).':'.&escape($uname).
                   2446:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2447:                 }
1.912     raeburn  2448:                 if ($response ne 'refused') {
                   2449:                     my @pairs=split(/\&/,$response);
                   2450:                     foreach my $item (@pairs) {
                   2451:                         my ($key,$value)=split(/=/,$item,2);
                   2452:                         $key = &unescape($key);
                   2453:                         next if ($key =~ /^error: 2 /);
                   2454:                         $returnhash{$key}=&thaw_unescape($value);
                   2455:                     }
                   2456:                 }
                   2457:             }
                   2458:         }
                   2459:     }
                   2460:     return %returnhash;
                   2461: }
                   2462: 
                   2463: sub inst_userrules {
1.923     raeburn  2464:     my ($udom,$check) = @_;
1.912     raeburn  2465:     my (%ruleshash,@ruleorder);
                   2466:     if ($udom ne '') {
                   2467:         my $homeserver=&domain($udom,'primary');
                   2468:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2469:             my $response;
                   2470:             if ($check eq 'id') {
                   2471:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2472:                                  $homeserver);
1.943     raeburn  2473:             } elsif ($check eq 'email') {
                   2474:                 $response=&reply('instemailrules:'.&escape($udom),
                   2475:                                  $homeserver);
1.923     raeburn  2476:             } else {
                   2477:                 $response=&reply('instuserrules:'.&escape($udom),
                   2478:                                  $homeserver);
                   2479:             }
1.912     raeburn  2480:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2481:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2482:                 ($response ne 'no_such_host')) {
                   2483:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2484:                 my @pairs=split(/\&/,$hashitems);
                   2485:                 foreach my $item (@pairs) {
                   2486:                     my ($key,$value)=split(/=/,$item,2);
                   2487:                     $key = &unescape($key);
                   2488:                     next if ($key =~ /^error: 2 /);
                   2489:                     $ruleshash{$key}=&thaw_unescape($value);
                   2490:                 }
                   2491:                 my @esc_order = split(/\&/,$orderitems);
                   2492:                 foreach my $item (@esc_order) {
                   2493:                     push(@ruleorder,&unescape($item));
                   2494:                 }
                   2495:             }
                   2496:         }
                   2497:     }
                   2498:     return (\%ruleshash,\@ruleorder);
                   2499: }
                   2500: 
1.976     raeburn  2501: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2502: 
                   2503: sub get_domain_defaults {
1.1240    raeburn  2504:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2505:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2506:     my $cachetime = 60*60*24;
1.1240    raeburn  2507:     unless ($ignore_cache) {
                   2508:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2509:         if (defined($cached)) {
                   2510:             if (ref($result) eq 'HASH') {
                   2511:                 return %{$result};
                   2512:             }
1.943     raeburn  2513:         }
                   2514:     }
                   2515:     my %domdefaults;
                   2516:     my %domconfig =
1.989     raeburn  2517:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2518:                                   'requestcourses','inststatus',
1.1183    raeburn  2519:                                   'coursedefaults','usersessions',
1.1258    raeburn  2520:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2521:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2522:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2523:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2524:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2525:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2526:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2527:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2528:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2529:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2530:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2531:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2532:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2533:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2534:     } else {
                   2535:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2536:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2537:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2538:     }
1.976     raeburn  2539:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2540:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2541:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2542:         } else {
                   2543:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2544:         }
1.1177    raeburn  2545:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2546:         foreach my $item (@usertools) {
                   2547:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2548:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2549:             }
                   2550:         }
1.1229    raeburn  2551:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2552:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2553:         }
1.976     raeburn  2554:     }
1.985     raeburn  2555:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2556:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2557:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2558:         }
                   2559:     }
1.1183    raeburn  2560:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2561:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2562:     }
1.989     raeburn  2563:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2564:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2565:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2566:         }
                   2567:     }
1.1047    raeburn  2568:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2569:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2570:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2571:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2572:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2573:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2574:         }
1.1254    raeburn  2575:         foreach my $type (@coursetypes) {
                   2576:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2577:                 unless ($type eq 'community') {
                   2578:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2579:                 }
                   2580:             }
                   2581:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2582:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2583:             }
1.1277    raeburn  2584:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2585:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2586:                     $domdefaults{$type.'postsubtimeout'} = 
                   2587:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2588:                 }
                   2589:             }
1.1230    raeburn  2590:         }
1.1286    raeburn  2591:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2592:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2593:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2594:                 if (@clonecodes) {
                   2595:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2596:                 }
                   2597:             }
                   2598:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2599:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2600:         }
1.1356    raeburn  2601:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2602:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2603:         } 
1.1047    raeburn  2604:     }
1.1073    raeburn  2605:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2606:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2607:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2608:         }
                   2609:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2610:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2611:         }
1.1279    raeburn  2612:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2613:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2614:         }
1.1073    raeburn  2615:     }
1.1254    raeburn  2616:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2617:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2618:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2619:                             'approval','limit');
                   2620:             foreach my $type (@coursetypes) {
                   2621:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2622:                     my @mgrdc = ();
                   2623:                     foreach my $item (@settings) {
                   2624:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2625:                             push(@mgrdc,$item);
                   2626:                         }
                   2627:                     }
                   2628:                     if (@mgrdc) {
                   2629:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2630:                     }
                   2631:                 }
                   2632:             }
                   2633:         }
                   2634:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2635:             foreach my $type (@coursetypes) {
                   2636:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2637:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2638:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2639:                     }
                   2640:                 }
                   2641:             }
                   2642:         }
                   2643:     }
1.1258    raeburn  2644:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2645:         $domdefaults{'catauth'} = 'std';
                   2646:         $domdefaults{'catunauth'} = 'std';
                   2647:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2648:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2649:         }
                   2650:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2651:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2652:         }
                   2653:     }
1.1315    raeburn  2654:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2655:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2656:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2657:         }
1.1338    raeburn  2658:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2659:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2660:         }
                   2661:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2662:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2663:         }
                   2664:     }
1.1320    raeburn  2665:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2666:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2667:         foreach my $prefix (@prefixes) {
                   2668:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2669:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2670:             }
                   2671:         }
                   2672:     }
1.1314    raeburn  2673:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2674:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2675:     }
1.1332    raeburn  2676:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2677:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2678:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2679:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2680:         }
                   2681:     }
1.1219    raeburn  2682:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2683:     return %domdefaults;
                   2684: }
                   2685: 
1.1311    raeburn  2686: sub course_portal_url {
                   2687:     my ($cnum,$cdom) = @_;
                   2688:     my $chome = &homeserver($cnum,$cdom);
                   2689:     my $hostname = &hostname($chome);
                   2690:     my $protocol = $protocol{$chome};
                   2691:     $protocol = 'http' if ($protocol ne 'https');
                   2692:     my %domdefaults = &get_domain_defaults($cdom);
                   2693:     my $firsturl;
                   2694:     if ($domdefaults{'portal_def'}) {
                   2695:         $firsturl = $domdefaults{'portal_def'};
                   2696:     } else {
                   2697:         $firsturl = $protocol.'://'.$hostname;
                   2698:     }
                   2699:     return $firsturl;
                   2700: }
                   2701: 
1.344     www      2702: # --------------------------------------------------- Assign a key to a student
                   2703: 
                   2704: sub assign_access_key {
1.364     www      2705: #
                   2706: # a valid key looks like uname:udom#comments
                   2707: # comments are being appended
                   2708: #
1.498     www      2709:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2710:     $kdom=
1.620     albertel 2711:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2712:     $knum=
1.620     albertel 2713:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2714:     $cdom=
1.620     albertel 2715:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2716:     $cnum=
1.620     albertel 2717:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2718:     $udom=$env{'user.name'} unless (defined($udom));
                   2719:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2720:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2721:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2722:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2723:                                                   # assigned to this person
                   2724:                                                   # - this should not happen,
1.345     www      2725:                                                   # unless something went wrong
                   2726:                                                   # the first time around
                   2727: # ready to assign
1.364     www      2728:         $logentry=$1.'; '.$logentry;
1.496     www      2729:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2730:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2731: # key now belongs to user
1.346     www      2732: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2733:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2734:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2735:                 return 'ok';
                   2736:             } else {
                   2737:                 return 
                   2738:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2739: 	    }
                   2740:         } else {
                   2741:             return 'error: Could not assign key, try again later.';
                   2742:         }
1.364     www      2743:     } elsif (!$existing{$ckey}) {
1.345     www      2744: # the key does not exist
                   2745: 	return 'error: The key does not exist';
                   2746:     } else {
                   2747: # the key is somebody else's
                   2748: 	return 'error: The key is already in use';
                   2749:     }
1.344     www      2750: }
                   2751: 
1.364     www      2752: # ------------------------------------------ put an additional comment on a key
                   2753: 
                   2754: sub comment_access_key {
                   2755: #
                   2756: # a valid key looks like uname:udom#comments
                   2757: # comments are being appended
                   2758: #
                   2759:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2760:     $cdom=
1.620     albertel 2761:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2762:     $cnum=
1.620     albertel 2763:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2764:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2765:     if ($existing{$ckey}) {
                   2766:         $existing{$ckey}.='; '.$logentry;
                   2767: # ready to assign
1.367     www      2768:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2769:                                                  $cdom,$cnum) eq 'ok') {
                   2770: 	    return 'ok';
                   2771:         } else {
                   2772: 	    return 'error: Count not store comment.';
                   2773:         }
                   2774:     } else {
                   2775: # the key does not exist
                   2776: 	return 'error: The key does not exist';
                   2777:     }
                   2778: }
                   2779: 
1.344     www      2780: # ------------------------------------------------------ Generate a set of keys
                   2781: 
                   2782: sub generate_access_keys {
1.364     www      2783:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2784:     $cdom=
1.620     albertel 2785:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2786:     $cnum=
1.620     albertel 2787:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2788:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2789:     unless (($cdom) && ($cnum)) { return 0; }
                   2790:     if ($number>10000) { return 0; }
                   2791:     sleep(2); # make sure don't get same seed twice
                   2792:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2793:     my $total=0;
                   2794:     for (my $i=1;$i<=$number;$i++) {
                   2795:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2796:                   sprintf("%lx",int(100000*rand)).'-'.
                   2797:                   sprintf("%lx",int(100000*rand));
                   2798:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2799:        $newkey=~s/0/h/g; # and also 0 and O
                   2800:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2801:        if ($existing{$newkey}) {
                   2802:            $i--;
                   2803:        } else {
1.364     www      2804: 	  if (&put('accesskeys',
                   2805:               { $newkey => '# generated '.localtime().
1.620     albertel 2806:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2807:                            '; '.$logentry },
                   2808: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2809:               $total++;
                   2810: 	  }
                   2811:        }
                   2812:     }
1.620     albertel 2813:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2814:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2815:     return $total;
                   2816: }
                   2817: 
                   2818: # ------------------------------------------------------- Validate an accesskey
                   2819: 
                   2820: sub validate_access_key {
                   2821:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2822:     $cdom=
1.620     albertel 2823:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2824:     $cnum=
1.620     albertel 2825:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2826:     $udom=$env{'user.domain'} unless (defined($udom));
                   2827:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2828:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2829:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2830: }
                   2831: 
                   2832: # ------------------------------------- Find the section of student in a course
1.652     albertel 2833: sub devalidate_getsection_cache {
                   2834:     my ($udom,$unam,$courseid)=@_;
                   2835:     my $hashid="$udom:$unam:$courseid";
                   2836:     &devalidate_cache_new('getsection',$hashid);
                   2837: }
1.298     matthew  2838: 
1.815     albertel 2839: sub courseid_to_courseurl {
                   2840:     my ($courseid) = @_;
                   2841:     #already url style courseid
                   2842:     return $courseid if ($courseid =~ m{^/});
                   2843: 
                   2844:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2845: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2846: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2847: 	return "/$cdom/$cnum";
                   2848:     }
                   2849: 
                   2850:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2851:     if (exists($courseinfo{'num'})) {
                   2852: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2853:     }
                   2854: 
                   2855:     return undef;
                   2856: }
                   2857: 
1.298     matthew  2858: sub getsection {
                   2859:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2860:     my $cachetime=1800;
1.551     albertel 2861: 
                   2862:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2863:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2864:     if (defined($cached)) { return $result; }
                   2865: 
1.298     matthew  2866:     my %Pending; 
                   2867:     my %Expired;
                   2868:     #
                   2869:     # Each role can either have not started yet (pending), be active, 
                   2870:     #    or have expired.
                   2871:     #
                   2872:     # If there is an active role, we are done.
                   2873:     #
                   2874:     # If there is more than one role which has not started yet, 
                   2875:     #     choose the one which will start sooner
                   2876:     # If there is one role which has not started yet, return it.
                   2877:     #
                   2878:     # If there is more than one expired role, choose the one which ended last.
                   2879:     # If there is a role which has expired, return it.
                   2880:     #
1.815     albertel 2881:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2882:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2883:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2884:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2885:         my $section=$1;
                   2886:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2887:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2888:         my $now=time;
1.548     albertel 2889:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2890:             $Expired{$end}=$section;
                   2891:             next;
                   2892:         }
1.548     albertel 2893:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2894:             $Pending{$start}=$section;
                   2895:             next;
                   2896:         }
1.599     albertel 2897:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2898:     }
                   2899:     #
                   2900:     # Presumedly there will be few matching roles from the above
                   2901:     # loop and the sorting time will be negligible.
                   2902:     if (scalar(keys(%Pending))) {
                   2903:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2904:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2905:     } 
                   2906:     if (scalar(keys(%Expired))) {
                   2907:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2908:         my $time = pop(@sorted);
1.599     albertel 2909:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2910:     }
1.599     albertel 2911:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2912: }
1.70      www      2913: 
1.599     albertel 2914: sub save_cache {
                   2915:     &purge_remembered();
1.722     albertel 2916:     #&Apache::loncommon::validate_page();
1.620     albertel 2917:     undef(%env);
1.780     albertel 2918:     undef($env_loaded);
1.599     albertel 2919: }
1.452     albertel 2920: 
1.599     albertel 2921: my $to_remember=-1;
                   2922: my %remembered;
                   2923: my %accessed;
                   2924: my $kicks=0;
                   2925: my $hits=0;
1.849     albertel 2926: sub make_key {
                   2927:     my ($name,$id) = @_;
1.872     albertel 2928:     if (length($id) > 65 
                   2929: 	&& length(&escape($id)) > 200) {
                   2930: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2931:     }
1.849     albertel 2932:     return &escape($name.':'.$id);
                   2933: }
                   2934: 
1.599     albertel 2935: sub devalidate_cache_new {
                   2936:     my ($name,$id,$debug) = @_;
                   2937:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2938:     my $remembered_id=$name.':'.$id;
1.849     albertel 2939:     $id=&make_key($name,$id);
1.599     albertel 2940:     $memcache->delete($id);
1.1319    damieng  2941:     delete($remembered{$remembered_id});
                   2942:     delete($accessed{$remembered_id});
1.599     albertel 2943: }
                   2944: 
                   2945: sub is_cached_new {
                   2946:     my ($name,$id,$debug) = @_;
1.1319    damieng  2947:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2948:     if (exists($remembered{$remembered_id})) {
                   2949: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2950: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2951: 	$hits++;
1.1319    damieng  2952: 	return ($remembered{$remembered_id},1);
1.599     albertel 2953:     }
1.1319    damieng  2954:     $id=&make_key($name,$id);
1.599     albertel 2955:     my $value = $memcache->get($id);
                   2956:     if (!(defined($value))) {
                   2957: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2958: 	return (undef,undef);
1.416     albertel 2959:     }
1.599     albertel 2960:     if ($value eq '__undef__') {
                   2961: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2962: 	$value=undef;
                   2963:     }
1.1319    damieng  2964:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2965:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2966:     return ($value,1);
                   2967: }
                   2968: 
                   2969: sub do_cache_new {
                   2970:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2971:     my $remembered_id=$name.':'.$id;
1.849     albertel 2972:     $id=&make_key($name,$id);
1.599     albertel 2973:     my $setvalue=$value;
                   2974:     if (!defined($setvalue)) {
                   2975: 	$setvalue='__undef__';
                   2976:     }
1.623     albertel 2977:     if (!defined($time) ) {
                   2978: 	$time=600;
                   2979:     }
1.599     albertel 2980:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2981:     my $result = $memcache->set($id,$setvalue,$time);
                   2982:     if (! $result) {
1.872     albertel 2983: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2984: 	$memcache->disconnect_all();
1.872     albertel 2985:     }
1.600     albertel 2986:     # need to make a copy of $value
1.1319    damieng  2987:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2988:     return $value;
                   2989: }
                   2990: 
                   2991: sub make_room {
1.1319    damieng  2992:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2993: 
1.1319    damieng  2994:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2995:                                     : $value;
1.599     albertel 2996:     if ($to_remember<0) { return; }
1.1319    damieng  2997:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2998:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2999:     my $to_kick;
                   3000:     my $max_time=0;
                   3001:     foreach my $other (keys(%accessed)) {
                   3002: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3003: 	    $to_kick=$other;
                   3004: 	    $max_time=&tv_interval($accessed{$other});
                   3005: 	}
                   3006:     }
                   3007:     delete($remembered{$to_kick});
                   3008:     delete($accessed{$to_kick});
                   3009:     $kicks++;
                   3010:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3011:     return;
                   3012: }
                   3013: 
1.599     albertel 3014: sub purge_remembered {
1.604     albertel 3015:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3016:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3017:     undef(%remembered);
                   3018:     undef(%accessed);
1.428     albertel 3019: }
1.70      www      3020: # ------------------------------------- Read an entry from a user's environment
                   3021: 
                   3022: sub userenvironment {
                   3023:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3024:     my $items;
                   3025:     foreach my $item (@what) {
                   3026:         $items.=&escape($item).'&';
                   3027:     }
                   3028:     $items=~s/\&$//;
1.70      www      3029:     my %returnhash=();
1.1009    raeburn  3030:     my $uhome = &homeserver($unam,$udom);
                   3031:     unless ($uhome eq 'no_host') {
                   3032:         my @answer=split(/\&/, 
                   3033:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3034:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3035:             return %returnhash;
                   3036:         }
1.1009    raeburn  3037:         my $i;
                   3038:         for ($i=0;$i<=$#what;$i++) {
                   3039: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3040:         }
1.70      www      3041:     }
                   3042:     return %returnhash;
1.1       albertel 3043: }
                   3044: 
1.617     albertel 3045: # ---------------------------------------------------------- Get a studentphoto
                   3046: sub studentphoto {
                   3047:     my ($udom,$unam,$ext) = @_;
                   3048:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3049:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3050:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3051:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3052:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3053:             } else {
                   3054:                 my ($result,$perm_reqd)=
1.707     albertel 3055: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3056:                 if ($result eq 'ok') {
                   3057:                     if (!($perm_reqd eq 'yes')) {
                   3058:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3059:                     }
                   3060:                 }
                   3061:             }
                   3062:         }
                   3063:     } else {
                   3064:         my ($result,$perm_reqd) = 
1.707     albertel 3065: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3066:         if ($result eq 'ok') {
                   3067:             if (!($perm_reqd eq 'yes')) {
                   3068:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3069:             }
                   3070:         }
                   3071:     }
                   3072:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3073: }
                   3074: 
                   3075: sub retrievestudentphoto {
                   3076:     my ($udom,$unam,$ext,$type) = @_;
                   3077:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3078:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3079:     if ($ret eq 'ok') {
                   3080:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3081:         if ($type eq 'thumbnail') {
                   3082:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3083:         }
                   3084:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3085:         return $tokenurl;
                   3086:     } else {
                   3087:         if ($type eq 'thumbnail') {
                   3088:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3089:         } else { 
                   3090:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3091:         }
1.617     albertel 3092:     }
                   3093: }
                   3094: 
1.263     www      3095: # -------------------------------------------------------------------- New chat
                   3096: 
                   3097: sub chatsend {
1.724     raeburn  3098:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3099:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3100:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3101:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3102:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3103: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3104: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3105: }
                   3106: 
                   3107: # ------------------------------------------ Find current version of a resource
                   3108: 
                   3109: sub getversion {
                   3110:     my $fname=&clutter(shift);
1.1189    raeburn  3111:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3112:     return &currentversion(&filelocation('',$fname));
                   3113: }
                   3114: 
                   3115: sub currentversion {
                   3116:     my $fname=shift;
                   3117:     my $author=$fname;
                   3118:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3119:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3120:     my $home=&homeserver($uname,$udom);
1.292     www      3121:     if ($home eq 'no_host') { 
                   3122:         return -1; 
                   3123:     }
1.1112    www      3124:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3125:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3126: 	return -1;
                   3127:     }
1.1112    www      3128:     return $answer;
1.263     www      3129: }
                   3130: 
1.1111    www      3131: #
                   3132: # Return special version number of resource if set by override, empty otherwise
                   3133: #
                   3134: sub usedversion {
                   3135:     my $fname=shift;
                   3136:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3137:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3138:     if ($urlversion) { return $urlversion; }
                   3139:     return '';
                   3140: }
                   3141: 
1.1       albertel 3142: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3143: 
1.1       albertel 3144: sub subscribe {
                   3145:     my $fname=shift;
1.761     raeburn  3146:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3147:     $fname=~s/[\n\r]//g;
1.1       albertel 3148:     my $author=$fname;
                   3149:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3150:     my ($udom,$uname)=split(/\//,$author);
                   3151:     my $home=homeserver($uname,$udom);
1.335     albertel 3152:     if ($home eq 'no_host') {
                   3153:         return 'not_found';
1.1       albertel 3154:     }
                   3155:     my $answer=reply("sub:$fname",$home);
1.64      www      3156:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3157: 	$answer.=' by '.$home;
                   3158:     }
1.1       albertel 3159:     return $answer;
                   3160: }
                   3161:     
1.8       www      3162: # -------------------------------------------------------------- Replicate file
                   3163: 
                   3164: sub repcopy {
                   3165:     my $filename=shift;
1.23      www      3166:     $filename=~s/\/+/\//g;
1.1142    raeburn  3167:     my $londocroot = $perlvar{'lonDocRoot'};
                   3168:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3169:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3170:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3171: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3172: 	return &repcopy_userfile($filename);
                   3173:     }
1.532     albertel 3174:     $filename=~s/[\n\r]//g;
1.8       www      3175:     my $transname="$filename.in.transfer";
1.828     www      3176: # FIXME: this should flock
1.607     raeburn  3177:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3178:     my $remoteurl=subscribe($filename);
1.64      www      3179:     if ($remoteurl =~ /^con_lost by/) {
                   3180: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3181:            return 'unavailable';
1.8       www      3182:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3183: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3184: 	   return 'not_found';
1.64      www      3185:     } elsif ($remoteurl =~ /^rejected by/) {
                   3186: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3187:            return 'forbidden';
1.20      www      3188:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3189:            return 'ok';
1.8       www      3190:     } else {
1.290     www      3191:         my $author=$filename;
                   3192:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3193:         my ($udom,$uname)=split(/\//,$author);
                   3194:         my $home=homeserver($uname,$udom);
                   3195:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3196:            my @parts=split(/\//,$filename);
                   3197:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3198:            if ($path ne "$londocroot/res") {
1.8       www      3199:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3200: 	       return 'bad_request';
1.8       www      3201:            }
                   3202:            my $count;
                   3203:            for ($count=5;$count<$#parts;$count++) {
                   3204:                $path.="/$parts[$count]";
                   3205:                if ((-e $path)!=1) {
                   3206: 		   mkdir($path,0777);
                   3207:                }
                   3208:            }
                   3209:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3210:            my $response;
                   3211:            if ($remoteurl =~ m{/raw/}) {
                   3212:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3213:            } else {
                   3214:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3215:            }
1.8       www      3216:            if ($response->is_error()) {
                   3217: 	       unlink($transname);
                   3218:                my $message=$response->status_line;
1.672     albertel 3219:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3220:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3221:                return 'unavailable';
1.8       www      3222:            } else {
1.16      www      3223: 	       if ($remoteurl!~/\.meta$/) {
                   3224:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3225:                   my $mresponse;
                   3226:                   if ($remoteurl =~ m{/raw/}) {
                   3227:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3228:                   } else {
                   3229:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3230:                   }
1.16      www      3231:                   if ($mresponse->is_error()) {
                   3232: 		      unlink($filename.'.meta');
                   3233:                       &logthis(
1.672     albertel 3234:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3235:                   }
                   3236: 	       }
1.8       www      3237:                rename($transname,$filename);
1.607     raeburn  3238:                return 'ok';
1.8       www      3239:            }
1.290     www      3240:        }
1.8       www      3241:     }
1.330     www      3242: }
                   3243: 
                   3244: # ------------------------------------------------ Get server side include body
                   3245: sub ssi_body {
1.381     albertel 3246:     my ($filelink,%form)=@_;
1.606     matthew  3247:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3248:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3249:     }
1.953     www      3250:     my $output='';
                   3251:     my $response;
1.980     raeburn  3252:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3253:        ($output,$response)=&externalssi($filelink);
1.953     www      3254:     } else {
1.1004    droeschl 3255:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3256:        $filelink .= 'inhibitmenu=yes';
1.953     www      3257:        ($output,$response)=&ssi($filelink,%form);
                   3258:     }
1.778     albertel 3259:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3260:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3261:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3262:     if (wantarray) {
                   3263:         return ($output, $response);
                   3264:     } else {
                   3265:         return $output;
                   3266:     }
1.8       www      3267: }
                   3268: 
1.15      www      3269: # --------------------------------------------------------- Server Side Include
                   3270: 
1.782     albertel 3271: sub absolute_url {
                   3272:     my ($host_name) = @_;
                   3273:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3274:     if ($host_name eq '') {
                   3275: 	$host_name = $ENV{'SERVER_NAME'};
                   3276:     }
                   3277:     return $protocol.$host_name;
                   3278: }
                   3279: 
1.942     foxr     3280: #
                   3281: #   Server side include.
                   3282: # Parameters:
                   3283: #  fn     Possibly encrypted resource name/id.
                   3284: #  form   Hash that describes how the rendering should be done
                   3285: #         and other things.
1.944     foxr     3286: # Returns:
1.950     raeburn  3287: #   Scalar context: The content of the response.
                   3288: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3289: #     
1.15      www      3290: sub ssi {
                   3291: 
1.944     foxr     3292:     my ($fn,%form)=@_;
1.23      www      3293:     my $request;
1.711     albertel 3294: 
                   3295:     $form{'no_update_last_known'}=1;
1.895     albertel 3296:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3297:     if (%form) {
1.782     albertel 3298:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3299:       $request->content(join('&',map { 
                   3300:             my $name = escape($_);
                   3301:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3302:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3303:             : &escape($form{$_}) );    
                   3304:         } keys(%form)));
1.23      www      3305:     } else {
1.782     albertel 3306:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3307:     }
                   3308: 
1.15      www      3309:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3310:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3311:     my $islocal;
                   3312:     if (($env{'request.course.id'}) &&
                   3313:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3314:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3315:         ($form{'grade_symb'} ne '') &&
                   3316:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3317:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3318:         $islocal = 1;
                   3319:     }
1.1384    raeburn  3320:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3321:                                                 '','','',$islocal);
1.1182    foxr     3322: 
1.944     foxr     3323:     if (wantarray) {
1.1345    raeburn  3324: 	return ($response->content, $response);
1.944     foxr     3325:     } else {
1.1345    raeburn  3326: 	return $response->content;
1.942     foxr     3327:     }
1.324     www      3328: }
                   3329: 
                   3330: sub externalssi {
                   3331:     my ($url)=@_;
                   3332:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3333:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3334:     if (wantarray) {
                   3335:         return ($response->content, $response);
                   3336:     } else {
                   3337:         return $response->content;
                   3338:     }
1.15      www      3339: }
1.254     www      3340: 
1.1354    raeburn  3341: 
                   3342: # If the local copy of a replicated resource is outdated, trigger a  
                   3343: # connection from the homeserver to flush the delayed queue. If no update 
                   3344: # happens, remove local copies of outdated resource (and corresponding
                   3345: # metadata file).
                   3346: 
1.1352    raeburn  3347: sub remove_stale_resfile {
                   3348:     my ($url) = @_;
1.1354    raeburn  3349:     my $removed;
1.1352    raeburn  3350:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3351:         my $audom = $1;
                   3352:         my $auname = $2;
1.1353    raeburn  3353:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3354:             my $homeserver = &homeserver($auname,$audom);
                   3355:             unless (($homeserver eq 'no_host') ||
                   3356:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3357:                 my $fname = &filelocation('',$url);
                   3358:                 if (-e $fname) {
                   3359:                     my $protocol = $protocol{$homeserver};
                   3360:                     $protocol = 'http' if ($protocol ne 'https');
                   3361:                     my $hostname = &hostname($homeserver);
                   3362:                     if ($hostname) {
                   3363:                         my $uri = &declutter($url);
                   3364:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3365:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3366:                         if ($response->is_success()) {
                   3367:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3368:                             my $locmodtime = (stat($fname))[9];
                   3369:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3370:                                 my $stale;
                   3371:                                 my $answer = &reply('pong',$homeserver);
                   3372:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3373:                                     sleep(0.2);
                   3374:                                     $locmodtime = (stat($fname))[9];
                   3375:                                     if ($locmodtime < $remmodtime) {
                   3376:                                         my $posstransfer = $fname.'.in.transfer';
                   3377:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3378:                                             $removed = 1;
                   3379:                                         } else {
                   3380:                                             $stale = 1;
                   3381:                                         }
                   3382:                                     } else {
                   3383:                                         $removed = 1;
                   3384:                                     }
                   3385:                                 } else {
                   3386:                                     $stale = 1;
                   3387:                                 }
                   3388:                                 if ($stale) {
                   3389:                                     unlink($fname);
                   3390:                                     if ($uri!~/\.meta$/) {
                   3391:                                         unlink($fname.'.meta');
                   3392:                                     }
                   3393:                                     &reply("unsub:$fname",$homeserver);
                   3394:                                     $removed = 1;
1.1352    raeburn  3395:                                 }
                   3396:                             }
                   3397:                         }
                   3398:                     }
                   3399:                 }
                   3400:             }
                   3401:         }
                   3402:     }
1.1354    raeburn  3403:     return $removed;
1.1352    raeburn  3404: }
                   3405: 
1.492     albertel 3406: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3407: 
                   3408: sub allowuploaded {
                   3409:     my ($srcurl,$url)=@_;
                   3410:     $url=&clutter(&declutter($url));
                   3411:     my $dir=$url;
                   3412:     $dir=~s/\/[^\/]+$//;
                   3413:     my %httpref=();
                   3414:     my $httpurl=&hreflocation('',$url);
                   3415:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3416:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3417: }
1.477     raeburn  3418: 
1.1193    raeburn  3419: #
                   3420: # Determine if the current user should be able to edit a particular resource,
                   3421: # when viewing in course context.
                   3422: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3423: #     Functions.
                   3424: # (b) When displaying folder contents in course editor, used to determine if
                   3425: #     "Edit" link will be displayed alongside resource.
                   3426: #
1.1196    raeburn  3427: #  input: six args -- filename (decluttered), course number, course domain,
                   3428: #                   url, symb (if registered) and group (if this is a group
                   3429: #                   item -- e.g., bulletin board, group page etc.).
                   3430: #  output: array of five scalars -- 
1.1193    raeburn  3431: #          $cfile -- url for file editing if editable on current server
                   3432: #          $home -- homeserver of resource (i.e., for author if published,
                   3433: #                                           or course if uploaded.).
                   3434: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3435: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3436: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3437: #
                   3438: 
                   3439: sub can_edit_resource {
1.1194    raeburn  3440:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3441:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3442: #
                   3443: # For aboutme pages user can only edit his/her own.
                   3444: #
1.1199    raeburn  3445:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3446:         my ($sdom,$sname) = ($1,$2);
                   3447:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3448:             $home = $env{'user.home'};
                   3449:             $cfile = $resurl;
                   3450:             if ($env{'form.forceedit'}) {
                   3451:                 $forceview = 1;
                   3452:             } else {
                   3453:                 $forceedit = 1;
                   3454:             }
                   3455:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3456:         } else {
                   3457:             return;
                   3458:         }
                   3459:     }
                   3460: 
                   3461:     if ($env{'request.course.id'}) {
                   3462:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3463:         if ($group ne '') {
                   3464: # if this is a group homepage or group bulletin board, check group privs
                   3465:             my $allowed = 0;
1.1197    raeburn  3466:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3467:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3468:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3469:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3470:                     $allowed = 1;
                   3471:                 }
1.1197    raeburn  3472:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3473:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3474:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3475:                     $allowed = 1;
                   3476:                 }
                   3477:             }
                   3478:             if ($allowed) {
                   3479:                 $home=&homeserver($cnum,$cdom);
                   3480:                 if ($env{'form.forceedit'}) {
                   3481:                     $forceview = 1;
                   3482:                 } else {
                   3483:                     $forceedit = 1;
                   3484:                 }
                   3485:                 $cfile = $resurl;
                   3486:             } else {
                   3487:                 return;
                   3488:             }
                   3489:         } else {
1.1208    raeburn  3490:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3491:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3492:                     return;
                   3493:                 }
                   3494:             } elsif (!$crsedit) {
1.1194    raeburn  3495: #
                   3496: # No edit allowed where CC has switched to student role.
                   3497: #
                   3498:                 return;
                   3499:             }
                   3500:         }
                   3501:     }
                   3502: 
1.1193    raeburn  3503:     if ($file ne '') {
                   3504:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3505:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3506:                 $uploaded = 1;
                   3507:                 $incourse = 1;
1.1193    raeburn  3508:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3509:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3510:                     if ($env{'form.forceedit'}) {
                   3511:                         $forceview = 1;
                   3512:                     } else {
                   3513:                         $forceedit = 1;
                   3514:                     }
1.1194    raeburn  3515:                 }
                   3516:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3517:                 $incourse = 1;
                   3518:                 if ($env{'form.forceedit'}) {
                   3519:                     $forceview = 1;
                   3520:                 } else {
                   3521:                     $forceedit = 1;
                   3522:                 }
                   3523:                 $cfile = $resurl;
                   3524:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3525:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3526:                     $incourse = 1;
                   3527:                     if ($env{'form.forceedit'}) {
                   3528:                         $forceview = 1;
                   3529:                     } else {
                   3530:                         $forceedit = 1;
                   3531:                     }
                   3532:                     $cfile = $resurl;
1.1199    raeburn  3533:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3534:                     $incourse = 1;
                   3535:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3536:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3537:                     $incourse = 1;
1.1199    raeburn  3538:                     if ($env{'form.forceedit'}) {
                   3539:                         $forceview = 1;
                   3540:                     } else {
                   3541:                         $forceedit = 1;
                   3542:                     }
                   3543:                     $cfile = $resurl;
1.1343    raeburn  3544:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3545:                     $incourse = 1;
                   3546:                     if ($env{'form.forceedit'}) {
                   3547:                         $forceview = 1;
                   3548:                     } else {
                   3549:                         $forceedit = 1;
                   3550:                     }
                   3551:                     $cfile = $resurl;
1.1208    raeburn  3552:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3553:                     $incourse = 1;
                   3554:                     if ($env{'form.forceedit'}) {
                   3555:                         $forceview = 1;
                   3556:                     } else {
                   3557:                         $forceedit = 1;
                   3558:                     }
                   3559:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3560:                 }
                   3561:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3562:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3563:                 if (&is_on_map($template)) { 
                   3564:                     $incourse = 1;
                   3565:                     $forceview = 1;
                   3566:                     $cfile = $template;
1.1193    raeburn  3567:                 }
1.1199    raeburn  3568:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3569:                     $incourse = 1;
                   3570:                     if ($env{'form.forceedit'}) {
                   3571:                         $forceview = 1;
                   3572:                     } else {
                   3573:                         $forceedit = 1;
                   3574:                     }
                   3575:                     $cfile = $resurl;
1.1343    raeburn  3576:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3577:                 $incourse = 1;
                   3578:                 if ($env{'form.forceedit'}) {
                   3579:                     $forceview = 1;
                   3580:                 } else {
                   3581:                     $forceedit = 1;
                   3582:                 }
                   3583:                 $cfile = $resurl;
1.1199    raeburn  3584:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3585:                 $incourse = 1;
                   3586:                 $forceview = 1;
                   3587:                 if ($symb) {
                   3588:                     my ($map,$id,$res)=&decode_symb($symb);
                   3589:                     $env{'request.symb'} = $symb;
                   3590:                     $cfile = &clutter($res);
                   3591:                 } else {
                   3592:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3593:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3594:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3595:                         $cfile = '/adm/wrapper'.$escfile;
                   3596:                     } else {
                   3597:                         $escfile =~ s{^http://}{};
                   3598:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3599:                     }
1.1199    raeburn  3600:                 }
1.1234    raeburn  3601:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3602:                 if ($env{'form.forceedit'}) {
                   3603:                     $forceview = 1;
                   3604:                 } else {
                   3605:                     $forceedit = 1;
                   3606:                 }
                   3607:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3608:             }
                   3609:         }
1.1194    raeburn  3610:         if ($uploaded || $incourse) {
                   3611:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3612:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3613:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3614:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3615:             # Check that the user has permission to edit this resource
                   3616:             my $setpriv = 1;
                   3617:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3618:             if (defined($cfudom)) {
                   3619:                 $home=&homeserver($cfuname,$cfudom);
                   3620:                 $cfile=$file;
                   3621:             }
                   3622:         }
1.1194    raeburn  3623:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3624:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3625:             my @ids=&current_machine_ids();
                   3626:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3627:                 $switchserver=1;
                   3628:             }
                   3629:         }
                   3630:     }
1.1194    raeburn  3631:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3632: }
                   3633: 
                   3634: sub is_course_upload {
                   3635:     my ($file,$cnum,$cdom) = @_;
                   3636:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3637:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3638:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3639:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3640:         return 1;
                   3641:     }
                   3642:     return;
                   3643: }
                   3644: 
1.1194    raeburn  3645: sub in_course {
1.1195    raeburn  3646:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3647:     if ($hideprivileged) {
                   3648:         my $skipuser;
1.1219    raeburn  3649:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3650:         my @possdoms = ($cdom);  
                   3651:         if ($coursehash{'checkforpriv'}) { 
                   3652:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3653:         }
                   3654:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3655:             $skipuser = 1;
                   3656:             if ($coursehash{'nothideprivileged'}) {
                   3657:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3658:                     my $user;
                   3659:                     if ($item =~ /:/) {
                   3660:                         $user = $item;
                   3661:                     } else {
                   3662:                         $user = join(':',split(/[\@]/,$item));
                   3663:                     }
                   3664:                     if ($user eq $uname.':'.$udom) {
                   3665:                         undef($skipuser);
                   3666:                         last;
                   3667:                     }
                   3668:                 }
                   3669:             }
                   3670:             if ($skipuser) {
                   3671:                 return 0;
                   3672:             }
                   3673:         }
                   3674:     }
1.1194    raeburn  3675:     $type ||= 'any';
                   3676:     if (!defined($cdom) || !defined($cnum)) {
                   3677:         my $cid  = $env{'request.course.id'};
                   3678:         $cdom = $env{'course.'.$cid.'.domain'};
                   3679:         $cnum = $env{'course.'.$cid.'.num'};
                   3680:     }
                   3681:     my $typesref;
1.1195    raeburn  3682:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3683:         $typesref = ['active','previous','future'];
                   3684:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3685:         $typesref = [$type];
                   3686:     }
                   3687:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3688:                               $typesref,undef,[$cdom]);
                   3689:     my ($tmp) = keys(%roles);
                   3690:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3691:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3692:     if (@course_roles > 0) {
                   3693:         return 1;
                   3694:     }
                   3695:     return 0;
                   3696: }
                   3697: 
1.478     albertel 3698: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3699: # input: action, courseID, current domain, intended
1.637     raeburn  3700: #        path to file, source of file, instruction to parse file for objects,
                   3701: #        ref to hash for embedded objects,
                   3702: #        ref to hash for codebase of java objects.
1.1095    raeburn  3703: #        reference to scalar to accommodate mime type determined
                   3704: #          from File::MMagic if $parser = parse.
1.637     raeburn  3705: #
1.485     raeburn  3706: # output: url to file (if action was uploaddoc), 
                   3707: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3708: #
1.478     albertel 3709: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3710: # course.
1.477     raeburn  3711: #
1.478     albertel 3712: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3713: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3714: #          course's home server.
1.477     raeburn  3715: #
1.478     albertel 3716: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3717: #          be copied from $source (current location) to 
                   3718: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3719: #         and will then be copied to
                   3720: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3721: #         course's home server.
1.485     raeburn  3722: #
1.481     raeburn  3723: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3724: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3725: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3726: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3727: #         in course's home server.
1.637     raeburn  3728: #
1.477     raeburn  3729: 
                   3730: sub process_coursefile {
1.1095    raeburn  3731:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3732:         $mimetype)=@_;
1.477     raeburn  3733:     my $fetchresult;
1.638     albertel 3734:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3735:     if ($action eq 'propagate') {
1.638     albertel 3736:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3737: 			     $home);
1.481     raeburn  3738:     } else {
1.477     raeburn  3739:         my $fpath = '';
                   3740:         my $fname = $file;
1.478     albertel 3741:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3742:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3743:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3744:         if ($action eq 'copy') {
                   3745:             if ($source eq '') {
                   3746:                 $fetchresult = 'no source file';
                   3747:                 return $fetchresult;
                   3748:             } else {
                   3749:                 my $destination = $filepath.'/'.$fname;
                   3750:                 rename($source,$destination);
                   3751:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3752:                                  $home);
1.481     raeburn  3753:             }
                   3754:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3755:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3756:             print $fh $env{'form.'.$source};
1.481     raeburn  3757:             close($fh);
1.637     raeburn  3758:             if ($parser eq 'parse') {
1.1024    raeburn  3759:                 my $mm = new File::MMagic;
1.1095    raeburn  3760:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3761:                 if ($type eq 'text/html') {
1.1024    raeburn  3762:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3763:                     unless ($parse_result eq 'ok') {
                   3764:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3765:                     }
1.637     raeburn  3766:                 }
1.1095    raeburn  3767:                 if (ref($mimetype)) {
                   3768:                     $$mimetype = $type;
                   3769:                 } 
1.637     raeburn  3770:             }
1.477     raeburn  3771:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3772:                                  $home);
1.481     raeburn  3773:             if ($fetchresult eq 'ok') {
                   3774:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3775:             } else {
                   3776:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3777:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3778:                 return '/adm/notfound.html';
                   3779:             }
1.477     raeburn  3780:         }
                   3781:     }
1.485     raeburn  3782:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3783:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3784:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3785:     }
                   3786:     return $fetchresult;
                   3787: }
                   3788: 
1.637     raeburn  3789: sub build_filepath {
                   3790:     my ($fpath) = @_;
                   3791:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3792:     unless ($fpath eq '') {
                   3793:         my @parts=split('/',$fpath);
                   3794:         foreach my $part (@parts) {
                   3795:             $filepath.= '/'.$part;
                   3796:             if ((-e $filepath)!=1) {
                   3797:                 mkdir($filepath,0777);
                   3798:             }
                   3799:         }
                   3800:     }
                   3801:     return $filepath;
                   3802: }
                   3803: 
                   3804: sub store_edited_file {
1.638     albertel 3805:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3806:     my $file = $primary_url;
                   3807:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3808:     my $fpath = '';
                   3809:     my $fname = $file;
                   3810:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3811:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3812:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3813:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3814:     print $fh $content;
                   3815:     close($fh);
1.638     albertel 3816:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3817:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3818: 			  $home);
1.637     raeburn  3819:     if ($$fetchresult eq 'ok') {
                   3820:         return '/uploaded/'.$fpath.'/'.$fname;
                   3821:     } else {
1.638     albertel 3822:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3823: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3824:         return '/adm/notfound.html';
                   3825:     }
                   3826: }
                   3827: 
1.531     albertel 3828: sub clean_filename {
1.831     albertel 3829:     my ($fname,$args)=@_;
1.315     www      3830: # Replace Windows backslashes by forward slashes
1.257     www      3831:     $fname=~s/\\/\//g;
1.831     albertel 3832:     if (!$args->{'keep_path'}) {
                   3833:         # Get rid of everything but the actual filename
                   3834: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3835:     }
1.315     www      3836: # Replace spaces by underscores
                   3837:     $fname=~s/\s+/\_/g;
                   3838: # Replace all other weird characters by nothing
1.831     albertel 3839:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3840: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3841: # numbers
                   3842:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3843:     return $fname;
                   3844: }
1.1051    raeburn  3845: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3846: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3847: # image with the same aspect ratio as the original, but with dimensions which do 
                   3848: # not exceed $resizewidth and $resizeheight.
                   3849:  
1.984     neumanie 3850: sub resizeImage {
1.1051    raeburn  3851:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3852:     my $ima = Image::Magick->new;
                   3853:     my $resized;
                   3854:     if (-e $img_path) {
                   3855:         $ima->Read($img_path);
                   3856:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3857:             my $width = $ima->Get('width');
                   3858:             my $height = $ima->Get('height');
                   3859:             if ($width > $resizewidth) {
                   3860: 	        my $factor = $width/$resizewidth;
                   3861:                 my $newheight = $height/$factor;
                   3862:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3863:                 $resized = 1;
                   3864:             }
                   3865:         }
                   3866:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3867:             my $width = $ima->Get('width');
                   3868:             my $height = $ima->Get('height');
                   3869:             if ($height > $resizeheight) {
                   3870:                 my $factor = $height/$resizeheight;
                   3871:                 my $newwidth = $width/$factor;
                   3872:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3873:                 $resized = 1;
                   3874:             }
                   3875:         }
                   3876:         if ($resized) {
                   3877:             $ima->Write($img_path);
                   3878:         }
                   3879:     }
                   3880:     return;
1.977     amueller 3881: }
                   3882: 
1.608     albertel 3883: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3884: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3885: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3886: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3887: #                                    canceloverwrite, or ''. 
                   3888: #                   if 'coursedoc': upload to the current course
                   3889: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3890: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3891: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3892: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3893: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3894: #        $allfiles - reference to hash for embedded objects
                   3895: #        $codebase - reference to hash for codebase of java objects
                   3896: #        $desuname - username for permanent storage of uploaded file
                   3897: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3898: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3899: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3900: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3901: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3902: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3903: #                    from File::MMagic.
1.858     raeburn  3904: # 
1.686     albertel 3905: # output: url of file in userspace, or error: <message> 
                   3906: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3907: 
1.531     albertel 3908: sub userfileupload {
1.1090    raeburn  3909:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3910:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3911:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3912:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3913:     $fname=&clean_filename($fname);
1.1090    raeburn  3914:     # See if there is anything left
1.257     www      3915:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3916:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3917:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3918:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3919:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3920:         my $now = time;
1.1090    raeburn  3921:         my $filepath;
1.1095    raeburn  3922:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3923:              $filepath = 'tmp/helprequests/'.$now;
                   3924:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3925:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3926:                          '_'.$env{'user.domain'}.'/pending';
                   3927:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3928:             my ($docuname,$docudom);
1.1350    raeburn  3929:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3930:                 $docudom = $destudom;
                   3931:             } else {
                   3932:                 $docudom = $env{'user.domain'};
                   3933:             }
1.1350    raeburn  3934:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3935:                 $docuname = $destuname;
                   3936:             } else {
                   3937:                 $docuname = $env{'user.name'};
                   3938:             }
                   3939:             if (exists($env{'form.group'})) {
                   3940:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3941:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3942:             }
                   3943:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3944:             if ($context eq 'canceloverwrite') {
                   3945:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3946:                 if (-e  $tempfile) {
                   3947:                     my @info = stat($tempfile);
                   3948:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3949:                         unlink($tempfile);
                   3950:                     }
                   3951:                 }
                   3952:                 return;
1.523     raeburn  3953:             }
                   3954:         }
1.1090    raeburn  3955:         # Create the directory if not present
1.741     raeburn  3956:         my @parts=split(/\//,$filepath);
                   3957:         my $fullpath = $perlvar{'lonDaemons'};
                   3958:         for (my $i=0;$i<@parts;$i++) {
                   3959:             $fullpath .= '/'.$parts[$i];
                   3960:             if ((-e $fullpath)!=1) {
                   3961:                 mkdir($fullpath,0777);
                   3962:             }
                   3963:         }
1.1359    raeburn  3964:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3965:         print $fh $env{'form.'.$formname};
                   3966:         close($fh);
1.1090    raeburn  3967:         if ($context eq 'existingfile') {
                   3968:             my @info = stat($fullpath.'/'.$fname);
                   3969:             return ($fullpath.'/'.$fname,$info[9]);
                   3970:         } else {
                   3971:             return $fullpath.'/'.$fname;
                   3972:         }
1.523     raeburn  3973:     }
1.995     raeburn  3974:     if ($subdir eq 'scantron') {
                   3975:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3976:     } else {
1.995     raeburn  3977:         $fname="$subdir/$fname";
                   3978:     }
1.1090    raeburn  3979:     if ($context eq 'coursedoc') {
1.638     albertel 3980: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3981: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3982:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3983:             return &finishuserfileupload($docuname,$docudom,
                   3984: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3985: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3986:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3987:         } else {
1.1218    raeburn  3988:             if ($env{'form.folder'}) {
                   3989:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3990:             }
1.638     albertel 3991:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3992: 				       $fname,$formname,$parser,
1.1095    raeburn  3993: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3994:         }
1.719     banghart 3995:     } elsif (defined($destuname)) {
                   3996:         my $docuname=$destuname;
                   3997:         my $docudom=$destudom;
1.860     raeburn  3998: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3999: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4000:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4001:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4002:     } else {
1.638     albertel 4003:         my $docuname=$env{'user.name'};
                   4004:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4005:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4006:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4007:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4008:         }
1.860     raeburn  4009: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4010: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4011:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4012:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4013:     }
1.271     www      4014: }
                   4015: 
                   4016: sub finishuserfileupload {
1.860     raeburn  4017:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4018:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4019:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4020:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4021:   
1.860     raeburn  4022:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4023:     $file=$fname;
                   4024:     if ($fname=~m|/|) {
                   4025:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4026: 	$path.=$fnamepath.'/';
                   4027:     }
1.259     www      4028:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4029:     my $count;
                   4030:     for ($count=4;$count<=$#parts;$count++) {
                   4031:         $filepath.="/$parts[$count]";
                   4032:         if ((-e $filepath)!=1) {
                   4033: 	    mkdir($filepath,0777);
                   4034:         }
                   4035:     }
1.984     neumanie 4036: 
1.258     www      4037: # Save the file
                   4038:     {
1.1359    raeburn  4039: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4040: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4041: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4042: 	    return '/adm/notfound.html';
                   4043: 	}
1.1090    raeburn  4044:         if ($context eq 'overwrite') {
1.1117    foxr     4045:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4046:             my $target = $filepath.'/'.$file;
                   4047:             if (-e $source) {
                   4048:                 my @info = stat($source);
                   4049:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4050:                     unless (&File::Copy::move($source,$target)) {
                   4051:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4052:                         return "Moving from $source failed";
                   4053:                     }
                   4054:                 } else {
                   4055:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4056:                 }
                   4057:             } else {
                   4058:                 return "Temporary file: $source missing";
                   4059:             }
                   4060:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4061: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4062: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4063: 	    return '/adm/notfound.html';
                   4064: 	}
1.570     albertel 4065: 	close(FH);
1.1051    raeburn  4066:         if ($resizewidth && $resizeheight) {
                   4067:             my $mm = new File::MMagic;
                   4068:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4069:             if ($mime_type =~ m{^image/}) {
                   4070: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4071:             }  
1.977     amueller 4072: 	}
1.258     www      4073:     }
1.1152    raeburn  4074:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4075:         if (ref($mimetype)) {
                   4076:             if ($$mimetype eq '') {
                   4077:                 my $mm = new File::MMagic;
                   4078:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4079:                 $$mimetype = $type;
                   4080:             }
                   4081:         }
                   4082:     }
1.637     raeburn  4083:     if ($parser eq 'parse') {
1.1152    raeburn  4084:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4085:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4086:                                                        $allfiles,$codebase);
                   4087:             unless ($parse_result eq 'ok') {
                   4088:                 &logthis('Failed to parse '.$filepath.$file.
                   4089: 	   	         ' for embedded media: '.$parse_result); 
                   4090:             }
1.637     raeburn  4091:         }
                   4092:     }
1.860     raeburn  4093:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4094:         my $input = $filepath.'/'.$file;
                   4095:         my $output = $filepath.'/'.'tn-'.$file;
                   4096:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4097:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4098:         system({$args[0]} @args);
1.860     raeburn  4099:         if (-e $filepath.'/'.'tn-'.$file) {
                   4100:             $fetchthumb  = 1; 
                   4101:         }
                   4102:     }
1.858     raeburn  4103:  
1.259     www      4104: # Notify homeserver to grep it
                   4105: #
1.984     neumanie 4106:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4107:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4108:     if ($fetchresult eq 'ok') {
1.860     raeburn  4109:         if ($fetchthumb) {
                   4110:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4111:             if ($thumbresult ne 'ok') {
                   4112:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4113:                          $docuhome.': '.$thumbresult);
                   4114:             }
                   4115:         }
1.259     www      4116: #
1.258     www      4117: # Return the URL to it
1.494     albertel 4118:         return '/uploaded/'.$path.$file;
1.263     www      4119:     } else {
1.494     albertel 4120:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4121: 		 ': '.$fetchresult);
1.263     www      4122:         return '/adm/notfound.html';
1.858     raeburn  4123:     }
1.493     albertel 4124: }
                   4125: 
1.637     raeburn  4126: sub extract_embedded_items {
1.961     raeburn  4127:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4128:     my @state = ();
1.1164    raeburn  4129:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4130:     my %javafiles = (
                   4131:                       codebase => '',
                   4132:                       code => '',
                   4133:                       archive => ''
                   4134:                     );
                   4135:     my %mediafiles = (
                   4136:                       src => '',
                   4137:                       movie => '',
                   4138:                      );
1.648     raeburn  4139:     my $p;
                   4140:     if ($content) {
                   4141:         $p = HTML::LCParser->new($content);
                   4142:     } else {
1.961     raeburn  4143:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4144:     }
1.641     albertel 4145:     while (my $t=$p->get_token()) {
1.640     albertel 4146: 	if ($t->[0] eq 'S') {
                   4147: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4148: 	    push(@state, $tagname);
1.648     raeburn  4149:             if (lc($tagname) eq 'allow') {
                   4150:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4151:             }
1.640     albertel 4152: 	    if (lc($tagname) eq 'img') {
                   4153: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4154: 	    }
1.886     albertel 4155: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4156:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4157:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4158:                 }
1.886     albertel 4159: 	    }
1.645     raeburn  4160:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4161:                 my $src;
1.645     raeburn  4162:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4163:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4164:                 } else {
1.1164    raeburn  4165:                     if ($attr->{'src'} ne '') {
                   4166:                         $src = $attr->{'src'};
                   4167:                         &add_filetype($allfiles,$src,'src');
                   4168:                     }
                   4169:                 }
                   4170:                 my $text = $p->get_trimmed_text();
                   4171:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4172:                     my @swfargs = split(/,/,$1);
                   4173:                     foreach my $item (@swfargs) {
                   4174:                         $item =~ s/["']//g;
                   4175:                         $item =~ s/^\s+//;
                   4176:                         $item =~ s/\s+$//;
                   4177:                     }
                   4178:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4179:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4180:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4181:                         } else {
                   4182:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4183:                         }
                   4184:                     }
1.645     raeburn  4185:                 }
                   4186:             }
                   4187:             if (lc($tagname) eq 'link') {
                   4188:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4189:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4190:                 }
                   4191:             }
1.640     albertel 4192: 	    if (lc($tagname) eq 'object' ||
                   4193: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4194: 		foreach my $item (keys(%javafiles)) {
                   4195: 		    $javafiles{$item} = '';
                   4196: 		}
1.1164    raeburn  4197:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4198:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4199:                 }
1.640     albertel 4200: 	    }
                   4201: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4202: 		my $name = lc($attr->{'name'});
                   4203: 		foreach my $item (keys(%javafiles)) {
                   4204: 		    if ($name eq $item) {
                   4205: 			$javafiles{$item} = $attr->{'value'};
                   4206: 			last;
                   4207: 		    }
                   4208: 		}
1.1164    raeburn  4209:                 my $pathfrom;
1.640     albertel 4210: 		foreach my $item (keys(%mediafiles)) {
                   4211: 		    if ($name eq $item) {
1.1164    raeburn  4212:                         $pathfrom = $attr->{'value'};
                   4213:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4214: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4215: 			last;
                   4216: 		    }
                   4217: 		}
1.1164    raeburn  4218:                 if ($name eq 'flashvars') {
                   4219:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4220:                 }
                   4221:                 if ($pathfrom ne '') {
                   4222:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4223:                                          $pathfrom);
                   4224:                 }
1.640     albertel 4225: 	    }
                   4226: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4227: 		foreach my $item (keys(%javafiles)) {
                   4228: 		    if ($attr->{$item}) {
                   4229: 			$javafiles{$item} = $attr->{$item};
                   4230: 			last;
                   4231: 		    }
                   4232: 		}
                   4233: 		foreach my $item (keys(%mediafiles)) {
                   4234: 		    if ($attr->{$item}) {
                   4235: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4236: 			last;
                   4237: 		    }
                   4238: 		}
1.1164    raeburn  4239:                 if (lc($tagname) eq 'embed') {
                   4240:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4241:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4242:                                              $attr->{'src'});
                   4243:                     }
                   4244:                 }
1.640     albertel 4245: 	    }
1.1243    raeburn  4246:             if (lc($tagname) eq 'iframe') {
                   4247:                 my $src = $attr->{'src'} ;
                   4248:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4249:                     &add_filetype($allfiles,$src,'src');
                   4250:                 } elsif ($src =~ m{^/}) {
                   4251:                     if ($env{'request.course.id'}) {
                   4252:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4253:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4254:                         my $url = &hreflocation('',$fullpath);
                   4255:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4256:                             my $relpath = $1;
                   4257:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4258:                                 &add_filetype($allfiles,$1,'src');
                   4259:                             }
                   4260:                         }
                   4261:                     }
                   4262:                 }
                   4263:             }
1.1164    raeburn  4264:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4265:                 pop(@state);
1.1164    raeburn  4266:             }
1.640     albertel 4267: 	} elsif ($t->[0] eq 'E') {
                   4268: 	    my ($tagname) = ($t->[1]);
                   4269: 	    if ($javafiles{'codebase'} ne '') {
                   4270: 		$javafiles{'codebase'} .= '/';
                   4271: 	    }  
                   4272: 	    if (lc($tagname) eq 'applet' ||
                   4273: 		lc($tagname) eq 'object' ||
                   4274: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4275: 		) {
                   4276: 		foreach my $item (keys(%javafiles)) {
                   4277: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4278: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4279: 			&add_filetype($allfiles,$file,$item);
                   4280: 		    }
                   4281: 		}
                   4282: 	    } 
                   4283: 	    pop @state;
                   4284: 	}
                   4285:     }
1.1164    raeburn  4286:     foreach my $id (sort(keys(%flashvars))) {
                   4287:         if ($shockwave{$id} ne '') {
                   4288:             my @pairs = split(/\&/,$flashvars{$id});
                   4289:             foreach my $pair (@pairs) {
                   4290:                 my ($key,$value) = split(/\=/,$pair);
                   4291:                 if ($key eq 'thumb') {
                   4292:                     &add_filetype($allfiles,$value,$key);
                   4293:                 } elsif ($key eq 'content') {
                   4294:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4295:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4296:                     if ($ext ne '') {
                   4297:                         &add_filetype($allfiles,$path.$value,$ext);
                   4298:                     }
                   4299:                 }
                   4300:             }
                   4301:         }
                   4302:     }
1.637     raeburn  4303:     return 'ok';
                   4304: }
                   4305: 
1.639     albertel 4306: sub add_filetype {
                   4307:     my ($allfiles,$file,$type)=@_;
                   4308:     if (exists($allfiles->{$file})) {
                   4309: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4310: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4311: 	}
                   4312:     } else {
                   4313: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4314:     }
                   4315: }
                   4316: 
1.1164    raeburn  4317: sub embedded_dependency {
                   4318:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4319:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4320:         if (($identifier ne '') &&
                   4321:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4322:             ($pathfrom ne '')) {
                   4323:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4324:             foreach my $dep (@{$related->{$identifier}}) {
                   4325:                 &add_filetype($allfiles,$path.$dep,'object');
                   4326:             }
                   4327:         }
                   4328:     }
                   4329:     return;
                   4330: }
                   4331: 
1.493     albertel 4332: sub removeuploadedurl {
1.984     neumanie 4333:     my ($url)=@_;	
                   4334:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4335:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4336: }
                   4337: 
                   4338: sub removeuserfile {
                   4339:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4340:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4341:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4342:     if ($result eq 'ok') {	
1.798     raeburn  4343:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4344:             my $metafile = $fname.'.meta';
                   4345:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4346: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4347:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4348:             my $sqlresult = 
1.823     albertel 4349:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4350:                                         'portfolio_metadata',$group,
                   4351:                                         'delete');
1.798     raeburn  4352:         }
                   4353:     }
                   4354:     return $result;
1.257     www      4355: }
1.15      www      4356: 
1.530     albertel 4357: sub mkdiruserfile {
                   4358:     my ($docuname,$docudom,$dir)=@_;
                   4359:     my $home=&homeserver($docuname,$docudom);
                   4360:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4361: }
                   4362: 
1.531     albertel 4363: sub renameuserfile {
                   4364:     my ($docuname,$docudom,$old,$new)=@_;
                   4365:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4366:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4367:                         &escape("$old").':'.&escape("$new"),$home);
                   4368:     if ($result eq 'ok') {
                   4369:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4370:             my $oldmeta = $old.'.meta';
                   4371:             my $newmeta = $new.'.meta';
                   4372:             my $metaresult = 
                   4373:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4374: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4375:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4376:             my $sqlresult = 
1.823     albertel 4377:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4378:                                         'portfolio_metadata',$group,
                   4379:                                         'delete');
1.798     raeburn  4380:         }
                   4381:     }
                   4382:     return $result;
1.531     albertel 4383: }
                   4384: 
1.14      www      4385: # ------------------------------------------------------------------------- Log
                   4386: 
                   4387: sub log {
                   4388:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4389:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4390: }
                   4391: 
                   4392: # ------------------------------------------------------------------ Course Log
1.352     www      4393: #
                   4394: # This routine flushes several buffers of non-mission-critical nature
                   4395: #
1.157     www      4396: 
                   4397: sub flushcourselogs {
1.352     www      4398:     &logthis('Flushing log buffers');
                   4399: #
                   4400: # course logs
                   4401: # This is a log of all transactions in a course, which can be used
                   4402: # for data mining purposes
                   4403: #
                   4404: # It also collects the courseid database, which lists last transaction
                   4405: # times and course titles for all courseids
                   4406: #
                   4407:     my %courseidbuffer=();
1.921     raeburn  4408:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4409:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4410: 		          &escape($courselogs{$crsid}),
                   4411: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4412: 	    delete $courselogs{$crsid};
                   4413:         } else {
                   4414:             &logthis('Failed to flush log buffer for '.$crsid);
                   4415:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4416:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4417:                         " exceeded maximum size, deleting.</font>");
                   4418:                delete $courselogs{$crsid};
                   4419:             }
1.352     www      4420:         }
1.920     raeburn  4421:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4422:             'description' => $coursedescrbuf{$crsid},
                   4423:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4424:             'type'        => $coursetypebuf{$crsid},
                   4425:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4426:         };
1.191     harris41 4427:     }
1.352     www      4428: #
                   4429: # Write course id database (reverse lookup) to homeserver of courses 
                   4430: # Is used in pickcourse
                   4431: #
1.840     albertel 4432:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4433:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4434:                                     $courseidbuffer{$crs_home},
                   4435:                                     $crs_home,'timeonly');
1.352     www      4436:     }
                   4437: #
                   4438: # File accesses
                   4439: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4440: #
1.449     matthew  4441:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4442:         if ($entry =~ /___count$/) {
                   4443:             my ($dom,$name);
1.807     albertel 4444:             ($dom,$name,undef)=
1.811     albertel 4445: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4446:             if (! defined($dom) || $dom eq '' || 
                   4447:                 ! defined($name) || $name eq '') {
1.620     albertel 4448:                 my $cid = $env{'request.course.id'};
                   4449:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4450:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4451:             }
1.450     matthew  4452:             my $value = $accesshash{$entry};
                   4453:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4454:             my %temphash=($url => $value);
1.449     matthew  4455:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4456:             if ($result eq 'ok') {
                   4457:                 delete $accesshash{$entry};
                   4458:             }
                   4459:         } else {
1.811     albertel 4460:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4461:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4462:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4463:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4464:                 delete $accesshash{$entry};
                   4465:             }
1.185     www      4466:         }
1.191     harris41 4467:     }
1.352     www      4468: #
                   4469: # Roles
                   4470: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4471: #
1.800     albertel 4472:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4473:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4474: 	    split(/\:/,$entry);
                   4475:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4476:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4477:                 $rudom,$runame) eq 'ok') {
                   4478: 	    delete $userrolehash{$entry};
                   4479:         }
                   4480:     }
1.662     raeburn  4481: #
1.1334    raeburn  4482: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4483: #
                   4484:     my %domrolebuffer = ();
1.1000    raeburn  4485:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4486:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4487:         if ($domrolebuffer{$rudom}) {
                   4488:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4489:                       '='.&escape($domainrolehash{$entry});
                   4490:         } else {
                   4491:             $domrolebuffer{$rudom}.=&escape($entry).
                   4492:                       '='.&escape($domainrolehash{$entry});
                   4493:         }
                   4494:         delete $domainrolehash{$entry};
                   4495:     }
                   4496:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4497: 	my %servers;
                   4498: 	if (defined(&domain($dom,'primary'))) {
                   4499: 	    my $primary=&domain($dom,'primary');
                   4500: 	    my $hostname=&hostname($primary);
                   4501: 	    $servers{$primary} = $hostname;
                   4502: 	} else { 
                   4503: 	    %servers = &get_servers($dom,'library');
                   4504: 	}
1.841     albertel 4505: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4506: 	    if (&reply('domroleput:'.$dom.':'.
                   4507: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4508: 		last;
                   4509: 	    } else {  
1.841     albertel 4510: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4511: 	    }
1.662     raeburn  4512:         }
                   4513:     }
1.186     www      4514:     $dumpcount++;
1.157     www      4515: }
                   4516: 
                   4517: sub courselog {
                   4518:     my $what=shift;
1.158     www      4519:     $what=time.':'.$what;
1.620     albertel 4520:     unless ($env{'request.course.id'}) { return ''; }
                   4521:     $coursedombuf{$env{'request.course.id'}}=
                   4522:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4523:     $coursenumbuf{$env{'request.course.id'}}=
                   4524:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4525:     $coursehombuf{$env{'request.course.id'}}=
                   4526:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4527:     $coursedescrbuf{$env{'request.course.id'}}=
                   4528:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4529:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4530:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4531:     $courseownerbuf{$env{'request.course.id'}}=
                   4532:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4533:     $coursetypebuf{$env{'request.course.id'}}=
                   4534:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4535:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4536: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4537:     } else {
1.620     albertel 4538: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4539:     }
1.620     albertel 4540:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4541: 	&flushcourselogs();
                   4542:     }
1.158     www      4543: }
                   4544: 
                   4545: sub courseacclog {
                   4546:     my $fnsymb=shift;
1.620     albertel 4547:     unless ($env{'request.course.id'}) { return ''; }
                   4548:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4549:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4550:         $what.=':POST';
1.583     matthew  4551:         # FIXME: Probably ought to escape things....
1.800     albertel 4552: 	foreach my $key (keys(%env)) {
                   4553:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4554:                 my $formitem = $1;
                   4555:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4556:                     $what.=':'.$formitem.'='.$env{$key};
                   4557:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4558:                     $what.=':'.$formitem.'='.$env{$key};
                   4559:                 }
1.158     www      4560:             }
1.191     harris41 4561:         }
1.583     matthew  4562:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4563:         # FIXME: We should not be depending on a form parameter that someone
                   4564:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4565:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4566:             $what.= ':POST';
                   4567:             # FIXME: Probably ought to escape things....
                   4568:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4569:                                  'crsdiscuss') {
1.620     albertel 4570:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4571:             }
                   4572:         }
1.158     www      4573:     }
                   4574:     &courselog($what);
1.149     www      4575: }
                   4576: 
1.185     www      4577: sub countacc {
                   4578:     my $url=&declutter(shift);
1.458     matthew  4579:     return if (! defined($url) || $url eq '');
1.620     albertel 4580:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4581: #
                   4582: # Mark that this url was used in this course
                   4583: #
1.620     albertel 4584:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4585: #
                   4586: # Increase the access count for this resource in this child process
                   4587: #
1.281     www      4588:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4589:     $accesshash{$key}++;
1.185     www      4590: }
1.349     www      4591: 
1.361     www      4592: sub linklog {
                   4593:     my ($from,$to)=@_;
                   4594:     $from=&declutter($from);
                   4595:     $to=&declutter($to);
                   4596:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4597:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4598: }
1.1160    www      4599: 
                   4600: sub statslog {
                   4601:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4602:     if ($users<2) { return; }
                   4603:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4604:             'course'       => $env{'request.course.id'},
                   4605:             'sections'     => '"all"',
                   4606:             'num_students' => $users,
                   4607:             'part'         => $part,
                   4608:             'symb'         => $symb,
                   4609:             'mean_tries'   => $av_attempts,
                   4610:             'deg_of_diff'  => $degdiff});
                   4611:     foreach my $key (keys(%dynstore)) {
                   4612:         $accesshash{$key}=$dynstore{$key};
                   4613:     }
                   4614: }
1.361     www      4615:   
1.349     www      4616: sub userrolelog {
                   4617:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4618:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4619:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4620:        $userrolehash
                   4621:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4622:                     =$tend.':'.$tstart;
1.662     raeburn  4623:     }
1.1169    droeschl 4624:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4625:        $userrolehash
                   4626:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4627:                     =$tend.':'.$tstart;
                   4628:     }
1.1334    raeburn  4629:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4630:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4631:        $domainrolehash
                   4632:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4633:                     = $tend.':'.$tstart;
                   4634:     }
1.351     www      4635: }
                   4636: 
1.957     raeburn  4637: sub courserolelog {
                   4638:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4639:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4640:         my $cdom = $1;
                   4641:         my $cnum = $2;
                   4642:         my $sec = $3;
                   4643:         my $namespace = 'rolelog';
                   4644:         my %storehash = (
                   4645:                            role    => $trole,
                   4646:                            start   => $tstart,
                   4647:                            end     => $tend,
                   4648:                            selfenroll => $selfenroll,
                   4649:                            context    => $context,
                   4650:                         );
                   4651:         if ($trole eq 'gr') {
                   4652:             $namespace = 'groupslog';
                   4653:             $storehash{'group'} = $sec;
                   4654:         } else {
                   4655:             $storehash{'section'} = $sec;
                   4656:         }
1.1188    raeburn  4657:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4658:                    $domain,$cnum,$cdom);
1.1184    raeburn  4659:         if (($trole ne 'st') || ($sec ne '')) {
                   4660:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4661:         }
                   4662:     }
                   4663:     return;
                   4664: }
                   4665: 
1.1184    raeburn  4666: sub domainrolelog {
                   4667:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4668:     if ($area =~ m{^/($match_domain)/$}) {
                   4669:         my $cdom = $1;
                   4670:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4671:         my $namespace = 'rolelog';
                   4672:         my %storehash = (
                   4673:                            role    => $trole,
                   4674:                            start   => $tstart,
                   4675:                            end     => $tend,
                   4676:                            context => $context,
                   4677:                         );
1.1188    raeburn  4678:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4679:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4680:     }
                   4681:     return;
                   4682: 
                   4683: }
                   4684: 
                   4685: sub coauthorrolelog {
                   4686:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4687:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4688:         my $audom = $1;
                   4689:         my $auname = $2;
                   4690:         my $namespace = 'rolelog';
                   4691:         my %storehash = (
                   4692:                            role    => $trole,
                   4693:                            start   => $tstart,
                   4694:                            end     => $tend,
                   4695:                            context => $context,
                   4696:                         );
1.1188    raeburn  4697:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4698:                    $domain,$auname,$audom);
1.1184    raeburn  4699:     }
                   4700:     return;
                   4701: }
                   4702: 
1.351     www      4703: sub get_course_adv_roles {
1.948     raeburn  4704:     my ($cid,$codes) = @_;
1.620     albertel 4705:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4706:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4707:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4708:     my %nothide=();
1.800     albertel 4709:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4710:         if ($user !~ /:/) {
                   4711: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4712:         } else {
                   4713:             $nothide{$user}=1;
                   4714:         }
1.470     www      4715:     }
1.1219    raeburn  4716:     my @possdoms = ($coursehash{'domain'});
                   4717:     if ($coursehash{'checkforpriv'}) {
                   4718:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4719:     }
1.351     www      4720:     my %returnhash=();
                   4721:     my %dumphash=
                   4722:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4723:     my $now=time;
1.997     raeburn  4724:     my %privileged;
1.1000    raeburn  4725:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4726: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4727:         if (($tstart) && ($tstart<0)) { next; }
                   4728:         if (($tend) && ($tend<$now)) { next; }
                   4729:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4730:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4731: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4732:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4733:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4734: 	if ($role eq 'cr') { next; }
1.948     raeburn  4735:         if ($codes) {
                   4736:             if ($section) { $role .= ':'.$section; }
                   4737:             if ($returnhash{$role}) {
                   4738:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4739:             } else {
                   4740:                 $returnhash{$role}=$username.':'.$domain;
                   4741:             }
1.351     www      4742:         } else {
1.988     raeburn  4743:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4744:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4745:             if ($returnhash{$key}) {
                   4746: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4747:             } else {
                   4748:                 $returnhash{$key}=$username.':'.$domain;
                   4749:             }
1.351     www      4750:         }
1.948     raeburn  4751:     }
1.400     www      4752:     return %returnhash;
                   4753: }
                   4754: 
                   4755: sub get_my_roles {
1.937     raeburn  4756:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4757:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4758:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4759:     my (%dumphash,%nothide);
1.1086    raeburn  4760:     if ($context eq 'userroles') {
1.1166    raeburn  4761:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4762:     } else {
1.1219    raeburn  4763:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4764:         if ($hidepriv) {
                   4765:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4766:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4767:                 if ($user !~ /:/) {
                   4768:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4769:                 } else {
                   4770:                     $nothide{$user} = 1;
                   4771:                 }
                   4772:             }
                   4773:         }
1.858     raeburn  4774:     }
1.400     www      4775:     my %returnhash=();
                   4776:     my $now=time;
1.999     raeburn  4777:     my %privileged;
1.800     albertel 4778:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4779:         my ($role,$tend,$tstart);
                   4780:         if ($context eq 'userroles') {
1.1149    raeburn  4781:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4782: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4783:         } else {
                   4784:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4785:         }
1.400     www      4786:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4787:         my $status = 'active';
1.939     raeburn  4788:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4789:             $status = 'previous';
                   4790:         } 
                   4791:         if (($tstart) && ($now<$tstart)) {
                   4792:             $status = 'future';
                   4793:         }
                   4794:         if (ref($types) eq 'ARRAY') {
                   4795:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4796:                 next;
                   4797:             } 
                   4798:         } else {
                   4799:             if ($status ne 'active') {
                   4800:                 next;
                   4801:             }
                   4802:         }
1.867     raeburn  4803:         my ($rolecode,$username,$domain,$section,$area);
                   4804:         if ($context eq 'userroles') {
1.1186    raeburn  4805:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4806:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4807:         } else {
                   4808:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4809:         }
1.832     raeburn  4810:         if (ref($roledoms) eq 'ARRAY') {
                   4811:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4812:                 next;
                   4813:             }
                   4814:         }
                   4815:         if (ref($roles) eq 'ARRAY') {
                   4816:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4817:                 if ($role =~ /^cr\//) {
                   4818:                     if (!grep(/^cr$/,@{$roles})) {
                   4819:                         next;
                   4820:                     }
1.1104    raeburn  4821:                 } elsif ($role =~ /^gr\//) {
                   4822:                     if (!grep(/^gr$/,@{$roles})) {
                   4823:                         next;
                   4824:                     }
1.922     raeburn  4825:                 } else {
                   4826:                     next;
                   4827:                 }
1.832     raeburn  4828:             }
1.867     raeburn  4829:         }
1.937     raeburn  4830:         if ($hidepriv) {
1.1219    raeburn  4831:             my @privroles = ('dc','su');
1.999     raeburn  4832:             if ($context eq 'userroles') {
1.1219    raeburn  4833:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4834:             } else {
1.1219    raeburn  4835:                 my $possdoms = [$domain];
                   4836:                 if (ref($roledoms) eq 'ARRAY') {
                   4837:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4838:                 }
1.1219    raeburn  4839:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4840:                     if (!$nothide{$username.':'.$domain}) {
                   4841:                         next;
                   4842:                     }
                   4843:                 }
1.937     raeburn  4844:             }
                   4845:         }
1.933     raeburn  4846:         if ($withsec) {
                   4847:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4848:                 $tstart.':'.$tend;
                   4849:         } else {
                   4850:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4851:         }
1.832     raeburn  4852:     }
1.373     www      4853:     return %returnhash;
1.399     www      4854: }
                   4855: 
1.1333    raeburn  4856: sub get_all_adhocroles {
                   4857:     my ($dom) = @_;
                   4858:     my @roles_by_num = ();
                   4859:     my %domdefaults = &get_domain_defaults($dom);
                   4860:     my (%description,%access_in_dom,%access_info);
                   4861:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4862:         my $count = 0;
                   4863:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4864:         my %ordered;
                   4865:         foreach my $role (sort(keys(%domcurrent))) {
                   4866:             my ($order,$desc,$access_in_dom);
                   4867:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4868:                 $order = $domcurrent{$role}{'order'};
                   4869:                 $desc = $domcurrent{$role}{'desc'};
                   4870:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4871:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4872:             }
                   4873:             if ($order eq '') {
                   4874:                 $order = $count;
                   4875:             }
                   4876:             $ordered{$order} = $role;
                   4877:             if ($desc ne '') {
                   4878:                 $description{$role} = $desc;
                   4879:             } else {
                   4880:                 $description{$role}= $role;
                   4881:             }
                   4882:             $count++;
                   4883:         }
                   4884:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4885:             push(@roles_by_num,$ordered{$item});
                   4886:         }
                   4887:     }
                   4888:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4889: }
                   4890: 
1.1332    raeburn  4891: sub get_my_adhocroles {
1.1333    raeburn  4892:     my ($cid,$checkreg) = @_;
                   4893:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4894:     if ($env{'request.course.id'} eq $cid) {
                   4895:         $cdom = $env{'course.'.$cid.'.domain'};
                   4896:         $cnum = $env{'course.'.$cid.'.num'};
                   4897:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4898:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4899:         $cdom = $1;
                   4900:         $cnum = $2;
                   4901:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4902:                                      $cdom,$cnum);
                   4903:     }
                   4904:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4905:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4906:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4907:         if ($rosterhash{$user} ne '') {
                   4908:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4909:             return ([],{}) if ($type eq 'auto');
                   4910:         }
                   4911:     }
                   4912:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4913:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4914:             my $then=$env{'user.login.time'};
                   4915:             my $update=$env{'user.update.time'};
1.1335    raeburn  4916:             if (!$update) {
                   4917:                 $update = $then;
                   4918:             }
                   4919:             my @liveroles;
1.1334    raeburn  4920:             foreach my $role ('dh','da') {
                   4921:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4922:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4923:                     my $limit = $update;
                   4924:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4925:                         $limit = $then;
                   4926:                     }
1.1335    raeburn  4927:                     my $activerole = 1;
                   4928:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4929:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4930:                     if ($activerole) {
                   4931:                         push(@liveroles,$role);
                   4932:                     }
1.1334    raeburn  4933:                 }
1.1332    raeburn  4934:             }
1.1335    raeburn  4935:             if (@liveroles) {
1.1332    raeburn  4936:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4937:                     my ($accessref,$accessinfo,%access_in_dom);
                   4938:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4939:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4940:                         if (@{$roles_by_num}) {
1.1332    raeburn  4941:                             my %settings;
                   4942:                             if ($env{'request.course.id'} eq $cid) {
                   4943:                                 foreach my $envkey (keys(%env)) {
                   4944:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4945:                                         $settings{$1} = $env{$envkey};
                   4946:                                     }
                   4947:                                 }
                   4948:                             } else {
                   4949:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4950:                             }
                   4951:                             my %setincrs;
                   4952:                             if ($settings{'internal.adhocaccess'}) {
                   4953:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4954:                             }
                   4955:                             my @statuses;
                   4956:                             if ($env{'environment.inststatus'}) {
                   4957:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4958:                             }
                   4959:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4960:                             if (ref($accessref) eq 'HASH') {
                   4961:                                 %access_in_dom = %{$accessref};
                   4962:                             }
                   4963:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4964:                                 my ($curraccess,@okstatus,@personnel);
                   4965:                                 if ($setincrs{$role}) {
                   4966:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4967:                                     if ($curraccess eq 'status') {
                   4968:                                         @okstatus = split(/\&/,$rest);
                   4969:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4970:                                         @personnel = split(/\&/,$rest);
                   4971:                                     }
                   4972:                                 } else {
                   4973:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4974:                                     if (ref($accessinfo) eq 'HASH') {
                   4975:                                         if ($curraccess eq 'status') {
                   4976:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4977:                                                 @okstatus = @{$accessinfo->{$role}};
                   4978:                                             }
                   4979:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4980:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4981:                                                 @personnel = @{$accessinfo->{$role}};
                   4982:                                             }
1.1332    raeburn  4983:                                         }
                   4984:                                     }
                   4985:                                 }
                   4986:                                 if ($curraccess eq 'none') {
                   4987:                                     next;
                   4988:                                 } elsif ($curraccess eq 'all') {
                   4989:                                     push(@possroles,$role);
1.1336    raeburn  4990:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4991:                                     if (grep(/^dh$/,@liveroles)) {
                   4992:                                         push(@possroles,$role);
                   4993:                                     } else {
                   4994:                                         next;
                   4995:                                     }
1.1336    raeburn  4996:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4997:                                     if (grep(/^da$/,@liveroles)) {
                   4998:                                         push(@possroles,$role);
                   4999:                                     } else {
                   5000:                                         next;
                   5001:                                     }
1.1332    raeburn  5002:                                 } elsif ($curraccess eq 'status') {
                   5003:                                     if (@okstatus) {
                   5004:                                         if (!@statuses) {
                   5005:                                             if (grep(/^default$/,@okstatus)) {
                   5006:                                                 push(@possroles,$role);
                   5007:                                             }
                   5008:                                         } else {
                   5009:                                             foreach my $status (@okstatus) {
                   5010:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5011:                                                     push(@possroles,$role);
                   5012:                                                     last;
                   5013:                                                 }
                   5014:                                             }
                   5015:                                         }
                   5016:                                     }
                   5017:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5018:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5019:                                         if ($curraccess eq 'exc') {
                   5020:                                             push(@possroles,$role);
                   5021:                                         }
                   5022:                                     } elsif ($curraccess eq 'inc') {
                   5023:                                         push(@possroles,$role);
                   5024:                                     }
                   5025:                                 }
                   5026:                             }
                   5027:                         }
                   5028:                     }
                   5029:                 }
                   5030:             }
                   5031:         }
                   5032:     }
1.1333    raeburn  5033:     unless (ref($description) eq 'HASH') {
                   5034:         if (ref($roles_by_num) eq 'ARRAY') {
                   5035:             my %desc;
                   5036:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5037:             $description = \%desc;
                   5038:         } else {
                   5039:             $description = {};
                   5040:         }
                   5041:     }
                   5042:     return (\@possroles,$description);
1.1332    raeburn  5043: }
                   5044: 
1.399     www      5045: # ----------------------------------------------------- Frontpage Announcements
                   5046: #
                   5047: #
                   5048: 
                   5049: sub postannounce {
                   5050:     my ($server,$text)=@_;
1.844     albertel 5051:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5052:     unless ($text=~/\w/) { $text=''; }
                   5053:     return &reply('setannounce:'.&escape($text),$server);
                   5054: }
                   5055: 
                   5056: sub getannounce {
1.448     albertel 5057: 
1.1359    raeburn  5058:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5059: 	my $announcement='';
1.800     albertel 5060: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5061: 	close($fh);
1.399     www      5062: 	if ($announcement=~/\w/) { 
                   5063: 	    return 
                   5064:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5065:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5066: 	} else {
                   5067: 	    return '';
                   5068: 	}
                   5069:     } else {
                   5070: 	return '';
                   5071:     }
1.351     www      5072: }
1.353     www      5073: 
                   5074: # ---------------------------------------------------------- Course ID routines
                   5075: # Deal with domain's nohist_courseid.db files
                   5076: #
                   5077: 
                   5078: sub courseidput {
1.921     raeburn  5079:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5080:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5081:     my $outcome;
                   5082:     if ($caller eq 'timeonly') {
                   5083:         my $cids = '';
                   5084:         foreach my $item (keys(%$storehash)) {
                   5085:             $cids.=&escape($item).'&';
                   5086:         }
                   5087:         $cids=~s/\&$//;
                   5088:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5089:                           $coursehome);       
                   5090:     } else {
                   5091:         my $items = '';
                   5092:         foreach my $item (keys(%$storehash)) {
                   5093:             $items.= &escape($item).'='.
                   5094:                      &freeze_escape($$storehash{$item}).'&';
                   5095:         }
                   5096:         $items=~s/\&$//;
                   5097:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5098:                           $coursehome);
1.918     raeburn  5099:     }
                   5100:     if ($outcome eq 'unknown_cmd') {
                   5101:         my $what;
                   5102:         foreach my $cid (keys(%$storehash)) {
                   5103:             $what .= &escape($cid).'=';
1.921     raeburn  5104:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5105:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5106:             }
                   5107:             $what =~ s/\:$/&/;
                   5108:         }
                   5109:         $what =~ s/\&$//;  
                   5110:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5111:     } else {
                   5112:         return $outcome;
                   5113:     }
1.353     www      5114: }
                   5115: 
                   5116: sub courseiddump {
1.921     raeburn  5117:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5118:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5119:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5120:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5121:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5122:     my $as_hash = 1;
                   5123:     my %returnhash;
                   5124:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5125:     my %libserv = &all_library();
                   5126:     foreach my $tryserver (keys(%libserv)) {
                   5127:         if ( (  $hostidflag == 1 
                   5128: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5129: 	     || (!defined($hostidflag)) ) {
                   5130: 
1.918     raeburn  5131: 	    if (($domfilter eq '') ||
                   5132: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5133:                 my $rep;
                   5134:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5135:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5136:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5137:                                 &escape($descfilter), &escape($instcodefilter), 
                   5138:                                 &escape($ownerfilter), &escape($coursefilter),
                   5139:                                 &escape($typefilter), &escape($regexp_ok), 
                   5140:                                 $as_hash, &escape($selfenrollonly), 
                   5141:                                 &escape($catfilter), $showhidden, $caller, 
                   5142:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5143:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5144:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5145:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5146:                 } else {
                   5147:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5148:                              $sincefilter.':'.&escape($descfilter).':'.
                   5149:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5150:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5151:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5152:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5153:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5154:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5155:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5156:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5157:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5158:                 }
                   5159:                      
1.918     raeburn  5160:                 my @pairs=split(/\&/,$rep);
                   5161:                 foreach my $item (@pairs) {
                   5162:                     my ($key,$value)=split(/\=/,$item,2);
                   5163:                     $key = &unescape($key);
                   5164:                     next if ($key =~ /^error: 2 /);
                   5165:                     my $result = &thaw_unescape($value);
                   5166:                     if (ref($result) eq 'HASH') {
                   5167:                         $returnhash{$key}=$result;
                   5168:                     } else {
1.921     raeburn  5169:                         my @responses = split(/:/,$value);
                   5170:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5171:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5172:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5173:                         }
1.1008    raeburn  5174:                     }
1.353     www      5175:                 }
                   5176:             }
                   5177:         }
                   5178:     }
                   5179:     return %returnhash;
                   5180: }
                   5181: 
1.1055    raeburn  5182: sub courselastaccess {
                   5183:     my ($cdom,$cnum,$hostidref) = @_;
                   5184:     my %returnhash;
                   5185:     if ($cdom && $cnum) {
                   5186:         my $chome = &homeserver($cnum,$cdom);
                   5187:         if ($chome ne 'no_host') {
                   5188:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5189:             &extract_lastaccess(\%returnhash,$rep);
                   5190:         }
                   5191:     } else {
                   5192:         if (!$cdom) { $cdom=''; }
                   5193:         my %libserv = &all_library();
                   5194:         foreach my $tryserver (keys(%libserv)) {
                   5195:             if (ref($hostidref) eq 'ARRAY') {
                   5196:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5197:             } 
                   5198:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5199:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5200:                 &extract_lastaccess(\%returnhash,$rep);
                   5201:             }
                   5202:         }
                   5203:     }
                   5204:     return %returnhash;
                   5205: }
                   5206: 
                   5207: sub extract_lastaccess {
                   5208:     my ($returnhash,$rep) = @_;
                   5209:     if (ref($returnhash) eq 'HASH') {
                   5210:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5211:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5212:                  $rep eq '') {
                   5213:             my @pairs=split(/\&/,$rep);
                   5214:             foreach my $item (@pairs) {
                   5215:                 my ($key,$value)=split(/\=/,$item,2);
                   5216:                 $key = &unescape($key);
                   5217:                 next if ($key =~ /^error: 2 /);
                   5218:                 $returnhash->{$key} = &thaw_unescape($value);
                   5219:             }
                   5220:         }
                   5221:     }
                   5222:     return;
                   5223: }
                   5224: 
1.658     raeburn  5225: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5226: 
                   5227: sub dcmailput {
1.685     raeburn  5228:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5229:     my $status = &Apache::lonnet::critical(
1.740     www      5230:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5231:        &escape($message),$server);
1.662     raeburn  5232:     return $status;
                   5233: }
                   5234: 
1.658     raeburn  5235: sub dcmaildump {
                   5236:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5237:     my %returnhash=();
1.846     albertel 5238: 
                   5239:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5240:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5241:                                                          &escape($enddate).':';
                   5242: 	my @esc_senders=map { &escape($_)} @$senders;
                   5243: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5244: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5245:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5246:             if (($key) && ($value)) {
                   5247:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5248:             }
                   5249:         }
                   5250:     }
                   5251:     return %returnhash;
                   5252: }
1.662     raeburn  5253: # ---------------------------------------------------------- Domain roles
                   5254: 
                   5255: sub get_domain_roles {
                   5256:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5257:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5258:         $startdate = '.';
                   5259:     }
1.1018    raeburn  5260:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5261:         $enddate = '.';
                   5262:     }
1.922     raeburn  5263:     my $rolelist;
                   5264:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5265:         $rolelist = join('&',@{$roles});
1.922     raeburn  5266:     }
1.662     raeburn  5267:     my %personnel = ();
1.841     albertel 5268: 
                   5269:     my %servers = &get_servers($dom,'library');
                   5270:     foreach my $tryserver (keys(%servers)) {
                   5271: 	%{$personnel{$tryserver}}=();
                   5272: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5273: 					    &escape($startdate).':'.
                   5274: 					    &escape($enddate).':'.
                   5275: 					    &escape($rolelist), $tryserver))) {
                   5276: 	    my ($key,$value) = split(/\=/,$line,2);
                   5277: 	    if (($key) && ($value)) {
                   5278: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5279: 	    }
                   5280: 	}
1.662     raeburn  5281:     }
                   5282:     return %personnel;
                   5283: }
1.658     raeburn  5284: 
1.1332    raeburn  5285: sub get_active_domroles {
                   5286:     my ($dom,$roles) = @_;
                   5287:     return () unless (ref($roles) eq 'ARRAY');
                   5288:     my $now = time;
                   5289:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5290:     my %domroles;
                   5291:     foreach my $server (keys(%dompersonnel)) {
                   5292:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5293:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5294:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5295:         }
                   5296:     }
                   5297:     return %domroles;
                   5298: }
                   5299: 
1.1057    www      5300: # ----------------------------------------------------------- Interval timing 
1.149     www      5301: 
1.1153    www      5302: {
                   5303: # Caches needed for speedup of navmaps
                   5304: # We don't want to cache this for very long at all (5 seconds at most)
                   5305: # 
                   5306: # The user for whom we cache
                   5307: my $cachedkey='';
                   5308: # The cached times for this user
                   5309: my %cachedtimes=();
                   5310: # When this was last done
1.1282    raeburn  5311: my $cachedtime='';
1.1153    www      5312: 
                   5313: sub load_all_first_access {
1.1308    raeburn  5314:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5315:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5316:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5317:         (!$ignorecache)) {
1.1154    raeburn  5318:         return;
                   5319:     }
                   5320:     $cachedtime=time;
                   5321:     $cachedkey=$uname.':'.$udom;
                   5322:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5323: }
                   5324: 
1.504     albertel 5325: sub get_first_access {
1.1308    raeburn  5326:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5327:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5328:     if ($argsymb) { $symb=$argsymb; }
                   5329:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5330:     if ($argmap) { $map = $argmap; }
1.926     albertel 5331:     if ($type eq 'course') {
                   5332: 	$res='course';
                   5333:     } elsif ($type eq 'map') {
1.588     albertel 5334: 	$res=&symbread($map);
                   5335:     } else {
                   5336: 	$res=$symb;
                   5337:     }
1.1308    raeburn  5338:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5339:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5340: }
                   5341: 
                   5342: sub set_first_access {
1.1162    raeburn  5343:     my ($type,$interval)=@_;
1.790     albertel 5344:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5345:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5346:     if ($type eq 'course') {
                   5347: 	$res='course';
                   5348:     } elsif ($type eq 'map') {
1.588     albertel 5349: 	$res=&symbread($map);
                   5350:     } else {
                   5351: 	$res=$symb;
                   5352:     }
1.1153    www      5353:     $cachedkey='';
1.1162    raeburn  5354:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5355:     if ($firstaccess) {
                   5356:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5357:                  "to set new value (type: $type, extent: $res) for $uname:$udom ". 
                   5358:                  "in $courseid"); 
                   5359:         return 'already_set';
                   5360:     } else {
1.1162    raeburn  5361:         my $start = time;
                   5362: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5363:                           $udom,$uname);
                   5364:         if ($putres eq 'ok') {
                   5365:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5366:                  $udom,$uname); 
                   5367:             &appenv(
                   5368:                      {
                   5369:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5370:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5371:                      }
                   5372:                   );
1.1365    raeburn  5373:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5374:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5375:             }
1.1386    raeburn  5376:         } elsif ($putres ne 'refused') {
                   5377:             &logthis("Result: $putres when attempting to set first access time ".
                   5378:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5379:         }
                   5380:         return $putres;
1.505     albertel 5381:     }
                   5382:     return 'already_set';
1.504     albertel 5383: }
1.1153    www      5384: }
1.1282    raeburn  5385: 
1.110     www      5386: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5387: 
                   5388: sub expirespread {
                   5389:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5390:     my $cid=$env{'request.course.id'}; 
1.110     www      5391:     if ($cid) {
                   5392:        my $now=time;
                   5393:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5394:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5395:                             $env{'course.'.$cid.'.num'}.
1.110     www      5396: 	        	    ':nohist_expirationdates:'.
                   5397:                             &escape($key).'='.$now,
1.620     albertel 5398:                             $env{'course.'.$cid.'.home'})
1.110     www      5399:     }
                   5400:     return 'ok';
1.14      www      5401: }
                   5402: 
1.109     www      5403: # ----------------------------------------------------- Devalidate Spreadsheets
                   5404: 
                   5405: sub devalidate {
1.325     www      5406:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5407:     my $cid=$env{'request.course.id'}; 
1.109     www      5408:     if ($cid) {
1.391     matthew  5409:         # delete the stored spreadsheets for
                   5410:         # - the student level sheet of this user in course's homespace
                   5411:         # - the assessment level sheet for this resource 
                   5412:         #   for this user in user's homespace
1.553     albertel 5413: 	# - current conditional state info
1.325     www      5414: 	my $key=$uname.':'.$udom.':';
1.109     www      5415:         my $status=
1.299     matthew  5416: 	    &del('nohist_calculatedsheets',
1.391     matthew  5417: 		 [$key.'studentcalc:'],
1.620     albertel 5418: 		 $env{'course.'.$cid.'.domain'},
                   5419: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5420: 		.' '.
                   5421: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5422: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5423:         unless ($status eq 'ok ok') {
                   5424:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5425:                     $uname.' at '.$udom.' for '.
1.109     www      5426: 		    $symb.': '.$status);
1.133     albertel 5427:         }
1.553     albertel 5428: 	&delenv('user.state.'.$cid);
1.109     www      5429:     }
                   5430: }
                   5431: 
1.265     albertel 5432: sub get_scalar {
                   5433:     my ($string,$end) = @_;
                   5434:     my $value;
                   5435:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5436: 	$value = $1;
                   5437:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5438: 	$value = $1;
                   5439:     }
                   5440:     return &unescape($value);
                   5441: }
                   5442: 
                   5443: sub array2str {
                   5444:   my (@array) = @_;
                   5445:   my $result=&arrayref2str(\@array);
                   5446:   $result=~s/^__ARRAY_REF__//;
                   5447:   $result=~s/__END_ARRAY_REF__$//;
                   5448:   return $result;
                   5449: }
                   5450: 
1.204     albertel 5451: sub arrayref2str {
                   5452:   my ($arrayref) = @_;
1.265     albertel 5453:   my $result='__ARRAY_REF__';
1.204     albertel 5454:   foreach my $elem (@$arrayref) {
1.265     albertel 5455:     if(ref($elem) eq 'ARRAY') {
                   5456:       $result.=&arrayref2str($elem).'&';
                   5457:     } elsif(ref($elem) eq 'HASH') {
                   5458:       $result.=&hashref2str($elem).'&';
                   5459:     } elsif(ref($elem)) {
                   5460:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5461:     } else {
                   5462:       $result.=&escape($elem).'&';
                   5463:     }
                   5464:   }
                   5465:   $result=~s/\&$//;
1.265     albertel 5466:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5467:   return $result;
                   5468: }
                   5469: 
1.168     albertel 5470: sub hash2str {
1.204     albertel 5471:   my (%hash) = @_;
                   5472:   my $result=&hashref2str(\%hash);
1.265     albertel 5473:   $result=~s/^__HASH_REF__//;
                   5474:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5475:   return $result;
                   5476: }
                   5477: 
                   5478: sub hashref2str {
                   5479:   my ($hashref)=@_;
1.265     albertel 5480:   my $result='__HASH_REF__';
1.800     albertel 5481:   foreach my $key (sort(keys(%$hashref))) {
                   5482:     if (ref($key) eq 'ARRAY') {
                   5483:       $result.=&arrayref2str($key).'=';
                   5484:     } elsif (ref($key) eq 'HASH') {
                   5485:       $result.=&hashref2str($key).'=';
                   5486:     } elsif (ref($key)) {
1.265     albertel 5487:       $result.='=';
1.800     albertel 5488:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5489:     } else {
1.1132    raeburn  5490: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5491:     }
                   5492: 
1.800     albertel 5493:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5494:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5495:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5496:       $result.=&hashref2str($hashref->{$key}).'&';
                   5497:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5498:        $result.='&';
1.800     albertel 5499:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5500:     } else {
1.800     albertel 5501:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5502:     }
                   5503:   }
1.168     albertel 5504:   $result=~s/\&$//;
1.265     albertel 5505:   $result .= '__END_HASH_REF__';
1.168     albertel 5506:   return $result;
                   5507: }
                   5508: 
                   5509: sub str2hash {
1.265     albertel 5510:     my ($string)=@_;
                   5511:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5512:     return %$hash;
                   5513: }
                   5514: 
                   5515: sub str2hashref {
1.168     albertel 5516:   my ($string) = @_;
1.265     albertel 5517: 
                   5518:   my %hash;
                   5519: 
                   5520:   if($string !~ /^__HASH_REF__/) {
                   5521:       if (! ($string eq '' || !defined($string))) {
                   5522: 	  $hash{'error'}='Not hash reference';
                   5523:       }
                   5524:       return (\%hash, $string);
                   5525:   }
                   5526: 
                   5527:   $string =~ s/^__HASH_REF__//;
                   5528: 
                   5529:   while($string !~ /^__END_HASH_REF__/) {
                   5530:       #key
                   5531:       my $key='';
                   5532:       if($string =~ /^__HASH_REF__/) {
                   5533:           ($key, $string)=&str2hashref($string);
                   5534:           if(defined($key->{'error'})) {
                   5535:               $hash{'error'}='Bad data';
                   5536:               return (\%hash, $string);
                   5537:           }
                   5538:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5539:           ($key, $string)=&str2arrayref($string);
                   5540:           if($key->[0] eq 'Array reference error') {
                   5541:               $hash{'error'}='Bad data';
                   5542:               return (\%hash, $string);
                   5543:           }
                   5544:       } else {
                   5545:           $string =~ s/^(.*?)=//;
1.267     albertel 5546: 	  $key=&unescape($1);
1.265     albertel 5547:       }
                   5548:       $string =~ s/^=//;
                   5549: 
                   5550:       #value
                   5551:       my $value='';
                   5552:       if($string =~ /^__HASH_REF__/) {
                   5553:           ($value, $string)=&str2hashref($string);
                   5554:           if(defined($value->{'error'})) {
                   5555:               $hash{'error'}='Bad data';
                   5556:               return (\%hash, $string);
                   5557:           }
                   5558:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5559:           ($value, $string)=&str2arrayref($string);
                   5560:           if($value->[0] eq 'Array reference error') {
                   5561:               $hash{'error'}='Bad data';
                   5562:               return (\%hash, $string);
                   5563:           }
                   5564:       } else {
                   5565: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5566:       }
                   5567:       $string =~ s/^&//;
                   5568: 
                   5569:       $hash{$key}=$value;
1.204     albertel 5570:   }
1.265     albertel 5571: 
                   5572:   $string =~ s/^__END_HASH_REF__//;
                   5573: 
                   5574:   return (\%hash, $string);
1.204     albertel 5575: }
                   5576: 
                   5577: sub str2array {
1.265     albertel 5578:     my ($string)=@_;
                   5579:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5580:     return @$array;
                   5581: }
                   5582: 
                   5583: sub str2arrayref {
1.204     albertel 5584:   my ($string) = @_;
1.265     albertel 5585:   my @array;
                   5586: 
                   5587:   if($string !~ /^__ARRAY_REF__/) {
                   5588:       if (! ($string eq '' || !defined($string))) {
                   5589: 	  $array[0]='Array reference error';
                   5590:       }
                   5591:       return (\@array, $string);
                   5592:   }
                   5593: 
                   5594:   $string =~ s/^__ARRAY_REF__//;
                   5595: 
                   5596:   while($string !~ /^__END_ARRAY_REF__/) {
                   5597:       my $value='';
                   5598:       if($string =~ /^__HASH_REF__/) {
                   5599:           ($value, $string)=&str2hashref($string);
                   5600:           if(defined($value->{'error'})) {
                   5601:               $array[0] ='Array reference error';
                   5602:               return (\@array, $string);
                   5603:           }
                   5604:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5605:           ($value, $string)=&str2arrayref($string);
                   5606:           if($value->[0] eq 'Array reference error') {
                   5607:               $array[0] ='Array reference error';
                   5608:               return (\@array, $string);
                   5609:           }
                   5610:       } else {
                   5611: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5612:       }
                   5613:       $string =~ s/^&//;
                   5614: 
                   5615:       push(@array, $value);
1.191     harris41 5616:   }
1.265     albertel 5617: 
                   5618:   $string =~ s/^__END_ARRAY_REF__//;
                   5619: 
                   5620:   return (\@array, $string);
1.168     albertel 5621: }
                   5622: 
1.167     albertel 5623: # -------------------------------------------------------------------Temp Store
                   5624: 
1.168     albertel 5625: sub tmpreset {
                   5626:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5627:   if (!$symb) {
                   5628:     $symb=&symbread();
1.620     albertel 5629:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5630:   }
                   5631:   $symb=escape($symb);
                   5632: 
1.620     albertel 5633:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5634:   $namespace=~s/\//\_/g;
                   5635:   $namespace=~s/\W//g;
                   5636: 
1.620     albertel 5637:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5638:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5639:   if ($domain eq 'public' && $stuname eq 'public') {
                   5640:       $stuname=$ENV{'REMOTE_ADDR'};
                   5641:   }
1.1117    foxr     5642:   my $path=LONCAPA::tempdir();
1.168     albertel 5643:   my %hash;
                   5644:   if (tie(%hash,'GDBM_File',
                   5645: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5646: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5647:     foreach my $key (keys(%hash)) {
1.180     albertel 5648:       if ($key=~ /:$symb/) {
1.168     albertel 5649: 	delete($hash{$key});
                   5650:       }
                   5651:     }
                   5652:   }
                   5653: }
                   5654: 
1.167     albertel 5655: sub tmpstore {
1.168     albertel 5656:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5657: 
                   5658:   if (!$symb) {
                   5659:     $symb=&symbread();
1.620     albertel 5660:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5661:   }
                   5662:   $symb=escape($symb);
                   5663: 
                   5664:   if (!$namespace) {
                   5665:     # I don't think we would ever want to store this for a course.
                   5666:     # it seems this will only be used if we don't have a course.
1.620     albertel 5667:     #$namespace=$env{'request.course.id'};
1.168     albertel 5668:     #if (!$namespace) {
1.620     albertel 5669:       $namespace=$env{'request.state'};
1.168     albertel 5670:     #}
                   5671:   }
                   5672:   $namespace=~s/\//\_/g;
                   5673:   $namespace=~s/\W//g;
1.620     albertel 5674:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5675:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5676:   if ($domain eq 'public' && $stuname eq 'public') {
                   5677:       $stuname=$ENV{'REMOTE_ADDR'};
                   5678:   }
1.168     albertel 5679:   my $now=time;
                   5680:   my %hash;
1.1117    foxr     5681:   my $path=LONCAPA::tempdir();
1.168     albertel 5682:   if (tie(%hash,'GDBM_File',
                   5683: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5684: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5685:     $hash{"version:$symb"}++;
                   5686:     my $version=$hash{"version:$symb"};
                   5687:     my $allkeys=''; 
                   5688:     foreach my $key (keys(%$storehash)) {
                   5689:       $allkeys.=$key.':';
1.591     albertel 5690:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5691:     }
                   5692:     $hash{"$version:$symb:timestamp"}=$now;
                   5693:     $allkeys.='timestamp';
                   5694:     $hash{"$version:keys:$symb"}=$allkeys;
                   5695:     if (untie(%hash)) {
                   5696:       return 'ok';
                   5697:     } else {
                   5698:       return "error:$!";
                   5699:     }
                   5700:   } else {
                   5701:     return "error:$!";
                   5702:   }
                   5703: }
1.167     albertel 5704: 
1.168     albertel 5705: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5706: 
1.168     albertel 5707: sub tmprestore {
                   5708:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5709: 
1.168     albertel 5710:   if (!$symb) {
                   5711:     $symb=&symbread();
1.620     albertel 5712:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5713:   }
                   5714:   $symb=escape($symb);
                   5715: 
1.620     albertel 5716:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5717: 
1.620     albertel 5718:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5719:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5720:   if ($domain eq 'public' && $stuname eq 'public') {
                   5721:       $stuname=$ENV{'REMOTE_ADDR'};
                   5722:   }
1.168     albertel 5723:   my %returnhash;
                   5724:   $namespace=~s/\//\_/g;
                   5725:   $namespace=~s/\W//g;
                   5726:   my %hash;
1.1117    foxr     5727:   my $path=LONCAPA::tempdir();
1.168     albertel 5728:   if (tie(%hash,'GDBM_File',
                   5729: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5730: 	  &GDBM_READER(),0640)) {
1.168     albertel 5731:     my $version=$hash{"version:$symb"};
                   5732:     $returnhash{'version'}=$version;
                   5733:     my $scope;
                   5734:     for ($scope=1;$scope<=$version;$scope++) {
                   5735:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5736:       my @keys=split(/:/,$vkeys);
                   5737:       my $key;
                   5738:       $returnhash{"$scope:keys"}=$vkeys;
                   5739:       foreach $key (@keys) {
1.591     albertel 5740: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5741: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5742:       }
                   5743:     }
1.168     albertel 5744:     if (!(untie(%hash))) {
                   5745:       return "error:$!";
                   5746:     }
                   5747:   } else {
                   5748:     return "error:$!";
                   5749:   }
                   5750:   return %returnhash;
1.167     albertel 5751: }
                   5752: 
1.9       www      5753: # ----------------------------------------------------------------------- Store
                   5754: 
                   5755: sub store {
1.1269    raeburn  5756:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5757:     my $home='';
                   5758: 
1.168     albertel 5759:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5760: 
1.213     www      5761:     $symb=&symbclean($symb);
1.122     albertel 5762:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5763: 
1.620     albertel 5764:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5765:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5766: 
                   5767:     &devalidate($symb,$stuname,$domain);
1.109     www      5768: 
                   5769:     $symb=escape($symb);
1.187     www      5770:     if (!$namespace) { 
1.620     albertel 5771:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5772:           return ''; 
                   5773:        } 
                   5774:     }
1.620     albertel 5775:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5776: 
                   5777:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5778:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5779: 
1.12      www      5780:     my $namevalue='';
1.800     albertel 5781:     foreach my $key (keys(%$storehash)) {
                   5782:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5783:     }
1.12      www      5784:     $namevalue=~s/\&$//;
1.187     www      5785:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5786:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5787: }
                   5788: 
1.47      www      5789: # -------------------------------------------------------------- Critical Store
                   5790: 
                   5791: sub cstore {
1.1269    raeburn  5792:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5793:     my $home='';
                   5794: 
1.168     albertel 5795:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5796: 
1.213     www      5797:     $symb=&symbclean($symb);
1.122     albertel 5798:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5799: 
1.620     albertel 5800:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5801:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5802: 
                   5803:     &devalidate($symb,$stuname,$domain);
1.109     www      5804: 
                   5805:     $symb=escape($symb);
1.187     www      5806:     if (!$namespace) { 
1.620     albertel 5807:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5808:           return ''; 
                   5809:        } 
                   5810:     }
1.620     albertel 5811:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5812: 
                   5813:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5814:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5815: 
1.47      www      5816:     my $namevalue='';
1.800     albertel 5817:     foreach my $key (keys(%$storehash)) {
                   5818:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5819:     }
1.47      www      5820:     $namevalue=~s/\&$//;
1.187     www      5821:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5822:     return critical
1.1269    raeburn  5823:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5824: }
                   5825: 
1.9       www      5826: # --------------------------------------------------------------------- Restore
                   5827: 
                   5828: sub restore {
1.124     www      5829:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5830:     my $home='';
                   5831: 
1.168     albertel 5832:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5833: 
1.122     albertel 5834:     if (!$symb) {
1.1224    raeburn  5835:         return if ($namespace eq 'courserequests');
                   5836:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5837:     } else {
1.1224    raeburn  5838:         unless ($namespace eq 'courserequests') {
                   5839:             $symb=&escape(&symbclean($symb));
                   5840:         }
1.122     albertel 5841:     }
1.188     www      5842:     if (!$namespace) { 
1.620     albertel 5843:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5844:           return ''; 
                   5845:        } 
                   5846:     }
1.620     albertel 5847:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5848:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5849:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5850:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5851: 
1.12      www      5852:     my %returnhash=();
1.800     albertel 5853:     foreach my $line (split(/\&/,$answer)) {
                   5854: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5855:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5856:     }
1.75      www      5857:     my $version;
                   5858:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5859:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5860:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5861:        }
1.75      www      5862:     }
1.13      www      5863:     return %returnhash;
1.34      www      5864: }
                   5865: 
                   5866: # ---------------------------------------------------------- Course Description
1.1118    foxr     5867: #
                   5868: #  
1.34      www      5869: 
                   5870: sub coursedescription {
1.731     albertel 5871:     my ($courseid,$args)=@_;
1.34      www      5872:     $courseid=~s/^\///;
1.49      www      5873:     $courseid=~s/\_/\//g;
1.34      www      5874:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5875:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5876:     my $normalid=$cdomain.'_'.$cnum;
                   5877:     # need to always cache even if we get errors otherwise we keep 
                   5878:     # trying and trying and trying to get the course description.
                   5879:     my %envhash=();
                   5880:     my %returnhash=();
1.731     albertel 5881:     
                   5882:     my $expiretime=600;
                   5883:     if ($env{'request.course.id'} eq $normalid) {
                   5884: 	$expiretime=120;
                   5885:     }
                   5886: 
                   5887:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5888:     if (!$args->{'freshen_cache'}
                   5889: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5890: 	foreach my $key (keys(%env)) {
                   5891: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5892: 	    my ($setting) = $1;
                   5893: 	    $returnhash{$setting} = $env{$key};
                   5894: 	}
                   5895: 	return %returnhash;
                   5896:     }
                   5897: 
1.1118    foxr     5898:     # get the data again
                   5899: 
1.731     albertel 5900:     if (!$args->{'one_time'}) {
                   5901: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5902:     }
1.811     albertel 5903: 
1.34      www      5904:     if ($chome ne 'no_host') {
1.302     albertel 5905:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5906:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5907: 	   my $username = $env{'user.name'}; # Defult username
                   5908: 	   if(defined $args->{'user'}) {
                   5909: 	       $username = $args->{'user'};
                   5910: 	   }
1.129     albertel 5911:            $returnhash{'home'}= $chome;
                   5912: 	   $returnhash{'domain'} = $cdomain;
                   5913: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5914:            if (!defined($returnhash{'type'})) {
                   5915:                $returnhash{'type'} = 'Course';
                   5916:            }
1.130     albertel 5917:            while (my ($name,$value) = each %returnhash) {
1.53      www      5918:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5919:            }
1.270     www      5920:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5921:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5922: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5923:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5924:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5925:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5926:        }
                   5927:     }
1.731     albertel 5928:     if (!$args->{'one_time'}) {
1.949     raeburn  5929: 	&appenv(\%envhash);
1.731     albertel 5930:     }
1.302     albertel 5931:     return %returnhash;
1.461     www      5932: }
                   5933: 
1.1080    raeburn  5934: sub update_released_required {
                   5935:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5936:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5937:         $cid = $env{'request.course.id'};
                   5938:         $cdom = $env{'course.'.$cid.'.domain'};
                   5939:         $cnum = $env{'course.'.$cid.'.num'};
                   5940:         $chome = $env{'course.'.$cid.'.home'};
                   5941:     }
                   5942:     if ($needsrelease) {
                   5943:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5944:         my $needsupdate;
                   5945:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5946:             $needsupdate = 1;
                   5947:         } else {
                   5948:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5949:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5950:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5951:                 $needsupdate = 1;
                   5952:             }
                   5953:         }
                   5954:         if ($needsupdate) {
                   5955:             my %needshash = (
                   5956:                              'internal.releaserequired' => $needsrelease,
                   5957:                             );
                   5958:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5959:             if ($putresult eq 'ok') {
                   5960:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5961:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5962:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5963:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5964:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5965:                 }
                   5966:             }
                   5967:         }
                   5968:     }
                   5969:     return;
                   5970: }
                   5971: 
1.461     www      5972: # -------------------------------------------------See if a user is privileged
                   5973: 
                   5974: sub privileged {
1.1219    raeburn  5975:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5976:     my $now = time;
1.1219    raeburn  5977:     my $roles;
                   5978:     if (ref($possroles) eq 'ARRAY') {
                   5979:         $roles = $possroles; 
                   5980:     } else {
                   5981:         $roles = ['dc','su'];
                   5982:     }
                   5983:     if (ref($possdomains) eq 'ARRAY') {
                   5984:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5985:         foreach my $dom (@{$possdomains}) {
                   5986:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5987:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5988:                 foreach my $role (@{$roles}) {
                   5989:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5990:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5991:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5992:                             return 1 unless (($end && $end < $now) ||
                   5993:                                              ($start && $start > $now));
                   5994:                         }
                   5995:                     }
                   5996:                 }
                   5997:             }
                   5998:         }
                   5999:     } else {
                   6000:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6001:         my $now = time;
1.1170    droeschl 6002: 
1.1275    musolffc 6003:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6004:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6005:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6006:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6007:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6008:             }
1.1219    raeburn  6009:         }
                   6010:     }
                   6011:     return 0;
                   6012: }
1.1170    droeschl 6013: 
1.1219    raeburn  6014: sub privileged_by_domain {
                   6015:     my ($domains,$roles) = @_;
                   6016:     my %privileged = ();
                   6017:     my $cachetime = 60*60*24;
                   6018:     my $now = time;
                   6019:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6020:         return %privileged;
                   6021:     }
                   6022:     foreach my $dom (@{$domains}) {
                   6023:         next if (ref($privileged{$dom}) eq 'HASH');
                   6024:         my $needroles;
                   6025:         foreach my $role (@{$roles}) {
                   6026:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6027:             if (defined($cached)) {
                   6028:                 if (ref($result) eq 'HASH') {
                   6029:                     $privileged{$dom}{$role} = $result;
                   6030:                 }
                   6031:             } else {
                   6032:                 $needroles = 1;
                   6033:             }
                   6034:         }
                   6035:         if ($needroles) {
                   6036:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6037:             $privileged{$dom} = {};
                   6038:             foreach my $server (keys(%dompersonnel)) {
                   6039:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6040:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6041:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6042:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6043:                         next if ($end && $end < $now);
                   6044:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6045:                             $dompersonnel{$server}{$item};
                   6046:                     }
                   6047:                 }
                   6048:             }
                   6049:             if (ref($privileged{$dom}) eq 'HASH') {
                   6050:                 foreach my $role (@{$roles}) {
                   6051:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6052:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6053:                     } else {
                   6054:                         my %hash = ();
                   6055:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6056:                     }
                   6057:                 }
                   6058:             }
                   6059:         }
                   6060:     }
                   6061:     return %privileged;
1.9       www      6062: }
1.1       albertel 6063: 
1.103     harris41 6064: # -------------------------------------------------------- Get user privileges
1.11      www      6065: 
                   6066: sub rolesinit {
1.1169    droeschl 6067:     my ($domain, $username) = @_;
                   6068:     my %userroles = ('user.login.time' => time);
                   6069:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6070: 
                   6071:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6072:     # also, blocking can be triggered by an activating timer
                   6073:     # it's saved in the user's %env.
                   6074:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6075:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6076:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6077:         %timerintchk, %timerintenv);
                   6078: 
1.1162    raeburn  6079:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6080:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6081:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6082:     }
1.1169    droeschl 6083: 
1.1162    raeburn  6084:     foreach my $key (keys(%timerinterval)) {
                   6085:         my ($cid,$rest) = split(/\0/,$key);
                   6086:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6087:     }
1.1169    droeschl 6088: 
1.11      www      6089:     my %allroles=();
1.1162    raeburn  6090:     my %allgroups=();
1.11      www      6091: 
1.1274    raeburn  6092:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6093:         my $role = $rolesdump{$area};
                   6094:         $area =~ s/\_\w\w$//;
                   6095: 
                   6096:         my ($trole, $tend, $tstart, $group_privs);
                   6097: 
                   6098:         if ($role =~ /^cr/) {
                   6099:         # Custom role, defined by a user 
                   6100:         # e.g., user.role.cr/msu/smith/mynewrole
                   6101:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6102:                 $trole = $1;
                   6103:                 ($tend, $tstart) = split('_', $2);
                   6104:             } else {
                   6105:                 $trole = $role;
                   6106:             }
                   6107:         } elsif ($role =~ m|^gr/|) {
                   6108:         # Role of member in a group, defined within a course/community
                   6109:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6110:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6111:             next if $tstart eq '-1';
                   6112:             ($trole, $group_privs) = split(/\//, $trole);
                   6113:             $group_privs = &unescape($group_privs);
                   6114:         } else {
                   6115:         # Just a normal role, defined in roles.tab
                   6116:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6117:         }
                   6118: 
                   6119:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6120:                  $username);
                   6121:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6122: 
                   6123:         # role expired or not available yet?
                   6124:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6125:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6126: 
                   6127:         next if $area eq '' or $trole eq '';
                   6128: 
                   6129:         my $spec = "$trole.$area";
                   6130:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6131: 
                   6132:         if ($trole =~ /^cr\//) {
                   6133:         # Custom role, defined by a user
                   6134:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6135:         } elsif ($trole eq 'gr') {
                   6136:         # Role of a member in a group, defined within a course/community
                   6137:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6138:             next;
                   6139:         } else {
                   6140:         # Normal role, defined in roles.tab
                   6141:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6142:         }
                   6143: 
                   6144:         my $cid = $tdomain.'_'.$trest;
                   6145:         unless ($firstaccchk{$cid}) {
                   6146:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6147:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6148:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6149:                         $coursetimerstarts{$cid}{$item}; 
                   6150:                 }
                   6151:             }
                   6152:             $firstaccchk{$cid} = 1;
                   6153:         }
                   6154:         unless ($timerintchk{$cid}) {
                   6155:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6156:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6157:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6158:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6159:                 }
1.12      www      6160:             }
1.1169    droeschl 6161:             $timerintchk{$cid} = 1;
1.191     harris41 6162:         }
1.11      www      6163:     }
1.1169    droeschl 6164: 
1.1341    raeburn  6165:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6166:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6167:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6168:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6169: 
1.1162    raeburn  6170:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6171: }
                   6172: 
1.567     raeburn  6173: sub set_arearole {
1.1215    raeburn  6174:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6175:     unless ($nolog) {
1.567     raeburn  6176: # log the associated role with the area
1.1215    raeburn  6177:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6178:     }
1.743     albertel 6179:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6180: }
                   6181: 
                   6182: sub custom_roleprivs {
                   6183:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6184:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6185:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6186:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6187:         my ($rdummy,$roledef)=
                   6188:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6189:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6190:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6191:             if (defined($syspriv)) {
1.1043    raeburn  6192:                 if ($trest =~ /^$match_community$/) {
                   6193:                     $syspriv =~ s/bre\&S//; 
                   6194:                 }
1.567     raeburn  6195:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6196:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6197:             }
                   6198:             if ($tdomain ne '') {
                   6199:                 if (defined($dompriv)) {
                   6200:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6201:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6202:                 }
                   6203:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6204:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6205:                         my $rolename = $1;
                   6206:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6207:                     }
1.567     raeburn  6208:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6209:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6210:                 }
                   6211:             }
                   6212:         }
                   6213:     }
                   6214: }
                   6215: 
1.1332    raeburn  6216: sub course_adhocrole_privs {
                   6217:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6218:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6219:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6220:         my (%currprivs,%storeprivs);
                   6221:         foreach my $item (split(/:/,$coursepriv)) {
                   6222:             my ($priv,$restrict) = split(/\&/,$item);
                   6223:             $currprivs{$priv} = $restrict;
                   6224:         }
                   6225:         my (%possadd,%possremove,%full);
                   6226:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6227:             my ($priv,$restrict)=split(/\&/,$item);
                   6228:             $full{$priv} = $restrict;
                   6229:         }
                   6230:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6231:              next if ($item eq '');
                   6232:              my ($rule,$rest) = split(/=/,$item);
                   6233:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6234:              foreach my $priv (split(/:/,$rest)) {
                   6235:                  if ($priv ne '') {
                   6236:                      if ($rule eq 'off') {
                   6237:                          $possremove{$priv} = 1;
                   6238:                      } else {
                   6239:                          $possadd{$priv} = 1;
                   6240:                      }
                   6241:                  }
                   6242:              }
                   6243:          }
                   6244:          foreach my $priv (sort(keys(%full))) {
                   6245:              if (exists($currprivs{$priv})) {
                   6246:                  unless (exists($possremove{$priv})) {
                   6247:                      $storeprivs{$priv} = $currprivs{$priv};
                   6248:                  }
                   6249:              } elsif (exists($possadd{$priv})) {
                   6250:                  $storeprivs{$priv} = $full{$priv};
                   6251:              }
                   6252:          }
                   6253:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6254:      }
                   6255:      return $coursepriv;
                   6256: }
                   6257: 
1.678     raeburn  6258: sub group_roleprivs {
                   6259:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6260:     my $access = 1;
                   6261:     my $now = time;
                   6262:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6263:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6264:     if ($access) {
1.811     albertel 6265:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6266:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6267:     }
                   6268: }
1.567     raeburn  6269: 
                   6270: sub standard_roleprivs {
                   6271:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6272:     if (defined($pr{$trole.':s'})) {
                   6273:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6274:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6275:     }
                   6276:     if ($tdomain ne '') {
                   6277:         if (defined($pr{$trole.':d'})) {
                   6278:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6279:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6280:         }
                   6281:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6282:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6283:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6284:         }
                   6285:     }
                   6286: }
                   6287: 
                   6288: sub set_userprivs {
1.1064    raeburn  6289:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6290:     my $author=0;
                   6291:     my $adv=0;
1.1341    raeburn  6292:     my $rar=0;
1.678     raeburn  6293:     my %grouproles = ();
                   6294:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6295:         my @groupkeys; 
1.1000    raeburn  6296:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6297:             push(@groupkeys,$role);
                   6298:         }
                   6299:         if (ref($groups_roles) eq 'HASH') {
                   6300:             foreach my $key (keys(%{$groups_roles})) {
                   6301:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6302:                     push(@groupkeys,$key);
                   6303:                 }
                   6304:             }
                   6305:         }
                   6306:         if (@groupkeys > 0) {
                   6307:             foreach my $role (@groupkeys) {
                   6308:                 my ($trole,$area,$sec,$extendedarea);
                   6309:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6310:                     $trole = $1;
                   6311:                     $area = $2;
                   6312:                     $sec = $3;
                   6313:                     $extendedarea = $area.$sec;
                   6314:                     if (exists($$allgroups{$area})) {
                   6315:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6316:                             my $spec = $trole.'.'.$extendedarea;
                   6317:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6318:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6319:                         }
1.678     raeburn  6320:                     }
                   6321:                 }
                   6322:             }
                   6323:         }
                   6324:     }
1.800     albertel 6325:     foreach my $group (keys(%grouproles)) {
                   6326:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6327:     }
1.800     albertel 6328:     foreach my $role (keys(%{$allroles})) {
                   6329:         my %thesepriv;
1.941     raeburn  6330:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6331:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6332:             if ($item ne '') {
                   6333:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6334:                 if ($restrictions eq '') {
                   6335:                     $thesepriv{$privilege}='F';
                   6336:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6337:                     $thesepriv{$privilege}.=$restrictions;
                   6338:                 }
                   6339:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6340:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6341:             }
                   6342:         }
                   6343:         my $thesestr='';
1.1104    raeburn  6344:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6345: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6346: 	}
                   6347:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6348:     }
1.1341    raeburn  6349:     return ($author,$adv,$rar);
1.567     raeburn  6350: }
                   6351: 
1.994     raeburn  6352: sub role_status {
1.1104    raeburn  6353:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6354:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6355:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6356:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6357:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6358:             $$where = '/'.$two;
1.994     raeburn  6359:             $$trolecode=$$role.'.'.$$where;
                   6360:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6361:             $$tstatus='is';
1.1104    raeburn  6362:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6363:                 $$tstatus='future';
1.1034    raeburn  6364:                 if ($$tstart<$now) {
                   6365:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6366:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6367:                             my (%allroles,%allgroups,$group_privs,
                   6368:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6369:                             my %userroles = (
                   6370:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6371:                             );
1.1064    raeburn  6372:                             @rolecodes = ('cm'); 
1.1002    raeburn  6373:                             my $spec=$$role.'.'.$$where;
                   6374:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6375:                             if ($$role =~ /^cr\//) {
                   6376:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6377:                                 push(@rolecodes,'cr');
1.1002    raeburn  6378:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6379:                                 push(@rolecodes,$$role);
1.1002    raeburn  6380:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6381:                                                     $env{'user.name'});
1.1064    raeburn  6382:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6383:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6384:                                 $group_privs = &unescape($group_privs);
                   6385:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6386:                                 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  6387:                                 &get_groups_roles($tdomain,$trest,
                   6388:                                                   \%course_roles,\@rolecodes,
                   6389:                                                   \%groups_roles);
1.1002    raeburn  6390:                             } else {
1.1064    raeburn  6391:                                 push(@rolecodes,$$role);
1.1002    raeburn  6392:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6393:                             }
1.1341    raeburn  6394:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6395:                                                                    \%groups_roles);
1.1064    raeburn  6396:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6397:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6398:                         }
                   6399:                     }
1.1034    raeburn  6400:                     $$tstatus = 'is';
1.1002    raeburn  6401:                 }
1.994     raeburn  6402:             }
                   6403:             if ($$tend) {
1.1104    raeburn  6404:                 if ($$tend<$update) {
1.994     raeburn  6405:                     $$tstatus='expired';
                   6406:                 } elsif ($$tend<$now) {
                   6407:                     $$tstatus='will_not';
                   6408:                 }
                   6409:             }
                   6410:         }
                   6411:     }
                   6412: }
                   6413: 
1.1104    raeburn  6414: sub get_groups_roles {
                   6415:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6416:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6417:                   (ref($rolecodes) eq 'ARRAY') && 
                   6418:                   (ref($groups_roles) eq 'HASH')); 
                   6419:     if (keys(%{$cdom_courseroles}) > 0) {
                   6420:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6421:         if ($cdom ne '' && $cnum ne '') {
                   6422:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6423:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6424:                     my $crsrole = $1;
                   6425:                     my $crssec = $2;
                   6426:                     if ($crsrole =~ /^cr/) {
                   6427:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6428:                             push(@{$rolecodes},'cr');
                   6429:                         }
                   6430:                     } else {
                   6431:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6432:                             push(@{$rolecodes},$crsrole);
                   6433:                         }
                   6434:                     }
                   6435:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6436:                     if ($crssec ne '') {
                   6437:                         $rolekey .= "/$crssec";
                   6438:                     }
                   6439:                     $rolekey .= './';
                   6440:                     $groups_roles->{$rolekey} = $rolecodes;
                   6441:                 }
                   6442:             }
                   6443:         }
                   6444:     }
                   6445:     return;
                   6446: }
                   6447: 
                   6448: sub delete_env_groupprivs {
                   6449:     my ($where,$courseroles,$possroles) = @_;
                   6450:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6451:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6452:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6453:         %{$courseroles->{$udom}} =
                   6454:             &get_my_roles('','','userroles',['active'],
                   6455:                           $possroles,[$udom],1);
                   6456:     }
                   6457:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6458:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6459:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6460:             my $area = '/'.$cdom.'/'.$cnum;
                   6461:             my $privkey = "user.priv.$crsrole.$area";
                   6462:             if ($crssec ne '') {
                   6463:                 $privkey .= '/'.$crssec;
                   6464:             }
                   6465:             $privkey .= ".$area/$group";
                   6466:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6467:         }
                   6468:     }
                   6469:     return;
                   6470: }
                   6471: 
1.994     raeburn  6472: sub check_adhoc_privs {
1.1329    raeburn  6473:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6474:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6475:     if ($sec) {
                   6476:         $cckey .= '/'.$sec;
                   6477:     } 
1.1185    raeburn  6478:     my $setprivs;
1.994     raeburn  6479:     if ($env{$cckey}) {
                   6480:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6481:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6482:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6483:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6484:             $setprivs = 1;
1.994     raeburn  6485:         }
                   6486:     } else {
1.1330    raeburn  6487:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6488:         $setprivs = 1;
1.994     raeburn  6489:     }
1.1185    raeburn  6490:     return $setprivs;
1.994     raeburn  6491: }
                   6492: 
                   6493: sub set_adhoc_privileges {
1.1326    raeburn  6494: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6495:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6496:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6497:     if ($sec ne '') {
                   6498:         $area .= '/'.$sec;
                   6499:     }
1.994     raeburn  6500:     my $spec = $role.'.'.$area;
                   6501:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6502:                                   $env{'user.name'},1);
1.1326    raeburn  6503:     my %rolehash = ();
1.1332    raeburn  6504:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6505:         my $rolename = $1;
1.1326    raeburn  6506:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6507:         my %domdef = &get_domain_defaults($dcdom);
                   6508:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6509:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6510:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6511:             }
                   6512:         }
1.1326    raeburn  6513:     } else {
                   6514:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6515:     }
1.1341    raeburn  6516:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6517:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6518:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6519:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6520:         &appenv( {'request.role'        => $spec,
                   6521:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6522:                   'request.course.sec'  => $sec,
1.1088    raeburn  6523:                  }
                   6524:                );
                   6525:         my $tadv=0;
                   6526:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6527:         &appenv({'request.role.adv'    => $tadv});
                   6528:     }
1.994     raeburn  6529: }
                   6530: 
1.12      www      6531: # --------------------------------------------------------------- get interface
                   6532: 
                   6533: sub get {
1.131     albertel 6534:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6535:    my $items='';
1.800     albertel 6536:    foreach my $item (@$storearr) {
                   6537:        $items.=&escape($item).'&';
1.191     harris41 6538:    }
1.12      www      6539:    $items=~s/\&$//;
1.620     albertel 6540:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6541:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6542:    my $uhome=&homeserver($uname,$udomain);
                   6543: 
1.133     albertel 6544:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6545:    my @pairs=split(/\&/,$rep);
1.273     albertel 6546:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6547:      return @pairs;
                   6548:    }
1.15      www      6549:    my %returnhash=();
1.42      www      6550:    my $i=0;
1.800     albertel 6551:    foreach my $item (@$storearr) {
                   6552:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6553:       $i++;
1.191     harris41 6554:    }
1.15      www      6555:    return %returnhash;
1.27      www      6556: }
                   6557: 
                   6558: # --------------------------------------------------------------- del interface
                   6559: 
                   6560: sub del {
1.133     albertel 6561:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6562:    my $items='';
1.800     albertel 6563:    foreach my $item (@$storearr) {
                   6564:        $items.=&escape($item).'&';
1.191     harris41 6565:    }
1.984     neumanie 6566: 
1.27      www      6567:    $items=~s/\&$//;
1.620     albertel 6568:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6569:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6570:    my $uhome=&homeserver($uname,$udomain);
                   6571:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6572: }
                   6573: 
                   6574: # -------------------------------------------------------------- dump interface
                   6575: 
1.1180    droeschl 6576: sub unserialize {
                   6577:     my ($rep, $escapedkeys) = @_;
                   6578: 
                   6579:     return {} if $rep =~ /^error/;
                   6580: 
                   6581:     my %returnhash=();
1.1252    raeburn  6582: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6583: 	    my ($key, $value) = split(/=/, $item, 2);
                   6584: 	    $key = unescape($key) unless $escapedkeys;
                   6585: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6586: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6587: 	}
                   6588:     #return %returnhash;
                   6589:     return \%returnhash;
                   6590: }        
                   6591: 
                   6592: # see Lond::dump_with_regexp
                   6593: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6594: sub dump {
1.1180    droeschl 6595:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6596:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6597:     if (!$uname) { $uname=$env{'user.name'}; }
                   6598:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6599: 
1.1266    raeburn  6600:     if ($regexp) {
                   6601:         $regexp=&escape($regexp);
                   6602:     } else {
                   6603:         $regexp='.';
                   6604:     }
1.1180    droeschl 6605:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6606:         # user is hosted on this machine
1.1266    raeburn  6607:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6608:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6609:         return %{unserialize($reply, $escapedkeys)};
                   6610:     }
1.1166    raeburn  6611:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6612:     my @pairs=split(/\&/,$rep);
                   6613:     my %returnhash=();
1.1098    foxr     6614:     if (!($rep =~ /^error/ )) {
                   6615: 	foreach my $item (@pairs) {
                   6616: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6617:         $key = unescape($key) unless $escapedkeys;
                   6618:         #$key = &unescape($key);
1.1098    foxr     6619: 	    next if ($key =~ /^error: 2 /);
                   6620: 	    $returnhash{$key}=&thaw_unescape($value);
                   6621: 	}
1.755     albertel 6622:     }
                   6623:     return %returnhash;
1.407     www      6624: }
                   6625: 
1.1098    foxr     6626: 
1.717     albertel 6627: # --------------------------------------------------------- dumpstore interface
                   6628: 
                   6629: sub dumpstore {
                   6630:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6631:    # same as dump but keys must be escaped. They may contain colon separated
                   6632:    # lists of values that may themself contain colons (e.g. symbs).
                   6633:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6634: }
                   6635: 
1.407     www      6636: # -------------------------------------------------------------- keys interface
                   6637: 
                   6638: sub getkeys {
                   6639:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6640:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6641:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6642:    my $uhome=&homeserver($uname,$udomain);
                   6643:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6644:    my @keyarray=();
1.800     albertel 6645:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6646:       next if ($key =~ /^error: 2 /);
1.800     albertel 6647:       push(@keyarray,&unescape($key));
1.407     www      6648:    }
                   6649:    return @keyarray;
1.318     matthew  6650: }
                   6651: 
1.319     matthew  6652: # --------------------------------------------------------------- currentdump
                   6653: sub currentdump {
1.328     matthew  6654:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6655:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6656:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6657:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6658:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6659:    my $rep;
                   6660: 
                   6661:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6662:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6663:                    $courseid)));
                   6664:    } else {
                   6665:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6666:    }
                   6667: 
1.318     matthew  6668:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6669:    #
1.318     matthew  6670:    my %returnhash=();
1.319     matthew  6671:    #
1.1343    raeburn  6672:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6673:        # an old lond will not know currentdump
                   6674:        # Do a dump and make it look like a currentdump
1.822     albertel 6675:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6676:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6677:        my %hash = @tmp;
                   6678:        @tmp=();
1.424     matthew  6679:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6680:    } else {
                   6681:        my @pairs=split(/\&/,$rep);
1.800     albertel 6682:        foreach my $pair (@pairs) {
                   6683:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6684:            my ($symb,$param) = split(/:/,$key);
                   6685:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6686:                                                         &thaw_unescape($value);
1.319     matthew  6687:        }
1.191     harris41 6688:    }
1.12      www      6689:    return %returnhash;
1.424     matthew  6690: }
                   6691: 
                   6692: sub convert_dump_to_currentdump{
                   6693:     my %hash = %{shift()};
                   6694:     my %returnhash;
                   6695:     # Code ripped from lond, essentially.  The only difference
                   6696:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6697:     # we might run in to problems with parameter names =~ /^v\./
                   6698:     while (my ($key,$value) = each(%hash)) {
                   6699:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6700: 	$symb  = &unescape($symb);
                   6701: 	$param = &unescape($param);
1.424     matthew  6702:         next if ($v eq 'version' || $symb eq 'keys');
                   6703:         next if (exists($returnhash{$symb}) &&
                   6704:                  exists($returnhash{$symb}->{$param}) &&
                   6705:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6706:         $returnhash{$symb}->{$param}=$value;
                   6707:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6708:     }
                   6709:     #
                   6710:     # Remove all of the keys in the hashes which keep track of
                   6711:     # the version of the parameter.
                   6712:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6713:         # use a foreach because we are going to delete from the hash.
                   6714:         foreach my $key (keys(%$param_hash)) {
                   6715:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6716:         }
                   6717:     }
                   6718:     return \%returnhash;
1.12      www      6719: }
                   6720: 
1.627     albertel 6721: # ------------------------------------------------------ critical inc interface
                   6722: 
                   6723: sub cinc {
                   6724:     return &inc(@_,'critical');
                   6725: }
                   6726: 
1.449     matthew  6727: # --------------------------------------------------------------- inc interface
                   6728: 
                   6729: sub inc {
1.627     albertel 6730:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6731:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6732:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6733:     my $uhome=&homeserver($uname,$udomain);
                   6734:     my $items='';
                   6735:     if (! ref($store)) {
                   6736:         # got a single value, so use that instead
                   6737:         $items = &escape($store).'=&';
                   6738:     } elsif (ref($store) eq 'SCALAR') {
                   6739:         $items = &escape($$store).'=&';        
                   6740:     } elsif (ref($store) eq 'ARRAY') {
                   6741:         $items = join('=&',map {&escape($_);} @{$store});
                   6742:     } elsif (ref($store) eq 'HASH') {
                   6743:         while (my($key,$value) = each(%{$store})) {
                   6744:             $items.= &escape($key).'='.&escape($value).'&';
                   6745:         }
                   6746:     }
                   6747:     $items=~s/\&$//;
1.627     albertel 6748:     if ($critical) {
                   6749: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6750:     } else {
                   6751: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6752:     }
1.449     matthew  6753: }
                   6754: 
1.12      www      6755: # --------------------------------------------------------------- put interface
                   6756: 
                   6757: sub put {
1.134     albertel 6758:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6759:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6760:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6761:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6762:    my $items='';
1.800     albertel 6763:    foreach my $item (keys(%$storehash)) {
                   6764:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6765:    }
1.12      www      6766:    $items=~s/\&$//;
1.134     albertel 6767:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6768: }
                   6769: 
1.631     albertel 6770: # ------------------------------------------------------------ newput interface
                   6771: 
                   6772: sub newput {
                   6773:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6774:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6775:    if (!$uname) { $uname=$env{'user.name'}; }
                   6776:    my $uhome=&homeserver($uname,$udomain);
                   6777:    my $items='';
                   6778:    foreach my $key (keys(%$storehash)) {
                   6779:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6780:    }
                   6781:    $items=~s/\&$//;
                   6782:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6783: }
                   6784: 
                   6785: # ---------------------------------------------------------  putstore interface
                   6786: 
1.524     raeburn  6787: sub putstore {
1.1269    raeburn  6788:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6789:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6790:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6791:    my $uhome=&homeserver($uname,$udomain);
                   6792:    my $items='';
1.715     albertel 6793:    foreach my $key (keys(%$storehash)) {
                   6794:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6795:    }
1.715     albertel 6796:    $items=~s/\&$//;
1.716     albertel 6797:    my $esc_symb=&escape($symb);
                   6798:    my $esc_v=&escape($version);
1.715     albertel 6799:    my $reply =
1.716     albertel 6800:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6801: 	      $uhome);
1.1269    raeburn  6802:    if (($tolog) && ($reply eq 'ok')) {
                   6803:        my $namevalue='';
                   6804:        foreach my $key (keys(%{$storehash})) {
                   6805:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6806:        }
                   6807:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6808:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6809:                      '&version='.$esc_v.
                   6810:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6811:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6812:    }
1.715     albertel 6813:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6814:        # gfall back to way things use to be done
1.715     albertel 6815:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6816: 			    $uname);
1.524     raeburn  6817:    }
1.715     albertel 6818:    return $reply;
                   6819: }
                   6820: 
                   6821: sub old_putstore {
1.716     albertel 6822:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6823:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6824:     if (!$uname) { $uname=$env{'user.name'}; }
                   6825:     my $uhome=&homeserver($uname,$udomain);
                   6826:     my %newstorehash;
1.800     albertel 6827:     foreach my $item (keys(%$storehash)) {
                   6828: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6829: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6830:     }
                   6831:     my $items='';
                   6832:     my %allitems = ();
1.800     albertel 6833:     foreach my $item (keys(%newstorehash)) {
                   6834: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6835: 	    my $key = $1.':keys:'.$2;
                   6836: 	    $allitems{$key} .= $3.':';
                   6837: 	}
1.800     albertel 6838: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6839:     }
1.800     albertel 6840:     foreach my $item (keys(%allitems)) {
                   6841: 	$allitems{$item} =~ s/\:$//;
                   6842: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6843:     }
                   6844:     $items=~s/\&$//;
                   6845:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6846: }
                   6847: 
1.47      www      6848: # ------------------------------------------------------ critical put interface
                   6849: 
                   6850: sub cput {
1.134     albertel 6851:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6852:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6853:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6854:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6855:    my $items='';
1.800     albertel 6856:    foreach my $item (keys(%$storehash)) {
                   6857:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6858:    }
1.47      www      6859:    $items=~s/\&$//;
1.134     albertel 6860:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6861: }
                   6862: 
                   6863: # -------------------------------------------------------------- eget interface
                   6864: 
                   6865: sub eget {
1.133     albertel 6866:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6867:    my $items='';
1.800     albertel 6868:    foreach my $item (@$storearr) {
                   6869:        $items.=&escape($item).'&';
1.191     harris41 6870:    }
1.12      www      6871:    $items=~s/\&$//;
1.620     albertel 6872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6873:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6874:    my $uhome=&homeserver($uname,$udomain);
                   6875:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6876:    my @pairs=split(/\&/,$rep);
                   6877:    my %returnhash=();
1.42      www      6878:    my $i=0;
1.800     albertel 6879:    foreach my $item (@$storearr) {
                   6880:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6881:       $i++;
1.191     harris41 6882:    }
1.12      www      6883:    return %returnhash;
                   6884: }
                   6885: 
1.667     albertel 6886: # ------------------------------------------------------------ tmpput interface
                   6887: sub tmpput {
1.802     raeburn  6888:     my ($storehash,$server,$context)=@_;
1.667     albertel 6889:     my $items='';
1.800     albertel 6890:     foreach my $item (keys(%$storehash)) {
                   6891: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6892:     }
                   6893:     $items=~s/\&$//;
1.802     raeburn  6894:     if (defined($context)) {
                   6895:         $items .= ':'.&escape($context);
                   6896:     }
1.667     albertel 6897:     return &reply("tmpput:$items",$server);
                   6898: }
                   6899: 
                   6900: # ------------------------------------------------------------ tmpget interface
                   6901: sub tmpget {
1.688     albertel 6902:     my ($token,$server)=@_;
                   6903:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6904:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6905:     my %returnhash;
1.1328    raeburn  6906:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6907:         return %returnhash;
                   6908:     }
1.667     albertel 6909:     foreach my $item (split(/\&/,$rep)) {
                   6910: 	my ($key,$value)=split(/=/,$item);
                   6911: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6912:     }
                   6913:     return %returnhash;
                   6914: }
                   6915: 
1.1113    raeburn  6916: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6917: sub tmpdel {
                   6918:     my ($token,$server)=@_;
                   6919:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6920:     return &reply("tmpdel:$token",$server);
                   6921: }
                   6922: 
1.1198    raeburn  6923: # ------------------------------------------------------------ get_timebased_id 
                   6924: 
                   6925: sub get_timebased_id {
                   6926:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6927:         $maxtries) = @_;
                   6928:     my ($newid,$error,$dellock);
                   6929:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6930:         return ('','ok','invalid call to get suffix');
                   6931:     }
                   6932: 
                   6933: # set defaults for any optional args for which values were not supplied
                   6934:     if ($who eq '') {
                   6935:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6936:     }
                   6937:     if (!$locktries) {
                   6938:         $locktries = 3;
                   6939:     }
                   6940:     if (!$maxtries) {
                   6941:         $maxtries = 10;
                   6942:     }
                   6943:     
                   6944:     if (($cdom eq '') || ($cnum eq '')) {
                   6945:         if ($env{'request.course.id'}) {
                   6946:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6947:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6948:         }
                   6949:         if (($cdom eq '') || ($cnum eq '')) {
                   6950:             return ('','ok','call to get suffix not in course context');
                   6951:         }
                   6952:     }
                   6953: 
                   6954: # construct locking item
                   6955:     my $lockhash = {
                   6956:                       $prefix."\0".'locked_'.$keyid => $who,
                   6957:                    };
                   6958:     my $tries = 0;
                   6959: 
                   6960: # attempt to get lock on nohist_$namespace file
                   6961:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6962:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6963:         $tries ++;
                   6964:         sleep 1;
                   6965:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6966:     }
                   6967: 
                   6968: # attempt to get unique identifier, based on current timestamp
                   6969:     if ($gotlock eq 'ok') {
                   6970:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6971:         my $id = time;
                   6972:         $newid = $id;
1.1268    raeburn  6973:         if ($idtype eq 'addcode') {
                   6974:             $newid .= &sixnum_code();
                   6975:         }
1.1198    raeburn  6976:         my $idtries = 0;
                   6977:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6978:             if ($idtype eq 'concat') {
                   6979:                 $newid = $id.$idtries;
1.1268    raeburn  6980:             } elsif ($idtype eq 'addcode') {
                   6981:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6982:             } else {
                   6983:                 $newid ++;
                   6984:             }
                   6985:             $idtries ++;
                   6986:         }
                   6987:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6988:             my %new_item =  (
                   6989:                               $prefix."\0".$newid => $who,
                   6990:                             );
                   6991:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6992:                                                  $cdom,$cnum);
                   6993:             if ($putresult ne 'ok') {
                   6994:                 undef($newid);
                   6995:                 $error = 'error saving new item: '.$putresult;
                   6996:             }
                   6997:         } else {
1.1268    raeburn  6998:              undef($newid);
1.1198    raeburn  6999:              $error = ('error: no unique suffix available for the new item ');
                   7000:         }
                   7001: #  remove lock
                   7002:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7003:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7004:     } else {
                   7005:         $error = "error: could not obtain lockfile\n";
                   7006:         $dellock = 'ok';
1.1276    raeburn  7007:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7008:             $dellock = 'nolock';
                   7009:         }
1.1198    raeburn  7010:     }
                   7011:     return ($newid,$dellock,$error);
                   7012: }
                   7013: 
1.1268    raeburn  7014: sub sixnum_code {
                   7015:     my $code;
                   7016:     for (0..6) {
                   7017:         $code .= int( rand(9) );
                   7018:     }
                   7019:     return $code;
                   7020: }
                   7021: 
1.765     albertel 7022: # -------------------------------------------------- portfolio access checking
                   7023: 
                   7024: sub portfolio_access {
1.1270    raeburn  7025:     my ($requrl,$clientip) = @_;
1.765     albertel 7026:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7027:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7028:     if ($result) {
                   7029:         my %setters;
                   7030:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7031:             my ($startblock,$endblock) =
                   7032:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7033:             if ($startblock && $endblock) {
                   7034:                 return 'B';
                   7035:             }
                   7036:         } else {
                   7037:             my ($startblock,$endblock) =
                   7038:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7039:             if ($startblock && $endblock) {
                   7040:                 return 'B';
                   7041:             }
                   7042:         }
                   7043:     }
1.765     albertel 7044:     if ($result eq 'ok') {
1.766     albertel 7045:        return 'F';
1.765     albertel 7046:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7047:        return 'A';
1.765     albertel 7048:     }
1.766     albertel 7049:     return '';
1.765     albertel 7050: }
                   7051: 
                   7052: sub get_portfolio_access {
1.1270    raeburn  7053:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7054: 
                   7055:     if (!ref($access_hash)) {
                   7056: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7057: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7058: 						   $file_name);
                   7059: 	$access_hash = $access_controls{$file_name};
                   7060:     }
                   7061: 
1.1270    raeburn  7062:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7063:     my $now = time;
                   7064:     if (ref($access_hash) eq 'HASH') {
                   7065:         foreach my $key (keys(%{$access_hash})) {
                   7066:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7067:             if ($start > $now) {
                   7068:                 next;
                   7069:             }
                   7070:             if ($end && $end<$now) {
                   7071:                 next;
                   7072:             }
                   7073:             if ($scope eq 'public') {
                   7074:                 $public = $key;
                   7075:                 last;
                   7076:             } elsif ($scope eq 'guest') {
                   7077:                 $guest = $key;
                   7078:             } elsif ($scope eq 'domains') {
                   7079:                 push(@domains,$key);
                   7080:             } elsif ($scope eq 'users') {
                   7081:                 push(@users,$key);
                   7082:             } elsif ($scope eq 'course') {
                   7083:                 push(@courses,$key);
                   7084:             } elsif ($scope eq 'group') {
                   7085:                 push(@groups,$key);
1.1270    raeburn  7086:             } elsif ($scope eq 'ip') {
                   7087:                 push(@ips,$key);
1.765     albertel 7088:             }
                   7089:         }
                   7090:         if ($public) {
                   7091:             return 'ok';
1.1270    raeburn  7092:         } elsif (@ips > 0) {
                   7093:             my $allowed;
                   7094:             foreach my $ipkey (@ips) {
                   7095:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7096:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7097:                         $allowed = 1;
                   7098:                         last; 
                   7099:                     }
                   7100:                 }
                   7101:             }
                   7102:             if ($allowed) {
                   7103:                 return 'ok';
                   7104:             }
1.765     albertel 7105:         }
                   7106:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7107:             if ($guest) {
                   7108:                 return $guest;
                   7109:             }
                   7110:         } else {
                   7111:             if (@domains > 0) {
                   7112:                 foreach my $domkey (@domains) {
                   7113:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7114:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7115:                             return 'ok';
                   7116:                         }
                   7117:                     }
                   7118:                 }
                   7119:             }
                   7120:             if (@users > 0) {
                   7121:                 foreach my $userkey (@users) {
1.865     raeburn  7122:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7123:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7124:                             if (ref($item) eq 'HASH') {
                   7125:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7126:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7127:                                     return 'ok';
                   7128:                                 }
                   7129:                             }
                   7130:                         }
                   7131:                     } 
1.765     albertel 7132:                 }
                   7133:             }
                   7134:             my %roleshash;
                   7135:             my @courses_and_groups = @courses;
                   7136:             push(@courses_and_groups,@groups); 
                   7137:             if (@courses_and_groups > 0) {
                   7138:                 my (%allgroups,%allroles); 
                   7139:                 my ($start,$end,$role,$sec,$group);
                   7140:                 foreach my $envkey (%env) {
1.1060    raeburn  7141:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7142:                         my $cid = $2.'_'.$3; 
                   7143:                         if ($1 eq 'gr') {
                   7144:                             $group = $4;
                   7145:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7146:                         } else {
                   7147:                             if ($4 eq '') {
                   7148:                                 $sec = 'none';
                   7149:                             } else {
                   7150:                                 $sec = $4;
                   7151:                             }
                   7152:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7153:                         }
1.811     albertel 7154:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7155:                         my $cid = $2.'_'.$3;
                   7156:                         if ($4 eq '') {
                   7157:                             $sec = 'none';
                   7158:                         } else {
                   7159:                             $sec = $4;
                   7160:                         }
                   7161:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7162:                     }
                   7163:                 }
                   7164:                 if (keys(%allroles) == 0) {
                   7165:                     return;
                   7166:                 }
                   7167:                 foreach my $key (@courses_and_groups) {
                   7168:                     my %content = %{$$access_hash{$key}};
                   7169:                     my $cnum = $content{'number'};
                   7170:                     my $cdom = $content{'domain'};
                   7171:                     my $cid = $cdom.'_'.$cnum;
                   7172:                     if (!exists($allroles{$cid})) {
                   7173:                         next;
                   7174:                     }    
                   7175:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7176:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7177:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7178:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7179:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7180:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7181:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7182:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7183:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7184:                                         if (grep/^all$/,@sections) {
                   7185:                                             return 'ok';
                   7186:                                         } else {
                   7187:                                             if (grep/^$sec$/,@sections) {
                   7188:                                                 return 'ok';
                   7189:                                             }
                   7190:                                         }
                   7191:                                     }
                   7192:                                 }
                   7193:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7194:                                     if (grep/^none$/,@groups) {
                   7195:                                         return 'ok';
                   7196:                                     }
                   7197:                                 } else {
                   7198:                                     if (grep/^all$/,@groups) {
                   7199:                                         return 'ok';
                   7200:                                     } 
                   7201:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7202:                                         if (grep/^$group$/,@groups) {
                   7203:                                             return 'ok';
                   7204:                                         }
                   7205:                                     }
                   7206:                                 } 
                   7207:                             }
                   7208:                         }
                   7209:                     }
                   7210:                 }
                   7211:             }
                   7212:             if ($guest) {
                   7213:                 return $guest;
                   7214:             }
                   7215:         }
                   7216:     }
                   7217:     return;
                   7218: }
                   7219: 
                   7220: sub course_group_datechecker {
                   7221:     my ($dates,$now,$status) = @_;
                   7222:     my ($start,$end) = split(/\./,$dates);
                   7223:     if (!$start && !$end) {
                   7224:         return 'ok';
                   7225:     }
                   7226:     if (grep/^active$/,@{$status}) {
                   7227:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7228:             return 'ok';
                   7229:         }
                   7230:     }
                   7231:     if (grep/^previous$/,@{$status}) {
                   7232:         if ($end > $now ) {
                   7233:             return 'ok';
                   7234:         }
                   7235:     }
                   7236:     if (grep/^future$/,@{$status}) {
                   7237:         if ($start > $now) {
                   7238:             return 'ok';
                   7239:         }
                   7240:     }
                   7241:     return; 
                   7242: }
                   7243: 
                   7244: sub parse_portfolio_url {
                   7245:     my ($url) = @_;
                   7246: 
                   7247:     my ($type,$udom,$unum,$group,$file_name);
                   7248:     
1.823     albertel 7249:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7250: 	$type = 1;
                   7251:         $udom = $1;
                   7252:         $unum = $2;
                   7253:         $file_name = $3;
1.823     albertel 7254:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7255: 	$type = 2;
                   7256:         $udom = $1;
                   7257:         $unum = $2;
                   7258:         $group = $3;
                   7259:         $file_name = $3.'/'.$4;
                   7260:     }
                   7261:     if (wantarray) {
                   7262: 	return ($type,$udom,$unum,$file_name,$group);
                   7263:     }
                   7264:     return $type;
                   7265: }
                   7266: 
                   7267: sub is_portfolio_url {
                   7268:     my ($url) = @_;
                   7269:     return scalar(&parse_portfolio_url($url));
                   7270: }
                   7271: 
1.798     raeburn  7272: sub is_portfolio_file {
                   7273:     my ($file) = @_;
1.820     raeburn  7274:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7275:         return 1;
                   7276:     }
                   7277:     return;
                   7278: }
                   7279: 
1.976     raeburn  7280: sub usertools_access {
1.1084    raeburn  7281:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7282:     my ($access,%tools);
                   7283:     if ($context eq '') {
                   7284:         $context = 'tools';
                   7285:     }
                   7286:     if ($context eq 'requestcourses') {
                   7287:         %tools = (
                   7288:                       official   => 1,
                   7289:                       unofficial => 1,
1.1006    raeburn  7290:                       community  => 1,
1.1246    raeburn  7291:                       textbook   => 1,
1.1305    raeburn  7292:                       placement  => 1,
1.1368    raeburn  7293:                       lti        => 1,
1.985     raeburn  7294:                  );
1.1183    raeburn  7295:     } elsif ($context eq 'requestauthor') {
                   7296:         %tools = (
                   7297:                       requestauthor => 1,
                   7298:                  );
1.985     raeburn  7299:     } else {
                   7300:         %tools = (
                   7301:                       aboutme   => 1,
                   7302:                       blog      => 1,
1.1177    raeburn  7303:                       webdav    => 1,
1.985     raeburn  7304:                       portfolio => 1,
                   7305:                  );
                   7306:     }
1.976     raeburn  7307:     return if (!defined($tools{$tool}));
                   7308: 
1.1242    raeburn  7309:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7310:         $udom = $env{'user.domain'};
                   7311:         $uname = $env{'user.name'};
                   7312:     }
                   7313: 
1.978     raeburn  7314:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7315:         if ($action ne 'reload') {
1.985     raeburn  7316:             if ($context eq 'requestcourses') {
                   7317:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7318:             } elsif ($context eq 'requestauthor') {
                   7319:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7320:             } else {
                   7321:                 return $env{'environment.availabletools.'.$tool};
                   7322:             }
                   7323:         }
1.976     raeburn  7324:     }
                   7325: 
1.1183    raeburn  7326:     my ($toolstatus,$inststatus,$envkey);
                   7327:     if ($context eq 'requestauthor') {
                   7328:         $envkey = $context; 
                   7329:     } else {
                   7330:         $envkey = $context.'.'.$tool;
                   7331:     }
1.976     raeburn  7332: 
1.985     raeburn  7333:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7334:          ($action ne 'reload')) {
1.1183    raeburn  7335:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7336:         $inststatus = $env{'environment.inststatus'};
                   7337:     } else {
1.1084    raeburn  7338:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7339:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7340:             $inststatus = $userenvref->{'inststatus'};
                   7341:         } else {
1.1183    raeburn  7342:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7343:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7344:             $inststatus = $userenv{'inststatus'};
                   7345:         }
1.976     raeburn  7346:     }
                   7347: 
                   7348:     if ($toolstatus ne '') {
                   7349:         if ($toolstatus) {
                   7350:             $access = 1;
                   7351:         } else {
                   7352:             $access = 0;
                   7353:         }
                   7354:         return $access;
                   7355:     }
                   7356: 
1.1084    raeburn  7357:     my ($is_adv,%domdef);
                   7358:     if (ref($is_advref) eq 'HASH') {
                   7359:         $is_adv = $is_advref->{'is_adv'};
                   7360:     } else {
                   7361:         $is_adv = &is_advanced_user($udom,$uname);
                   7362:     }
                   7363:     if (ref($domdefref) eq 'HASH') {
                   7364:         %domdef = %{$domdefref};
                   7365:     } else {
                   7366:         %domdef = &get_domain_defaults($udom);
                   7367:     }
1.976     raeburn  7368:     if (ref($domdef{$tool}) eq 'HASH') {
                   7369:         if ($is_adv) {
                   7370:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7371:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7372:                     $access = 1;
                   7373:                 } else {
                   7374:                     $access = 0;
                   7375:                 }
                   7376:                 return $access;
                   7377:             }
                   7378:         }
                   7379:         if ($inststatus ne '') {
                   7380:             my ($hasaccess,$hasnoaccess);
                   7381:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7382:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7383:                     if ($domdef{$tool}{$affiliation}) {
                   7384:                         $hasaccess = 1;
                   7385:                     } else {
                   7386:                         $hasnoaccess = 1;
                   7387:                     }
                   7388:                 }
                   7389:             }
                   7390:             if ($hasaccess || $hasnoaccess) {
                   7391:                 if ($hasaccess) {
                   7392:                     $access = 1;
                   7393:                 } elsif ($hasnoaccess) {
                   7394:                     $access = 0; 
                   7395:                 }
                   7396:                 return $access;
                   7397:             }
                   7398:         } else {
                   7399:             if ($domdef{$tool}{'default'} ne '') {
                   7400:                 if ($domdef{$tool}{'default'}) {
                   7401:                     $access = 1;
                   7402:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7403:                     $access = 0;
                   7404:                 }
                   7405:                 return $access;
                   7406:             }
                   7407:         }
                   7408:     } else {
1.1177    raeburn  7409:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7410:             $access = 1;
                   7411:         } else {
                   7412:             $access = 0;
                   7413:         }
1.976     raeburn  7414:         return $access;
                   7415:     }
                   7416: }
                   7417: 
1.1050    raeburn  7418: sub is_course_owner {
                   7419:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7420:     if (($udom eq '') || ($uname eq '')) {
                   7421:         $udom = $env{'user.domain'};
                   7422:         $uname = $env{'user.name'};
                   7423:     }
                   7424:     unless (($udom eq '') || ($uname eq '')) {
                   7425:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7426:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7427:                 return 1;
                   7428:             } else {
                   7429:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7430:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7431:                     return 1;
                   7432:                 }
                   7433:             }
                   7434:         }
                   7435:     }
                   7436:     return;
                   7437: }
                   7438: 
1.976     raeburn  7439: sub is_advanced_user {
                   7440:     my ($udom,$uname) = @_;
1.1085    raeburn  7441:     if ($udom ne '' && $uname ne '') {
                   7442:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7443:             if (wantarray) {
                   7444:                 return ($env{'user.adv'},$env{'user.author'});
                   7445:             } else {
                   7446:                 return $env{'user.adv'};
                   7447:             }
1.1085    raeburn  7448:         }
                   7449:     }
1.976     raeburn  7450:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7451:     my %allroles;
1.1128    raeburn  7452:     my ($is_adv,$is_author);
1.976     raeburn  7453:     foreach my $role (keys(%roleshash)) {
                   7454:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7455:         my $area = '/'.$tdomain.'/'.$trest;
                   7456:         if ($sec ne '') {
                   7457:             $area .= '/'.$sec;
                   7458:         }
                   7459:         if (($area ne '') && ($trole ne '')) {
                   7460:             my $spec=$trole.'.'.$area;
                   7461:             if ($trole =~ /^cr\//) {
                   7462:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7463:             } elsif ($trole ne 'gr') {
                   7464:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7465:             }
1.1128    raeburn  7466:             if ($trole eq 'au') {
                   7467:                 $is_author = 1;
                   7468:             }
1.976     raeburn  7469:         }
                   7470:     }
                   7471:     foreach my $role (keys(%allroles)) {
                   7472:         last if ($is_adv);
                   7473:         foreach my $item (split(/:/,$allroles{$role})) {
                   7474:             if ($item ne '') {
                   7475:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7476:                 if ($privilege eq 'adv') {
                   7477:                     $is_adv = 1;
                   7478:                     last;
                   7479:                 }
                   7480:             }
                   7481:         }
                   7482:     }
1.1128    raeburn  7483:     if (wantarray) {
                   7484:         return ($is_adv,$is_author);
                   7485:     }
1.976     raeburn  7486:     return $is_adv;
                   7487: }
1.798     raeburn  7488: 
1.1035    raeburn  7489: sub check_can_request {
1.1368    raeburn  7490:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7491:     my $canreq = 0;
1.1368    raeburn  7492:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7493:         $uname = $env{'user.name'};
                   7494:         $udom = $env{'user.domain'};
                   7495:     }
1.1035    raeburn  7496:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7497:     my @options = ('approval','validate','autolimit');
                   7498:     my $optregex = join('|',@options);
                   7499:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7500:         foreach my $type (@{$types}) {
1.1368    raeburn  7501:             if (&usertools_access($uname,$udom,$type,undef,
                   7502:                                   'requestcourses')) {
1.1035    raeburn  7503:                 $canreq ++;
1.1036    raeburn  7504:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7505:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7506:                 }
1.1368    raeburn  7507:                 if ($dom eq $udom) {
1.1035    raeburn  7508:                     $can_request->{$type} = 1;
                   7509:                 }
                   7510:             }
1.1368    raeburn  7511:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7512:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7513:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7514:                 if (@curr > 0) {
1.1036    raeburn  7515:                     foreach my $item (@curr) {
                   7516:                         if (ref($request_domains) eq 'HASH') {
                   7517:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7518:                             if ($otherdom ne '') {
                   7519:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7520:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7521:                                         push(@{$request_domains->{$type}},$otherdom);
                   7522:                                     }
                   7523:                                 } else {
                   7524:                                     push(@{$request_domains->{$type}},$otherdom);
                   7525:                                 }
                   7526:                             }
                   7527:                         }
                   7528:                     }
1.1368    raeburn  7529:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7530:                         $canreq ++;
1.1035    raeburn  7531:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7532:                             $can_request->{$type} = 1;
                   7533:                         }
                   7534:                     }
                   7535:                 }
                   7536:             }
                   7537:         }
                   7538:     }
                   7539:     return $canreq;
                   7540: }
                   7541: 
1.341     www      7542: # ---------------------------------------------- Custom access rule evaluation
                   7543: 
                   7544: sub customaccess {
                   7545:     my ($priv,$uri)=@_;
1.807     albertel 7546:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7547:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7548:     $udom = &LONCAPA::clean_domain($udom);
                   7549:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7550:     my $access=0;
1.800     albertel 7551:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7552: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7553: 	if ($type eq 'user') {
                   7554: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7555: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7556: 		if ($tdom) {
                   7557: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7558: 		}
1.896     albertel 7559: 		if ($tuname) {
                   7560: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7561: 		}
                   7562: 		$access=($effect eq 'allow');
                   7563: 		last;
                   7564: 	    }
                   7565: 	} else {
                   7566: 	    if ($role) {
                   7567: 		if ($role ne $urole) { next; }
                   7568: 	    }
                   7569: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7570: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7571: 		if ($tdom) {
                   7572: 		    if ($tdom ne $udom) { next; }
                   7573: 		}
                   7574: 		if ($tcrs) {
                   7575: 		    if ($tcrs ne $ucrs) { next; }
                   7576: 		}
                   7577: 		if ($tsec) {
                   7578: 		    if ($tsec ne $usec) { next; }
                   7579: 		}
                   7580: 		$access=($effect eq 'allow');
                   7581: 		last;
                   7582: 	    }
                   7583: 	    if ($realm eq '' && $role eq '') {
                   7584: 		$access=($effect eq 'allow');
                   7585: 	    }
1.402     bowersj2 7586: 	}
1.341     www      7587:     }
                   7588:     return $access;
                   7589: }
                   7590: 
1.103     harris41 7591: # ------------------------------------------------- Check for a user privilege
1.12      www      7592: 
                   7593: sub allowed {
1.1281    raeburn  7594:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7595:     my $ver_orguri=$uri;
1.439     www      7596:     $uri=&deversion($uri);
1.152     www      7597:     my $orguri=$uri;
1.52      www      7598:     $uri=&declutter($uri);
1.809     raeburn  7599: 
1.810     raeburn  7600:     if ($priv eq 'evb') {
                   7601: # Evade communication block restrictions for specified role in a course
                   7602:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7603:             return $1;
                   7604:         } else {
                   7605:             return;
                   7606:         }
                   7607:     }
                   7608: 
1.620     albertel 7609:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7610: # Free bre access to adm and meta resources
1.1343    raeburn  7611:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7612: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7613: 	&& ($priv eq 'bre')) {
1.14      www      7614: 	return 'F';
1.159     www      7615:     }
                   7616: 
1.545     banghart 7617: # Free bre access to user's own portfolio contents
1.714     raeburn  7618:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7619:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7620: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7621:         my %setters;
                   7622:         my ($startblock,$endblock) = 
                   7623:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7624:         if ($startblock && $endblock) {
                   7625:             return 'B';
                   7626:         } else {
                   7627:             return 'F';
                   7628:         }
1.545     banghart 7629:     }
                   7630: 
1.762     raeburn  7631: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7632:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7633:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7634:         if (exists($env{'request.course.id'})) {
                   7635:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7636:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7637:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7638:                 my $courseprivid=$env{'request.course.id'};
                   7639:                 $courseprivid=~s/\_/\//;
                   7640:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7641:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7642:                     return $1; 
1.762     raeburn  7643:                 } else {
                   7644:                     if ($env{'request.course.sec'}) {
                   7645:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7646:                     }
                   7647:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7648:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7649:                         return $2;
                   7650:                     }
1.714     raeburn  7651:                 }
                   7652:             }
                   7653:         }
                   7654:     }
                   7655: 
1.159     www      7656: # Free bre to public access
                   7657: 
                   7658:     if ($priv eq 'bre') {
1.1362    raeburn  7659:         my $copyright;
                   7660:         unless ($uri =~ /ext\.tool/) {
                   7661:             $copyright=&metadata($uri,'copyright');
                   7662:         }
1.620     albertel 7663: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7664:            return 'F'; 
                   7665:         }
1.238     www      7666:         if ($copyright eq 'priv') {
                   7667:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7668: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7669: 		return '';
                   7670:             }
                   7671:         }
                   7672:         if ($copyright eq 'domain') {
                   7673:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7674: 	    unless (($env{'user.domain'} eq $1) ||
                   7675:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7676: 		return '';
                   7677:             }
1.262     matthew  7678:         }
1.620     albertel 7679:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7680:             # Library role, so allow browsing of resources in this domain.
                   7681:             return 'F';
1.238     www      7682:         }
1.341     www      7683:         if ($copyright eq 'custom') {
                   7684: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7685:         }
1.14      www      7686:     }
1.264     matthew  7687:     # Domain coordinator is trying to create a course
1.620     albertel 7688:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7689:         # uri is the requested domain in this case.
                   7690:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7691:         # a role of dc for the domain in question.
1.620     albertel 7692:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7693:     }
1.29      www      7694: 
1.52      www      7695:     my $thisallowed='';
                   7696:     my $statecond=0;
                   7697:     my $courseprivid='';
                   7698: 
1.1039    raeburn  7699:     my $ownaccess;
1.1043    raeburn  7700:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7701:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7702:         if ($uri eq '') {
                   7703:             $ownaccess = 1;
                   7704:         } else {
                   7705:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7706:                 my $udom = $env{'user.domain'};
                   7707:                 my $uname = $env{'user.name'};
                   7708:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7709:                     $ownaccess = 1;
1.1040    raeburn  7710:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7711:                     unless ($uri =~ m{\.\./}) {
                   7712:                         $ownaccess = 1;
                   7713:                     }
                   7714:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7715:                     my $now = time;
                   7716:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7717:                         my $adom = $1;
                   7718:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7719:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7720:                                 my ($start,$end) = split('.',$env{$key});
                   7721:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7722:                                     $ownaccess = 1;
                   7723:                                     last;
                   7724:                                 }
                   7725:                             }
                   7726:                         }
                   7727:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7728:                         my $adom = $1;
                   7729:                         my $aname = $2;
1.1042    raeburn  7730:                         foreach my $role ('ca','aa') { 
                   7731:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7732:                                 my ($start,$end) =
                   7733:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7734:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7735:                                     $ownaccess = 1;
                   7736:                                     last;
                   7737:                                 }
1.1039    raeburn  7738:                             }
                   7739:                         }
                   7740:                     }
                   7741:                 }
                   7742:             }
                   7743:         }
                   7744:     }
                   7745: 
1.52      www      7746: # Course
                   7747: 
1.620     albertel 7748:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7749:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7750:             $thisallowed.=$1;
                   7751:         }
1.52      www      7752:     }
1.29      www      7753: 
1.52      www      7754: # Domain
                   7755: 
1.620     albertel 7756:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7757:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7758:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7759:             $thisallowed.=$1;
                   7760:         }
1.12      www      7761:     }
1.52      www      7762: 
1.1141    raeburn  7763: # User who is not author or co-author might still be able to edit
                   7764: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7765:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7766:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7767:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7768:             $thisallowed.=$1;
                   7769:         }
                   7770:     }
                   7771: 
1.52      www      7772: # Course: uri itself is a course
1.66      www      7773:     my $courseuri=$uri;
                   7774:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7775:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7776: 
1.620     albertel 7777:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7778:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7779:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7780:             $thisallowed.=$1;
                   7781:         }
1.12      www      7782:     }
1.29      www      7783: 
1.665     albertel 7784: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7785: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7786:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7787: 	$thisallowed='';
1.671     raeburn  7788:         my ($match)=&is_on_map($uri);
                   7789:         if ($match) {
                   7790:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7791:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7792:                 my $value = $1;
                   7793:                 if ($noblockcheck) {
                   7794:                     $thisallowed.=$value;
1.1162    raeburn  7795:                 } else {
1.1281    raeburn  7796:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7797:                     if (@blockers > 0) {
                   7798:                         $thisallowed = 'B';
                   7799:                     } else {
                   7800:                         $thisallowed.=$value;
                   7801:                     }
1.1162    raeburn  7802:                 }
1.671     raeburn  7803:             }
                   7804:         } else {
1.705     albertel 7805:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7806:             if ($refuri) {
                   7807:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7808:                     $thisallowed='F';
1.671     raeburn  7809:                 } else {
                   7810:                     $refuri=&declutter($refuri);
                   7811:                     my ($match) = &is_on_map($refuri);
                   7812:                     if ($match) {
1.1281    raeburn  7813:                         if ($noblockcheck) {
                   7814:                             $thisallowed='F';
1.1162    raeburn  7815:                         } else {
1.1281    raeburn  7816:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7817:                             if (@blockers > 0) {
                   7818:                                 $thisallowed = 'B';
                   7819:                             } else {
                   7820:                                 $thisallowed='F';
                   7821:                             }
1.1162    raeburn  7822:                         }
1.671     raeburn  7823:                     }
1.669     raeburn  7824:                 }
1.671     raeburn  7825:             }
                   7826:         }
1.314     www      7827:     }
1.492     albertel 7828: 
1.766     albertel 7829:     if ($priv eq 'bre'
                   7830: 	&& $thisallowed ne 'F' 
                   7831: 	&& $thisallowed ne '2'
                   7832: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7833: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7834:     }
1.1250    raeburn  7835: 
1.52      www      7836: # Full access at system, domain or course-wide level? Exit.
1.29      www      7837:     if ($thisallowed=~/F/) {
                   7838: 	return 'F';
                   7839:     }
                   7840: 
1.52      www      7841: # If this is generating or modifying users, exit with special codes
1.29      www      7842: 
1.643     www      7843:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7844: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7845: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7846: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7847: 	    unless ($auname) { return $thisallowed; }
                   7848: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7849: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7850: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7851: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7852: 	}
1.52      www      7853: 	return $thisallowed;
                   7854:     }
                   7855: #
1.103     harris41 7856: # Gathered so far: system, domain and course wide privileges
1.52      www      7857: #
                   7858: # Course: See if uri or referer is an individual resource that is part of 
                   7859: # the course
                   7860: 
1.620     albertel 7861:     if ($env{'request.course.id'}) {
1.232     www      7862: 
1.620     albertel 7863:        $courseprivid=$env{'request.course.id'};
                   7864:        if ($env{'request.course.sec'}) {
                   7865:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7866:        }
                   7867:        $courseprivid=~s/\_/\//;
                   7868:        my $checkreferer=1;
1.232     www      7869:        my ($match,$cond)=&is_on_map($uri);
                   7870:        if ($match) {
                   7871:            $statecond=$cond;
1.620     albertel 7872:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7873:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7874:                my $value = $1;
                   7875:                if ($priv eq 'bre') {
1.1281    raeburn  7876:                    if ($noblockcheck) {
                   7877:                        $thisallowed.=$value;
1.1162    raeburn  7878:                    } else {
1.1281    raeburn  7879:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7880:                        if (@blockers > 0) {
                   7881:                            $thisallowed = 'B';
                   7882:                        } else {
                   7883:                            $thisallowed.=$value;
                   7884:                        }
1.1162    raeburn  7885:                    }
                   7886:                } else {
                   7887:                    $thisallowed.=$value;
                   7888:                }
1.52      www      7889:                $checkreferer=0;
                   7890:            }
1.29      www      7891:        }
1.83      www      7892:        
1.148     www      7893:        if ($checkreferer) {
1.620     albertel 7894: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7895:             unless ($refuri) {
1.800     albertel 7896:                 foreach my $key (keys(%env)) {
                   7897: 		    if ($key=~/^httpref\..*\*/) {
                   7898: 			my $pattern=$key;
1.156     www      7899:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7900:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7901:                         $pattern=~s/\//\\\//g;
1.152     www      7902:                         if ($orguri=~/$pattern/) {
1.800     albertel 7903: 			    $refuri=$env{$key};
1.148     www      7904:                         }
                   7905:                     }
1.191     harris41 7906:                 }
1.148     www      7907:             }
1.232     www      7908: 
1.148     www      7909:          if ($refuri) { 
1.152     www      7910: 	  $refuri=&declutter($refuri);
1.232     www      7911:           my ($match,$cond)=&is_on_map($refuri);
                   7912:             if ($match) {
                   7913:               my $refstatecond=$cond;
1.620     albertel 7914:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7915:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7916:                   my $value = $1;
                   7917:                   if ($priv eq 'bre') {
1.1281    raeburn  7918:                       if ($noblockcheck) {
                   7919:                           $thisallowed.=$value;
1.1162    raeburn  7920:                       } else {
1.1281    raeburn  7921:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7922:                           if (@blockers > 0) {
                   7923:                               $thisallowed = 'B';
                   7924:                           } else {
                   7925:                               $thisallowed.=$value;
                   7926:                           }
1.1162    raeburn  7927:                       }
                   7928:                   } else {
                   7929:                       $thisallowed.=$value;
                   7930:                   }
1.53      www      7931:                   $uri=$refuri;
                   7932:                   $statecond=$refstatecond;
1.52      www      7933:               }
                   7934:           }
1.148     www      7935:         }
1.29      www      7936:        }
1.52      www      7937:    }
1.29      www      7938: 
1.52      www      7939: #
1.103     harris41 7940: # Gathered now: all privileges that could apply, and condition number
1.52      www      7941: # 
                   7942: #
                   7943: # Full or no access?
                   7944: #
1.29      www      7945: 
1.52      www      7946:     if ($thisallowed=~/F/) {
                   7947: 	return 'F';
                   7948:     }
1.29      www      7949: 
1.52      www      7950:     unless ($thisallowed) {
                   7951:         return '';
                   7952:     }
1.29      www      7953: 
1.52      www      7954: # Restrictions exist, deal with them
                   7955: #
                   7956: #   C:according to course preferences
                   7957: #   R:according to resource settings
                   7958: #   L:unless locked
                   7959: #   X:according to user session state
                   7960: #
                   7961: 
                   7962: # Possibly locked functionality, check all courses
1.54      www      7963: # Locks might take effect only after 10 minutes cache expiration for other
                   7964: # courses, and 2 minutes for current course
1.52      www      7965: 
                   7966:     my $envkey;
                   7967:     if ($thisallowed=~/L/) {
1.1000    raeburn  7968:         foreach $envkey (keys(%env)) {
1.54      www      7969:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7970:                my $courseid=$2;
                   7971:                my $roleid=$1.'.'.$2;
1.92      www      7972:                $courseid=~s/^\///;
1.54      www      7973:                my $expiretime=600;
1.620     albertel 7974:                if ($env{'request.role'} eq $roleid) {
1.54      www      7975: 		  $expiretime=120;
                   7976:                }
                   7977: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7978:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7979:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7980: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7981:                }
1.620     albertel 7982:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7983:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7984: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7985:                        &log($env{'user.domain'},$env{'user.name'},
                   7986:                             $env{'user.home'},
1.57      www      7987:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7988:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7989:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7990: 		       return '';
                   7991:                    }
                   7992:                }
1.620     albertel 7993:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7994:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7995: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7996:                        &log($env{'user.domain'},$env{'user.name'},
                   7997:                             $env{'user.home'},
1.57      www      7998:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7999:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8000:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8001: 		       return '';
                   8002:                    }
                   8003:                }
                   8004: 	   }
1.29      www      8005:        }
1.52      www      8006:     }
                   8007:    
                   8008: #
                   8009: # Rest of the restrictions depend on selected course
                   8010: #
                   8011: 
1.620     albertel 8012:     unless ($env{'request.course.id'}) {
1.766     albertel 8013: 	if ($thisallowed eq 'A') {
                   8014: 	    return 'A';
1.814     raeburn  8015:         } elsif ($thisallowed eq 'B') {
                   8016:             return 'B';
1.766     albertel 8017: 	} else {
                   8018: 	    return '1';
                   8019: 	}
1.52      www      8020:     }
1.29      www      8021: 
1.52      www      8022: #
                   8023: # Now user is definitely in a course
                   8024: #
1.53      www      8025: 
                   8026: 
                   8027: # Course preferences
                   8028: 
                   8029:    if ($thisallowed=~/C/) {
1.620     albertel 8030:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8031:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8032:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8033: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8034: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8035: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8036: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8037: 			$env{'request.course.id'});
                   8038: 	   }
1.237     www      8039:            return '';
                   8040:        }
                   8041: 
1.620     albertel 8042:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8043: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8044: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8045: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8046: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8047: 			$env{'request.course.id'});
                   8048: 	   }
1.54      www      8049:            return '';
                   8050:        }
1.53      www      8051:    }
                   8052: 
                   8053: # Resource preferences
                   8054: 
                   8055:    if ($thisallowed=~/R/) {
1.620     albertel 8056:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8057:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8058: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8059: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8060: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8061: 	   }
                   8062: 	   return '';
1.54      www      8063:        }
1.53      www      8064:    }
1.30      www      8065: 
1.246     www      8066: # Restricted by state or randomout?
1.30      www      8067: 
1.52      www      8068:    if ($thisallowed=~/X/) {
1.620     albertel 8069:       if ($env{'acc.randomout'}) {
1.579     albertel 8070: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8071:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8072:             return ''; 
                   8073:          }
1.247     www      8074:       }
                   8075:       if (&condval($statecond)) {
1.52      www      8076: 	 return '2';
                   8077:       } else {
                   8078:          return '';
                   8079:       }
                   8080:    }
1.30      www      8081: 
1.766     albertel 8082:     if ($thisallowed eq 'A') {
                   8083: 	return 'A';
1.814     raeburn  8084:     } elsif ($thisallowed eq 'B') {
                   8085:         return 'B';
1.766     albertel 8086:     }
1.52      www      8087:    return 'F';
1.232     www      8088: }
1.1162    raeburn  8089: 
1.1192    raeburn  8090: # ------------------------------------------- Check construction space access
                   8091: 
                   8092: sub constructaccess {
                   8093:     my ($url,$setpriv)=@_;
                   8094: 
                   8095: # We do not allow editing of previous versions of files
                   8096:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8097: 
                   8098: # Get username and domain from URL
                   8099:     my ($ownername,$ownerdomain,$ownerhome);
                   8100: 
                   8101:     ($ownerdomain,$ownername) =
1.1325    raeburn  8102:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8103: 
                   8104: # The URL does not really point to any authorspace, forget it
                   8105:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8106: 
                   8107: # Now we need to see if the user has access to the authorspace of
                   8108: # $ownername at $ownerdomain
                   8109: 
                   8110:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8111: # Real author for this?
                   8112:        $ownerhome = $env{'user.home'};
                   8113:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8114:           return ($ownername,$ownerdomain,$ownerhome);
                   8115:        }
                   8116:     } else {
                   8117: # Co-author for this?
                   8118:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8119:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8120:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8121:             return ($ownername,$ownerdomain,$ownerhome);
                   8122:         }
1.1312    raeburn  8123:         if ($env{'request.course.id'}) {
                   8124:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8125:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8126:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8127:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8128:                     return ($ownername,$ownerdomain,$ownerhome);
                   8129:                 }
                   8130:             }
                   8131:         }
1.1192    raeburn  8132:     }
                   8133: 
                   8134: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8135: # we might as well leave
                   8136:    unless ($setpriv) { return ''; }
                   8137: 
                   8138: # Backdoor access?
                   8139:     my $allowed=&allowed('eco',$ownerdomain);
                   8140: # Nope
                   8141:     unless ($allowed) { return ''; }
                   8142: # Looks like we may have access, but could be locked by the owner of the construction space
                   8143:     if ($allowed eq 'U') {
                   8144:         my %blocked=&get('environment',['domcoord.author'],
                   8145:                          $ownerdomain,$ownername);
                   8146: # Is blocked by owner
                   8147:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8148:     }
                   8149:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8150: # Grant temporary access
                   8151:         my $then=$env{'user.login.time'};
1.1209    raeburn  8152:         my $update=$env{'user.update.time'};
1.1192    raeburn  8153:         if (!$update) { $update = $then; }
                   8154:         my $refresh=$env{'user.refresh.time'};
                   8155:         if (!$refresh) { $refresh = $update; }
                   8156:         my $now = time;
                   8157:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8158:                            $now,'ca','constructaccess');
                   8159:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8160:         return($ownername,$ownerdomain,$ownerhome);
                   8161:     }
                   8162: # No business here
                   8163:     return '';
                   8164: }
                   8165: 
1.1282    raeburn  8166: # ----------------------------------------------------------- Content Blocking
                   8167: 
                   8168: {
                   8169: # Caches for faster Course Contents display where content blocking
                   8170: # is in operation (i.e., interval param set) for timed quiz.
                   8171: #
                   8172: # User for whom data are being temporarily cached.
                   8173: my $cacheduser='';
                   8174: # Cached blockers for this user (a hash of blocking items). 
                   8175: my %cachedblockers=();
                   8176: # When the data were last cached.
                   8177: my $cachedlast='';
                   8178: 
                   8179: sub load_all_blockers {
                   8180:     my ($uname,$udom,$blocks)=@_;
                   8181:     if (($uname ne '') && ($udom ne '')) { 
                   8182:         if (($cacheduser eq $uname.':'.$udom) &&
                   8183:             (abs($cachedlast-time)<5)) {
                   8184:             return;
                   8185:         }
                   8186:     }
                   8187:     $cachedlast=time;
                   8188:     $cacheduser=$uname.':'.$udom;
                   8189:     %cachedblockers = &get_commblock_resources($blocks);
                   8190: }
                   8191: 
1.1162    raeburn  8192: sub get_comm_blocks {
                   8193:     my ($cdom,$cnum) = @_;
                   8194:     if ($cdom eq '' || $cnum eq '') {
                   8195:         return unless ($env{'request.course.id'});
                   8196:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8197:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8198:     }
                   8199:     my %commblocks;
                   8200:     my $hashid=$cdom.'_'.$cnum;
                   8201:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8202:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8203:         %commblocks = %{$blocksref};
                   8204:     } else {
                   8205:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8206:         my $cachetime = 600;
                   8207:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8208:     }
                   8209:     return %commblocks;
                   8210: }
                   8211: 
1.1282    raeburn  8212: sub get_commblock_resources {
                   8213:     my ($blocks) = @_;
                   8214:     my %blockers = ();
                   8215:     return %blockers unless ($env{'request.course.id'});
                   8216:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8217:     my %commblocks;
                   8218:     if (ref($blocks) eq 'HASH') {
                   8219:         %commblocks = %{$blocks};
                   8220:     } else {
                   8221:         %commblocks = &get_comm_blocks();
                   8222:     }
1.1282    raeburn  8223:     return %blockers unless (keys(%commblocks) > 0); 
                   8224:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8225:     return %blockers unless (ref($navmap));
1.1162    raeburn  8226:     my $now = time;
                   8227:     foreach my $block (keys(%commblocks)) {
                   8228:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8229:             my ($start,$end) = ($1,$2);
                   8230:             if ($start <= $now && $end >= $now) {
                   8231:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8232:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8233:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8234:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8235:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8236:                             }
                   8237:                         }
                   8238:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8239:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8240:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8241:                             }
                   8242:                         }
                   8243:                     }
                   8244:                 }
                   8245:             }
                   8246:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8247:             my $item = $1;
1.1163    raeburn  8248:             my @to_test;
1.1162    raeburn  8249:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8250:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8251:                     my @interval;
                   8252:                     my $type = 'map';
                   8253:                     if ($item eq 'course') {
                   8254:                         $type = 'course';
                   8255:                         @interval=&EXT("resource.0.interval");
                   8256:                     } else {
                   8257:                         if ($item =~ /___\d+___/) {
                   8258:                             $type = 'resource';
                   8259:                             @interval=&EXT("resource.0.interval",$item);
                   8260:                             if (ref($navmap)) {                        
                   8261:                                 my $res = $navmap->getBySymb($item); 
                   8262:                                 push(@to_test,$res);
                   8263:                             }
1.1162    raeburn  8264:                         } else {
1.1282    raeburn  8265:                             my $mapsymb = &symbread($item,1);
                   8266:                             if ($mapsymb) {
                   8267:                                 if (ref($navmap)) {
                   8268:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8269:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8270:                                     foreach my $res (@to_test) {
                   8271:                                         my $symb = $res->symb();
                   8272:                                         next if ($symb eq $mapsymb);
                   8273:                                         if ($symb ne '') {
                   8274:                                             @interval=&EXT("resource.0.interval",$symb);
                   8275:                                             if ($interval[1] eq 'map') {
                   8276:                                                 last;
1.1162    raeburn  8277:                                             }
                   8278:                                         }
                   8279:                                     }
                   8280:                                 }
                   8281:                             }
                   8282:                         }
1.1282    raeburn  8283:                     }
1.1310    raeburn  8284:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8285:                         my $timelimit = $1; 
1.1282    raeburn  8286:                         my $first_access;
                   8287:                         if ($type eq 'resource') {
                   8288:                             $first_access=&get_first_access($interval[1],$item);
                   8289:                         } elsif ($type eq 'map') {
                   8290:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8291:                         } else {
                   8292:                             $first_access=&get_first_access($interval[1]);
                   8293:                         }
                   8294:                         if ($first_access) {
1.1292    raeburn  8295:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8296:                             if ($timesup > $now) {
                   8297:                                 my $activeblock;
                   8298:                                 foreach my $res (@to_test) {
1.1283    raeburn  8299:                                     if ($res->answerable()) {
1.1282    raeburn  8300:                                         $activeblock = 1;
                   8301:                                         last;
                   8302:                                     }
                   8303:                                 }
                   8304:                                 if ($activeblock) {
                   8305:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8306:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8307:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8308:                                          }
                   8309:                                     }
                   8310:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8311:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8312:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8313:                                         }
1.1162    raeburn  8314:                                     }
                   8315:                                 }
                   8316:                             }
                   8317:                         }
                   8318:                     }
                   8319:                 }
                   8320:             }
                   8321:         }
                   8322:     }
1.1282    raeburn  8323:     return %blockers;
1.1162    raeburn  8324: }
                   8325: 
1.1282    raeburn  8326: sub has_comm_blocking {
                   8327:     my ($priv,$symb,$uri,$blocks) = @_;
                   8328:     my @blockers;
                   8329:     return unless ($env{'request.course.id'});
                   8330:     return unless ($priv eq 'bre');
                   8331:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8332:     return if ($env{'request.state'} eq 'construct');
                   8333:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8334:     return unless (keys(%cachedblockers) > 0);
                   8335:     my (%possibles,@symbs);
                   8336:     if (!$symb) {
                   8337:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8338:     }
1.1282    raeburn  8339:     if ($symb) {
                   8340:         @symbs = ($symb);
                   8341:     } elsif (keys(%possibles)) { 
                   8342:         @symbs = keys(%possibles);
                   8343:     }
                   8344:     my $noblock;
                   8345:     foreach my $symb (@symbs) {
                   8346:         last if ($noblock);
                   8347:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8348:         foreach my $block (keys(%cachedblockers)) {
                   8349:             if ($block =~ /^firstaccess____(.+)$/) {
                   8350:                 my $item = $1;
                   8351:                 if (($item eq $map) || ($item eq $symb)) {
                   8352:                     $noblock = 1;
                   8353:                     last;
                   8354:                 }
                   8355:             }
                   8356:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8357:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8358:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8359:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8360:                             push(@blockers,$block);
                   8361:                         }
                   8362:                     }
                   8363:                 }
1.1162    raeburn  8364:             }
1.1282    raeburn  8365:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8366:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8367:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8368:                         push(@blockers,$block);
                   8369:                     }
                   8370:                 }
1.1162    raeburn  8371:             }
                   8372:         }
                   8373:     }
1.1282    raeburn  8374:     return if ($noblock);
                   8375:     return @blockers;
                   8376: }
1.1162    raeburn  8377: }
                   8378: 
1.1282    raeburn  8379: # -------------------------------- Deversion and split uri into path an filename   
                   8380: 
1.1133    foxr     8381: #
1.1282    raeburn  8382: #   Removes the version from a URI and
1.1133    foxr     8383: #   splits it in to its filename and path to the filename.
                   8384: #   Seems like File::Basename could have done this more clearly.
                   8385: #   Parameters:
                   8386: #      $uri   - input URI
                   8387: #   Returns:
                   8388: #     Two element list consisting of 
                   8389: #     $pathname  - the URI up to and excluding the trailing /
                   8390: #     $filename  - The part of the URI following the last /
                   8391: #  NOTE:
                   8392: #    Another realization of this is simply:
                   8393: #    use File::Basename;
                   8394: #    ...
                   8395: #    $uri = shift;
                   8396: #    $filename = basename($uri);
                   8397: #    $path     = dirname($uri);
                   8398: #    return ($filename, $path);
                   8399: #
                   8400: #     The implementation below is probably faster however.
                   8401: #
1.710     albertel 8402: sub split_uri_for_cond {
                   8403:     my $uri=&deversion(&declutter(shift));
                   8404:     my @uriparts=split(/\//,$uri);
                   8405:     my $filename=pop(@uriparts);
                   8406:     my $pathname=join('/',@uriparts);
                   8407:     return ($pathname,$filename);
                   8408: }
1.232     www      8409: # --------------------------------------------------- Is a resource on the map?
                   8410: 
                   8411: sub is_on_map {
1.710     albertel 8412:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8413:     #Trying to find the conditional for the file
1.620     albertel 8414:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8415: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8416:     if ($match) {
1.289     bowersj2 8417: 	return (1,$1);
                   8418:     } else {
1.434     www      8419: 	return (0,0);
1.289     bowersj2 8420:     }
1.12      www      8421: }
                   8422: 
1.427     www      8423: # --------------------------------------------------------- Get symb from alias
                   8424: 
                   8425: sub get_symb_from_alias {
                   8426:     my $symb=shift;
                   8427:     my ($map,$resid,$url)=&decode_symb($symb);
                   8428: # Already is a symb
                   8429:     if ($url) { return $symb; }
                   8430: # Must be an alias
                   8431:     my $aliassymb='';
                   8432:     my %bighash;
1.620     albertel 8433:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8434:                             &GDBM_READER(),0640)) {
                   8435:         my $rid=$bighash{'mapalias_'.$symb};
                   8436: 	if ($rid) {
                   8437: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8438: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8439: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8440: 	}
                   8441:         untie %bighash;
                   8442:     }
                   8443:     return $aliassymb;
                   8444: }
                   8445: 
1.12      www      8446: # ----------------------------------------------------------------- Define Role
                   8447: 
                   8448: sub definerole {
                   8449:   if (allowed('mcr','/')) {
1.1326    raeburn  8450:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8451:     foreach my $role (split(':',$sysrole)) {
                   8452: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8453:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8454:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8455: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8456:                return "refused:s:$crole&$cqual"; 
                   8457:             }
                   8458:         }
1.191     harris41 8459:     }
1.800     albertel 8460:     foreach my $role (split(':',$domrole)) {
                   8461: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8462:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8463:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8464: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8465:                return "refused:d:$crole&$cqual"; 
                   8466:             }
                   8467:         }
1.191     harris41 8468:     }
1.800     albertel 8469:     foreach my $role (split(':',$courole)) {
                   8470: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8471:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8472:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8473: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8474:                return "refused:c:$crole&$cqual"; 
                   8475:             }
                   8476:         }
1.191     harris41 8477:     }
1.1326    raeburn  8478:     my $uhome;
                   8479:     if (($uname ne '') && ($udom ne '')) {
                   8480:         $uhome = &homeserver($uname,$udom);
                   8481:         return $uhome if ($uhome eq 'no_host');
                   8482:     } else {
                   8483:         $uname = $env{'user.name'};
                   8484:         $udom = $env{'user.domain'};
                   8485:         $uhome = $env{'user.home'};
                   8486:     }
1.620     albertel 8487:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8488:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8489:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8490:     return reply($command,$uhome);
1.12      www      8491:   } else {
                   8492:     return 'refused';
                   8493:   }
1.105     harris41 8494: }
                   8495: 
                   8496: # ---------------- Make a metadata query against the network of library servers
                   8497: 
                   8498: sub metadata_query {
1.1237    raeburn  8499:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8500:     my %rhash;
1.845     albertel 8501:     my %libserv = &all_library();
1.244     matthew  8502:     my @server_list = (defined($server_array) ? @$server_array
                   8503:                                               : keys(%libserv) );
                   8504:     for my $server (@server_list) {
1.1237    raeburn  8505:         my $domains = ''; 
                   8506:         if (ref($domains_hash) eq 'HASH') {
                   8507:             $domains = $domains_hash->{$server}; 
                   8508:         }
1.118     harris41 8509: 	unless ($custom or $customshow) {
1.1237    raeburn  8510: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8511: 	    $rhash{$server}=$reply;
                   8512: 	}
                   8513: 	else {
                   8514: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8515: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8516: 			     $server);
                   8517: 	    $rhash{$server}=$reply;
                   8518: 	}
1.112     harris41 8519:     }
1.118     harris41 8520:     return \%rhash;
1.240     www      8521: }
                   8522: 
                   8523: # ----------------------------------------- Send log queries and wait for reply
                   8524: 
                   8525: sub log_query {
                   8526:     my ($uname,$udom,$query,%filters)=@_;
                   8527:     my $uhome=&homeserver($uname,$udom);
                   8528:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8529:     my $uhost=&hostname($uhome);
1.800     albertel 8530:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8531:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8532:                        $uhome);
1.479     albertel 8533:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8534:     return get_query_reply($queryid);
                   8535: }
                   8536: 
1.818     raeburn  8537: # -------------------------- Update MySQL table for portfolio file
                   8538: 
                   8539: sub update_portfolio_table {
1.821     raeburn  8540:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8541:     if ($group ne '') {
                   8542:         $file_name =~s /^\Q$group\E//;
                   8543:     }
1.818     raeburn  8544:     my $homeserver = &homeserver($uname,$udom);
                   8545:     my $queryid=
1.821     raeburn  8546:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8547:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8548:     my $reply = &get_query_reply($queryid);
                   8549:     return $reply;
                   8550: }
                   8551: 
1.899     raeburn  8552: # -------------------------- Update MySQL allusers table
                   8553: 
                   8554: sub update_allusers_table {
                   8555:     my ($uname,$udom,$names) = @_;
                   8556:     my $homeserver = &homeserver($uname,$udom);
                   8557:     my $queryid=
                   8558:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8559:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8560:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8561:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8562:                'generation='.&escape($names->{'generation'}).'%%'.
                   8563:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8564:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8565:     return;
1.899     raeburn  8566: }
                   8567: 
1.508     raeburn  8568: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8569: 
                   8570: sub fetch_enrollment_query {
1.511     raeburn  8571:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8572:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8573:     my $maxtries = 1;
1.508     raeburn  8574:     if ($context eq 'automated') {
                   8575:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8576:         $sleep = 2;
                   8577:         $loopmax = 100;
1.547     raeburn  8578:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8579:     } else {
                   8580:         $homeserver = &homeserver($cnum,$dom);
                   8581:     }
1.838     albertel 8582:     my $host=&hostname($homeserver);
1.506     raeburn  8583:     my $cmd = '';
1.1000    raeburn  8584:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8585:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8586:     }
                   8587:     $cmd =~ s/%%$//;
                   8588:     $cmd = &escape($cmd);
                   8589:     my $query = 'fetchenrollment';
1.620     albertel 8590:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8591:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8592:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8593:         return 'error: '.$queryid;
                   8594:     }
1.1317    raeburn  8595:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8596:     my $tries = 1;
                   8597:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8598:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8599:         $tries ++;
                   8600:     }
1.526     raeburn  8601:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8602:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8603:     } else {
1.901     albertel 8604:         my @responses = split(/:/,$reply);
1.1322    raeburn  8605:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8606:             foreach my $line (@responses) {
                   8607:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8608:                 $$replyref{$key} = $value;
                   8609:             }
                   8610:         } else {
1.1117    foxr     8611:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8612:             foreach my $line (@responses) {
                   8613:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8614:                 $$replyref{$key} = $value;
                   8615:                 if ($value > 0) {
1.800     albertel 8616:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8617:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8618:                         my $destname = $pathname.'/'.$filename;
                   8619:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8620:                         if ($xml_classlist =~ /^error/) {
                   8621:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8622:                         } else {
1.1359    raeburn  8623:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8624:                                 print FILE &unescape($xml_classlist);
                   8625:                                 close(FILE);
1.526     raeburn  8626:                             } else {
                   8627:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8628:                             }
                   8629:                         }
                   8630:                     }
                   8631:                 }
                   8632:             }
                   8633:         }
                   8634:         return 'ok';
                   8635:     }
                   8636:     return 'error';
                   8637: }
                   8638: 
1.242     www      8639: sub get_query_reply {
1.1317    raeburn  8640:     my ($queryid,$sleep,$loopmax) = @_;;
                   8641:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8642:         $sleep = 0.2;
                   8643:     }
                   8644:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8645:         $loopmax = 100;
                   8646:     }
1.1117    foxr     8647:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8648:     my $reply='';
1.1317    raeburn  8649:     for (1..$loopmax) {
                   8650: 	sleep($sleep);
1.240     www      8651:         if (-e $replyfile.'.end') {
1.1359    raeburn  8652: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8653: 		$reply = join('',<$fh>);
                   8654: 		close($fh);
1.240     www      8655: 	   } else { return 'error: reply_file_error'; }
1.242     www      8656:            return &unescape($reply);
                   8657: 	}
1.240     www      8658:     }
1.242     www      8659:     return 'timeout:'.$queryid;
1.240     www      8660: }
                   8661: 
                   8662: sub courselog_query {
1.241     www      8663: #
                   8664: # possible filters:
                   8665: # url: url or symb
                   8666: # username
                   8667: # domain
                   8668: # action: view, submit, grade
                   8669: # start: timestamp
                   8670: # end: timestamp
                   8671: #
1.240     www      8672:     my (%filters)=@_;
1.620     albertel 8673:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8674:     if ($filters{'url'}) {
                   8675: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8676:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8677:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8678:     }
1.620     albertel 8679:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8680:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8681:     return &log_query($cname,$cdom,'courselog',%filters);
                   8682: }
                   8683: 
                   8684: sub userlog_query {
1.858     raeburn  8685: #
                   8686: # possible filters:
                   8687: # action: log check role
                   8688: # start: timestamp
                   8689: # end: timestamp
                   8690: #
1.240     www      8691:     my ($uname,$udom,%filters)=@_;
                   8692:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8693: }
                   8694: 
1.506     raeburn  8695: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8696: 
                   8697: sub auto_run {
1.508     raeburn  8698:     my ($cnum,$cdom) = @_;
1.876     raeburn  8699:     my $response = 0;
                   8700:     my $settings;
                   8701:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8702:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8703:         $settings = $domconfig{'autoenroll'};
                   8704:         if ($settings->{'run'} eq '1') {
                   8705:             $response = 1;
                   8706:         }
                   8707:     } else {
1.934     raeburn  8708:         my $homeserver;
                   8709:         if (&is_course($cdom,$cnum)) {
                   8710:             $homeserver = &homeserver($cnum,$cdom);
                   8711:         } else {
                   8712:             $homeserver = &domain($cdom,'primary');
                   8713:         }
                   8714:         if ($homeserver ne 'no_host') {
                   8715:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8716:         }
1.876     raeburn  8717:     }
1.506     raeburn  8718:     return $response;
                   8719: }
1.776     albertel 8720: 
1.506     raeburn  8721: sub auto_get_sections {
1.508     raeburn  8722:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8723:     my $homeserver;
                   8724:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8725:         $homeserver = &homeserver($cnum,$cdom);
                   8726:     }
                   8727:     if (!defined($homeserver)) { 
                   8728:         if ($cdom =~ /^$match_domain$/) {
                   8729:             $homeserver = &domain($cdom,'primary');
                   8730:         }
                   8731:     }
                   8732:     my @secs;
                   8733:     if (defined($homeserver)) {
                   8734:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8735:         unless ($response eq 'refused') {
                   8736:             @secs = split(/:/,$response);
                   8737:         }
1.506     raeburn  8738:     }
                   8739:     return @secs;
                   8740: }
1.776     albertel 8741: 
1.506     raeburn  8742: sub auto_new_course {
1.1099    raeburn  8743:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8744:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8745:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8746:     return $response;
                   8747: }
1.776     albertel 8748: 
1.506     raeburn  8749: sub auto_validate_courseID {
1.508     raeburn  8750:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8751:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8752:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8753:     return $response;
                   8754: }
1.776     albertel 8755: 
1.1007    raeburn  8756: sub auto_validate_instcode {
1.1020    raeburn  8757:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8758:     my ($homeserver,$response);
                   8759:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8760:         $homeserver = &homeserver($cnum,$cdom);
                   8761:     }
                   8762:     if (!defined($homeserver)) {
                   8763:         if ($cdom =~ /^$match_domain$/) {
                   8764:             $homeserver = &domain($cdom,'primary');
                   8765:         }
                   8766:     }
1.1065    raeburn  8767:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8768:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8769:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8770:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8771: }
                   8772: 
1.506     raeburn  8773: sub auto_create_password {
1.873     raeburn  8774:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8775:     my ($homeserver,$response);
1.506     raeburn  8776:     my $create_passwd = 0;
                   8777:     my $authchk = '';
1.873     raeburn  8778:     if ($udom =~ /^$match_domain$/) {
                   8779:         $homeserver = &domain($udom,'primary');
                   8780:     }
                   8781:     if ($homeserver eq '') {
                   8782:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8783:             $homeserver = &homeserver($cnum,$cdom);
                   8784:         }
                   8785:     }
                   8786:     if ($homeserver eq '') {
                   8787:         $authchk = 'nodomain';
1.506     raeburn  8788:     } else {
1.873     raeburn  8789:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8790:         if ($response eq 'refused') {
                   8791:             $authchk = 'refused';
                   8792:         } else {
1.901     albertel 8793:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8794:         }
1.506     raeburn  8795:     }
                   8796:     return ($authparam,$create_passwd,$authchk);
                   8797: }
                   8798: 
1.706     raeburn  8799: sub auto_photo_permission {
                   8800:     my ($cnum,$cdom,$students) = @_;
                   8801:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8802:     my ($outcome,$perm_reqd,$conditions) = 
                   8803: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8804:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8805: 	return (undef,undef);
                   8806:     }
1.706     raeburn  8807:     return ($outcome,$perm_reqd,$conditions);
                   8808: }
                   8809: 
                   8810: sub auto_checkphotos {
                   8811:     my ($uname,$udom,$pid) = @_;
                   8812:     my $homeserver = &homeserver($uname,$udom);
                   8813:     my ($result,$resulttype);
                   8814:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8815: 				   &escape($uname).':'.&escape($pid),
                   8816: 				   $homeserver));
1.709     albertel 8817:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8818: 	return (undef,undef);
                   8819:     }
1.706     raeburn  8820:     if ($outcome) {
                   8821:         ($result,$resulttype) = split(/:/,$outcome);
                   8822:     } 
                   8823:     return ($result,$resulttype);
                   8824: }
                   8825: 
                   8826: sub auto_photochoice {
                   8827:     my ($cnum,$cdom) = @_;
                   8828:     my $homeserver = &homeserver($cnum,$cdom);
                   8829:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8830: 						       &escape($cdom),
                   8831: 						       $homeserver)));
1.709     albertel 8832:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8833: 	return (undef,undef);
                   8834:     }
1.706     raeburn  8835:     return ($update,$comment);
                   8836: }
                   8837: 
                   8838: sub auto_photoupdate {
                   8839:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8840:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8841:     my $host=&hostname($homeserver);
1.706     raeburn  8842:     my $cmd = '';
                   8843:     my $maxtries = 1;
1.800     albertel 8844:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8845:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8846:     }
                   8847:     $cmd =~ s/%%$//;
                   8848:     $cmd = &escape($cmd);
                   8849:     my $query = 'institutionalphotos';
                   8850:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8851:     unless ($queryid=~/^\Q$host\E\_/) {
                   8852:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8853:         return 'error: '.$queryid;
                   8854:     }
                   8855:     my $reply = &get_query_reply($queryid);
                   8856:     my $tries = 1;
                   8857:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8858:         $reply = &get_query_reply($queryid);
                   8859:         $tries ++;
                   8860:     }
                   8861:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8862:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8863:     } else {
                   8864:         my @responses = split(/:/,$reply);
                   8865:         my $outcome = shift(@responses); 
                   8866:         foreach my $item (@responses) {
                   8867:             my ($key,$value) = split(/=/,$item);
                   8868:             $$photo{$key} = $value;
                   8869:         }
                   8870:         return $outcome;
                   8871:     }
                   8872:     return 'error';
                   8873: }
                   8874: 
1.521     raeburn  8875: sub auto_instcode_format {
1.793     albertel 8876:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8877: 	$cat_order) = @_;
1.521     raeburn  8878:     my $courses = '';
1.772     raeburn  8879:     my @homeservers;
1.521     raeburn  8880:     if ($caller eq 'global') {
1.841     albertel 8881: 	my %servers = &get_servers($codedom,'library');
                   8882: 	foreach my $tryserver (keys(%servers)) {
                   8883: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8884: 		push(@homeservers,$tryserver);
                   8885: 	    }
1.584     raeburn  8886:         }
1.1022    raeburn  8887:     } elsif ($caller eq 'requests') {
                   8888:         if ($codedom =~ /^$match_domain$/) {
                   8889:             my $chome = &domain($codedom,'primary');
                   8890:             unless ($chome eq 'no_host') {
                   8891:                 push(@homeservers,$chome);
                   8892:             }
                   8893:         }
1.521     raeburn  8894:     } else {
1.772     raeburn  8895:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8896:     }
1.793     albertel 8897:     foreach my $code (keys(%{$instcodes})) {
                   8898:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8899:     }
                   8900:     chop($courses);
1.772     raeburn  8901:     my $ok_response = 0;
                   8902:     my $response;
                   8903:     while (@homeservers > 0 && $ok_response == 0) {
                   8904:         my $server = shift(@homeservers); 
                   8905:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8906:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8907:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8908: 		split(/:/,$response);
1.772     raeburn  8909:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8910:             push(@{$codetitles},&str2array($codetitles_str));
                   8911:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8912:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8913:             $ok_response = 1;
                   8914:         }
                   8915:     }
                   8916:     if ($ok_response) {
1.521     raeburn  8917:         return 'ok';
1.772     raeburn  8918:     } else {
                   8919:         return $response;
1.521     raeburn  8920:     }
                   8921: }
                   8922: 
1.792     raeburn  8923: sub auto_instcode_defaults {
                   8924:     my ($domain,$returnhash,$code_order) = @_;
                   8925:     my @homeservers;
1.841     albertel 8926: 
                   8927:     my %servers = &get_servers($domain,'library');
                   8928:     foreach my $tryserver (keys(%servers)) {
                   8929: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8930: 	    push(@homeservers,$tryserver);
                   8931: 	}
1.792     raeburn  8932:     }
1.841     albertel 8933: 
1.792     raeburn  8934:     my $response;
1.841     albertel 8935:     foreach my $server (@homeservers) {
1.792     raeburn  8936:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8937:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8938: 	
                   8939: 	foreach my $pair (split(/\&/,$response)) {
                   8940: 	    my ($name,$value)=split(/\=/,$pair);
                   8941: 	    if ($name eq 'code_order') {
                   8942: 		@{$code_order} = split(/\&/,&unescape($value));
                   8943: 	    } else {
                   8944: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8945: 	    }
                   8946: 	}
                   8947: 	return 'ok';
1.792     raeburn  8948:     }
1.841     albertel 8949: 
                   8950:     return $response;
1.1003    raeburn  8951: }
                   8952: 
                   8953: sub auto_possible_instcodes {
1.1007    raeburn  8954:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8955:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8956:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8957:         return;
                   8958:     }
1.1003    raeburn  8959:     my (@homeservers,$uhome);
                   8960:     if (defined(&domain($domain,'primary'))) {
                   8961:         $uhome=&domain($domain,'primary');
                   8962:         push(@homeservers,&domain($domain,'primary'));
                   8963:     } else {
                   8964:         my %servers = &get_servers($domain,'library');
                   8965:         foreach my $tryserver (keys(%servers)) {
                   8966:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8967:                 push(@homeservers,$tryserver);
                   8968:             }
                   8969:         }
                   8970:     }
                   8971:     my $response;
                   8972:     foreach my $server (@homeservers) {
                   8973:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8974:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8975:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8976:             split(':',$response);
                   8977:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8978:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8979:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8980:             my ($name,$value)=split('=',$item);
                   8981:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8982:         }
                   8983:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8984:             my ($name,$value)=split('=',$item);
                   8985:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8986:         }
                   8987:         return 'ok';
                   8988:     }
                   8989:     return $response;
                   8990: }
1.792     raeburn  8991: 
1.1010    raeburn  8992: sub auto_courserequest_checks {
                   8993:     my ($dom) = @_;
1.1020    raeburn  8994:     my ($homeserver,%validations);
                   8995:     if ($dom =~ /^$match_domain$/) {
                   8996:         $homeserver = &domain($dom,'primary');
                   8997:     }
                   8998:     unless ($homeserver eq 'no_host') {
                   8999:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9000:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9001:             my @items = split(/&/,$response);
                   9002:             foreach my $item (@items) {
                   9003:                 my ($key,$value) = split('=',$item);
                   9004:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9005:             }
                   9006:         }
                   9007:     }
1.1010    raeburn  9008:     return %validations; 
                   9009: }
                   9010: 
1.1020    raeburn  9011: sub auto_courserequest_validation {
1.1255    raeburn  9012:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9013:     my ($homeserver,$response);
                   9014:     if ($dom =~ /^$match_domain$/) {
                   9015:         $homeserver = &domain($dom,'primary');
                   9016:     }
1.1255    raeburn  9017:     unless ($homeserver eq 'no_host') {
                   9018:         my $customdata;
                   9019:         if (ref($custominfo) eq 'HASH') {
                   9020:             $customdata = &freeze_escape($custominfo);
                   9021:         }
1.1020    raeburn  9022:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9023:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9024:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9025:                                     $customdata,$homeserver));
1.1020    raeburn  9026:     }
                   9027:     return $response;
                   9028: }
                   9029: 
1.777     albertel 9030: sub auto_validate_class_sec {
1.918     raeburn  9031:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9032:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9033:     my $ownerlist;
                   9034:     if (ref($owners) eq 'ARRAY') {
                   9035:         $ownerlist = join(',',@{$owners});
                   9036:     } else {
                   9037:         $ownerlist = $owners;
                   9038:     }
1.773     raeburn  9039:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9040:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9041:     return $response;
                   9042: }
                   9043: 
1.1367    raeburn  9044: sub auto_validate_instclasses {
                   9045:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9046:     my ($homeserver,%validations);
                   9047:     $homeserver = &homeserver($cnum,$cdom);
                   9048:     unless ($homeserver eq 'no_host') {
                   9049:         my $ownerlist;
                   9050:         if (ref($owners) eq 'ARRAY') {
                   9051:             $ownerlist = join(',',@{$owners});
                   9052:         } else {
                   9053:             $ownerlist = $owners;
                   9054:         }
                   9055:         if (ref($classesref) eq 'HASH') {
                   9056:             my $classes = &freeze_escape($classesref);
                   9057:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9058:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9059:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9060:                 my @items = split(/&/,$response);
                   9061:                 foreach my $item (@items) {
                   9062:                     my ($key,$value) = split('=',$item);
                   9063:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9064:                 }
                   9065:             }
                   9066:         }
                   9067:     }
                   9068:     return %validations;
                   9069: }
                   9070: 
1.1248    raeburn  9071: sub auto_crsreq_update {
                   9072:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9073:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9074:     my ($homeserver,%crsreqresponse);
                   9075:     if ($cdom =~ /^$match_domain$/) {
                   9076:         $homeserver = &domain($cdom,'primary');
                   9077:     }
                   9078:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9079:         my $info;
                   9080:         if (ref($inbound) eq 'HASH') {
                   9081:             $info = &freeze_escape($inbound);
                   9082:         }
                   9083:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9084:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9085:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9086:                             &escape($title).':'.&escape($code).':'.
                   9087:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9088:                             $homeserver);
1.1248    raeburn  9089:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9090:             my @items = split(/&/,$response);
                   9091:             foreach my $item (@items) {
                   9092:                 my ($key,$value) = split('=',$item);
                   9093:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9094:             }
                   9095:         }
                   9096:     }
                   9097:     return \%crsreqresponse;
                   9098: }
                   9099: 
1.1305    raeburn  9100: sub auto_export_grades {
1.1309    raeburn  9101:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9102:     my ($homeserver,%exportresponse);
                   9103:     if ($cdom =~ /^$match_domain$/) {
                   9104:         $homeserver = &domain($cdom,'primary');
                   9105:     }
                   9106:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9107:         my $info;
                   9108:         if (ref($inforef) eq 'HASH') {
                   9109:             $info = &freeze_escape($inforef);
                   9110:         }
                   9111:         if (ref($gradesref) eq 'HASH') {
                   9112:             my $grades = &freeze_escape($gradesref);
                   9113:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9114:                                 $info.':'.$grades,$homeserver);
                   9115:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9116:                 my @items = split(/&/,$response);
                   9117:                 foreach my $item (@items) {
                   9118:                     my ($key,$value) = split('=',$item);
                   9119:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9120:                 }
                   9121:             }
                   9122:         }
                   9123:     }
                   9124:     return \%exportresponse;
1.1305    raeburn  9125: }
                   9126: 
1.1287    raeburn  9127: sub check_instcode_cloning {
                   9128:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9129:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9130:         return;
                   9131:     }
                   9132:     my $canclone;
                   9133:     if (@{$code_order} > 0) {
                   9134:         my $instcoderegexp ='^';
                   9135:         my @clonecodes = split(/\&/,$cloner);
                   9136:         foreach my $item (@{$code_order}) {
                   9137:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9138:                 foreach my $pair (@clonecodes) {
                   9139:                     my ($key,$val) = split(/\=/,$pair,2);
                   9140:                     $val = &unescape($val);
                   9141:                     if ($key eq $item) {
                   9142:                         $instcoderegexp .= '('.$val.')';
                   9143:                         last;
                   9144:                     }
                   9145:                 }
                   9146:             } else {
                   9147:                 $instcoderegexp .= $codedefaults->{$item};
                   9148:             }
                   9149:         }
                   9150:         $instcoderegexp .= '$';
                   9151:         my (@from,@to);
                   9152:         eval {
                   9153:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9154:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9155:         };
                   9156:         if ((@from > 0) && (@to > 0)) {
                   9157:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9158:             if (!@diffs) {
                   9159:                 $canclone = 1;
                   9160:             }
                   9161:         }
                   9162:     }
                   9163:     return $canclone;
                   9164: }
                   9165: 
                   9166: sub default_instcode_cloning {
                   9167:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9168:     my (%codedefaults,@code_order,$canclone);
                   9169:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9170:         %codedefaults = %{$codedefaultsref};
                   9171:         @code_order = @{$codeorderref};
                   9172:     } elsif ($clonedom) {
                   9173:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9174:     }
                   9175:     if (($domdefclone) && (@code_order)) {
                   9176:         my @clonecodes = split(/\+/,$domdefclone);
                   9177:         my $instcoderegexp ='^';
                   9178:         foreach my $item (@code_order) {
                   9179:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9180:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9181:             } else {
                   9182:                 $instcoderegexp .= $codedefaults{$item};
                   9183:             }
                   9184:         }
                   9185:         $instcoderegexp .= '$';
                   9186:         my (@from,@to);
                   9187:         eval {
                   9188:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9189:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9190:         };
                   9191:         if ((@from > 0) && (@to > 0)) {
                   9192:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9193:             if (!@diffs) {
                   9194:                 $canclone = 1;
                   9195:             }
                   9196:         }
                   9197:     }
                   9198:     return $canclone;
                   9199: }
                   9200: 
1.679     raeburn  9201: # ------------------------------------------------------- Course Group routines
                   9202: 
                   9203: sub get_coursegroups {
1.809     raeburn  9204:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9205:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9206: }
                   9207: 
1.679     raeburn  9208: sub modify_coursegroup {
                   9209:     my ($cdom,$cnum,$groupsettings) = @_;
                   9210:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9211: }
                   9212: 
1.809     raeburn  9213: sub toggle_coursegroup_status {
                   9214:     my ($cdom,$cnum,$group,$action) = @_;
                   9215:     my ($from_namespace,$to_namespace);
                   9216:     if ($action eq 'delete') {
                   9217:         $from_namespace = 'coursegroups';
                   9218:         $to_namespace = 'deleted_groups';
                   9219:     } else {
                   9220:         $from_namespace = 'deleted_groups';
                   9221:         $to_namespace = 'coursegroups';
                   9222:     }
                   9223:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9224:     if (my $tmp = &error(%curr_group)) {
                   9225:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9226:         return ('read error',$tmp);
                   9227:     } else {
                   9228:         my %savedsettings = %curr_group; 
1.809     raeburn  9229:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9230:         my $deloutcome;
                   9231:         if ($result eq 'ok') {
1.809     raeburn  9232:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9233:         } else {
                   9234:             return ('write error',$result);
                   9235:         }
                   9236:         if ($deloutcome eq 'ok') {
                   9237:             return 'ok';
                   9238:         } else {
                   9239:             return ('delete error',$deloutcome);
                   9240:         }
                   9241:     }
                   9242: }
                   9243: 
1.679     raeburn  9244: sub modify_group_roles {
1.957     raeburn  9245:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9246:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9247:     my $role = 'gr/'.&escape($userprivs);
                   9248:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9249:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9250:     if ($result eq 'ok') {
                   9251:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9252:     }
1.679     raeburn  9253:     return $result;
                   9254: }
                   9255: 
                   9256: sub modify_coursegroup_membership {
                   9257:     my ($cdom,$cnum,$membership) = @_;
                   9258:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9259:     return $result;
                   9260: }
                   9261: 
1.682     raeburn  9262: sub get_active_groups {
                   9263:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9264:     my $now = time;
                   9265:     my %groups = ();
                   9266:     foreach my $key (keys(%env)) {
1.811     albertel 9267:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9268:             my ($start,$end) = split(/\./,$env{$key});
                   9269:             if (($end!=0) && ($end<$now)) { next; }
                   9270:             if (($start!=0) && ($start>$now)) { next; }
                   9271:             if ($1 eq $cdom && $2 eq $cnum) {
                   9272:                 $groups{$3} = $env{$key} ;
                   9273:             }
                   9274:         }
                   9275:     }
                   9276:     return %groups;
                   9277: }
                   9278: 
1.683     raeburn  9279: sub get_group_membership {
                   9280:     my ($cdom,$cnum,$group) = @_;
                   9281:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9282: }
                   9283: 
                   9284: sub get_users_groups {
                   9285:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9286:     my @usersgroups;
1.683     raeburn  9287:     my $cachetime=1800;
                   9288: 
                   9289:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9290:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9291:     if (defined($cached)) {
1.734     albertel 9292:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9293:     } else {  
                   9294:         $grouplist = '';
1.816     raeburn  9295:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9296:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9297:         my $access_end = $env{'course.'.$courseid.
                   9298:                               '.default_enrollment_end_date'};
                   9299:         my $now = time;
                   9300:         foreach my $key (keys(%roleshash)) {
                   9301:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9302:                 my $group = $1;
                   9303:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9304:                     my $start = $2;
                   9305:                     my $end = $1;
                   9306:                     if ($start == -1) { next; } # deleted from group
                   9307:                     if (($start!=0) && ($start>$now)) { next; }
                   9308:                     if (($end!=0) && ($end<$now)) {
                   9309:                         if ($access_end && $access_end < $now) {
                   9310:                             if ($access_end - $end < 86400) {
                   9311:                                 push(@usersgroups,$group);
1.733     raeburn  9312:                             }
                   9313:                         }
1.817     raeburn  9314:                         next;
1.733     raeburn  9315:                     }
1.817     raeburn  9316:                     push(@usersgroups,$group);
1.683     raeburn  9317:                 }
                   9318:             }
                   9319:         }
1.817     raeburn  9320:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9321:         $grouplist = join(':',@usersgroups);
                   9322:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9323:     }
1.733     raeburn  9324:     return @usersgroups;
1.683     raeburn  9325: }
                   9326: 
                   9327: sub devalidate_getgroups_cache {
                   9328:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9329:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9330: 
1.683     raeburn  9331:     my $hashid="$udom:$uname:$courseid";
                   9332:     &devalidate_cache_new('getgroups',$hashid);
                   9333: }
                   9334: 
1.12      www      9335: # ------------------------------------------------------------------ Plain Text
                   9336: 
                   9337: sub plaintext {
1.988     raeburn  9338:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9339:     if ($short =~ m{^cr/}) {
1.758     albertel 9340: 	return (split('/',$short))[-1];
                   9341:     }
1.742     raeburn  9342:     if (!defined($cid)) {
                   9343:         $cid = $env{'request.course.id'};
                   9344:     }
                   9345:     my %rolenames = (
1.1008    raeburn  9346:                       Course    => 'std',
                   9347:                       Community => 'alt1',
1.1305    raeburn  9348:                       Placement => 'std',
1.742     raeburn  9349:                     );
1.1037    raeburn  9350:     if ($cid ne '') {
                   9351:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9352:             unless ($forcedefault) {
                   9353:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9354:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9355:                 return &Apache::lonlocal::mt($roletext);
                   9356:             }
                   9357:         }
                   9358:     }
                   9359:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9360:         (defined($rolenames{$type})) && 
                   9361:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9362:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9363:     } elsif ($cid ne '') {
                   9364:         my $crstype = $env{'course.'.$cid.'.type'};
                   9365:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9366:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9367:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9368:         }
1.742     raeburn  9369:     }
1.1037    raeburn  9370:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9371: }
                   9372: 
                   9373: # ----------------------------------------------------------------- Assign Role
                   9374: 
                   9375: sub assignrole {
1.957     raeburn  9376:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9377:         $context)=@_;
1.21      www      9378:     my $mrole;
                   9379:     if ($role =~ /^cr\//) {
1.393     www      9380:         my $cwosec=$url;
1.811     albertel 9381:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9382: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9383:            my $refused = 1;
                   9384:            if ($context eq 'requestcourses') {
                   9385:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9386:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9387:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9388:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9389:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9390:                            if ($crsenv{'internal.courseowner'} eq
                   9391:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9392:                                $refused = '';
                   9393:                            }
                   9394:                        }
                   9395:                    }
                   9396:                }
                   9397:            }
                   9398:            if ($refused) {
                   9399:                &logthis('Refused custom assignrole: '.
                   9400:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9401:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9402:                return 'refused';
                   9403:            }
1.104     www      9404:         }
1.21      www      9405:         $mrole='cr';
1.678     raeburn  9406:     } elsif ($role =~ /^gr\//) {
                   9407:         my $cwogrp=$url;
1.811     albertel 9408:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9409:         unless (&allowed('mdg',$cwogrp)) {
                   9410:             &logthis('Refused group assignrole: '.
                   9411:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9412:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9413:             return 'refused';
                   9414:         }
                   9415:         $mrole='gr';
1.21      www      9416:     } else {
1.82      www      9417:         my $cwosec=$url;
1.811     albertel 9418:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9419:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9420:             my $refused;
                   9421:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9422:                 if (!(&allowed('c'.$role,$url))) {
                   9423:                     $refused = 1;
                   9424:                 }
                   9425:             } else {
                   9426:                 $refused = 1;
                   9427:             }
1.947     raeburn  9428:             if ($refused) {
1.1045    raeburn  9429:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9430:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9431:                     my %crsenv;
                   9432:                     if ($role eq 'cc' || $role eq 'co') {
                   9433:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9434:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9435:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9436:                                 if ($crsenv{'internal.courseowner'} eq 
                   9437:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9438:                                     $refused = '';
                   9439:                                 }
                   9440:                             }
                   9441:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9442:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9443:                                 if ($crsenv{'internal.courseowner'} eq 
                   9444:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9445:                                     $refused = '';
                   9446:                                 }
                   9447:                             }
                   9448:                         }
                   9449:                     }
1.1368    raeburn  9450:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9451:                     if ($role eq 'st') {
                   9452:                         $refused = '';
1.1377    raeburn  9453:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9454:                         $refused = '';
                   9455:                     }
1.1017    raeburn  9456:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9457:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9458:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9459:                         my $wrongcc;
                   9460:                         if ($cnum =~ /^$match_community$/) {
                   9461:                             $wrongcc = 1 if ($role eq 'cc');
                   9462:                         } else {
                   9463:                             $wrongcc = 1 if ($role eq 'co');
                   9464:                         }
                   9465:                         unless ($wrongcc) {
                   9466:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9467:                             if ($crsenv{'internal.courseowner'} eq 
                   9468:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9469:                                 $refused = '';
                   9470:                             }
1.1017    raeburn  9471:                         }
                   9472:                     }
1.1183    raeburn  9473:                 } elsif ($context eq 'requestauthor') {
                   9474:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9475:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9476:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9477:                             $refused = '';
                   9478:                         } else {
                   9479:                             my %domdefaults = &get_domain_defaults($udom);
                   9480:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9481:                                 my $checkbystatus;
                   9482:                                 if ($env{'user.adv'}) { 
                   9483:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9484:                                     if ($disposition eq 'automatic') {
                   9485:                                         $refused = '';
                   9486:                                     } elsif ($disposition eq '') {
                   9487:                                         $checkbystatus = 1;
                   9488:                                     } 
                   9489:                                 } else {
                   9490:                                     $checkbystatus = 1;
                   9491:                                 }
                   9492:                                 if ($checkbystatus) {
                   9493:                                     if ($env{'environment.inststatus'}) {
                   9494:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9495:                                         foreach my $type (@inststatuses) {
                   9496:                                             if (($type ne '') &&
                   9497:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9498:                                                 $refused = '';
                   9499:                                             }
                   9500:                                         }
                   9501:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9502:                                         $refused = '';
                   9503:                                     }
                   9504:                                 }
                   9505:                             }
                   9506:                         }
                   9507:                     }
1.1017    raeburn  9508:                 }
                   9509:                 if ($refused) {
1.947     raeburn  9510:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9511:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9512: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9513:                     return 'refused';
                   9514:                 }
1.932     raeburn  9515:             }
1.1131    raeburn  9516:         } elsif ($role eq 'au') {
                   9517:             if ($url ne '/'.$udom.'/') {
                   9518:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9519:                          ' to assign author role for '.$uname.':'.$udom.
                   9520:                          ' in domain: '.$url.' refused (wrong domain).');
                   9521:                 return 'refused';
                   9522:             }
1.104     www      9523:         }
1.21      www      9524:         $mrole=$role;
                   9525:     }
1.620     albertel 9526:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9527:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9528:     if ($end) { $command.='_'.$end; }
1.21      www      9529:     if ($start) {
                   9530: 	if ($end) { 
1.81      www      9531:            $command.='_'.$start; 
1.21      www      9532:         } else {
1.81      www      9533:            $command.='_0_'.$start;
1.21      www      9534:         }
                   9535:     }
1.739     raeburn  9536:     my $origstart = $start;
                   9537:     my $origend = $end;
1.957     raeburn  9538:     my $delflag;
1.357     www      9539: # actually delete
                   9540:     if ($deleteflag) {
1.373     www      9541: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9542: # modify command to delete the role
1.620     albertel 9543:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9544:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9545: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9546: # set start and finish to negative values for userrolelog
                   9547:            $start=-1;
                   9548:            $end=-1;
1.957     raeburn  9549:            $delflag = 1;
1.357     www      9550:         }
                   9551:     }
                   9552: # send command
1.349     www      9553:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9554: # log new user role if status is ok
1.349     www      9555:     if ($answer eq 'ok') {
1.663     raeburn  9556: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9557:         if (($role eq 'cc') || ($role eq 'in') ||
                   9558:             ($role eq 'ep') || ($role eq 'ad') ||
                   9559:             ($role eq 'ta') || ($role eq 'st') ||
                   9560:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9561:             ($role eq 'co')) {
1.1200    raeburn  9562: # for course roles, perform group memberships changes triggered by role change.
                   9563:             unless ($role =~ /^gr/) {
                   9564:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9565:                                                  $origstart,$selfenroll,$context);
                   9566:             }
1.1184    raeburn  9567:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9568:                            $selfenroll,$context);
                   9569:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9570:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9571:                  ($role eq 'da')) {
1.1184    raeburn  9572:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9573:                            $context);
                   9574:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9575:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9576:                              $context); 
                   9577:         }
1.1053    raeburn  9578:         if ($role eq 'cc') {
                   9579:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9580:         }
1.349     www      9581:     }
                   9582:     return $answer;
1.169     harris41 9583: }
                   9584: 
1.1053    raeburn  9585: sub autoupdate_coowners {
                   9586:     my ($url,$end,$start,$uname,$udom) = @_;
                   9587:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9588:     if (($cdom ne '') && ($cnum ne '')) {
                   9589:         my $now = time;
                   9590:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9591:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9592:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9593:             my $instcode = $coursehash{'internal.coursecode'};
                   9594:             if ($instcode ne '') {
1.1056    raeburn  9595:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9596:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9597:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9598:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9599:                         if ($result eq 'valid') {
                   9600:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9601:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9602:                                     push(@newcoowners,$coowner);
                   9603:                                 }
                   9604:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9605:                                     push(@newcoowners,$uname.':'.$udom);
                   9606:                                 }
                   9607:                                 @newcoowners = sort(@newcoowners);
                   9608:                             } else {
                   9609:                                 push(@newcoowners,$uname.':'.$udom);
                   9610:                             }
                   9611:                         } else {
                   9612:                             if ($coursehash{'internal.co-owners'}) {
                   9613:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9614:                                     unless ($coowner eq $uname.':'.$udom) {
                   9615:                                         push(@newcoowners,$coowner);
                   9616:                                     }
                   9617:                                 }
                   9618:                                 unless (@newcoowners > 0) {
                   9619:                                     $delcoowners = 1;
                   9620:                                     $coowners = '';
                   9621:                                 }
                   9622:                             }
                   9623:                         }
                   9624:                         if (@newcoowners || $delcoowners) {
                   9625:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9626:                                             $delcoowners,@newcoowners);
                   9627:                         }
                   9628:                     }
                   9629:                 }
                   9630:             }
                   9631:         }
                   9632:     }
                   9633: }
                   9634: 
                   9635: sub store_coowners {
                   9636:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9637:     my $cid = $cdom.'_'.$cnum;
                   9638:     my ($coowners,$delresult,$putresult);
                   9639:     if (@newcoowners) {
                   9640:         $coowners = join(',',@newcoowners);
                   9641:         my %coownershash = (
                   9642:                             'internal.co-owners' => $coowners,
                   9643:                            );
                   9644:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9645:         if ($putresult eq 'ok') {
                   9646:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9647:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9648:             }
                   9649:         }
                   9650:     }
                   9651:     if ($delcoowners) {
                   9652:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9653:         if ($delresult eq 'ok') {
                   9654:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9655:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9656:             }
                   9657:         }
                   9658:     }
                   9659:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9660:         my %crsinfo =
                   9661:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9662:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9663:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9664:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9665:         }
                   9666:     }
                   9667: }
                   9668: 
1.169     harris41 9669: # -------------------------------------------------- Modify user authentication
1.197     www      9670: # Overrides without validation
                   9671: 
1.169     harris41 9672: sub modifyuserauth {
                   9673:     my ($udom,$uname,$umode,$upass)=@_;
                   9674:     my $uhome=&homeserver($uname,$udom);
1.197     www      9675:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9676:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9677:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9678:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9679:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9680: 		     &escape($upass),$uhome);
1.620     albertel 9681:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9682:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9683:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9684:     &log($udom,,$uname,$uhome,
1.620     albertel 9685:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9686:                                      $env{'user.name'}.', '.$umode.
1.197     www      9687:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9688:     unless ($reply eq 'ok') {
1.197     www      9689:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9690: 	return 'error: '.$reply;
                   9691:     }   
1.170     harris41 9692:     return 'ok';
1.80      www      9693: }
                   9694: 
1.81      www      9695: # --------------------------------------------------------------- Modify a user
1.80      www      9696: 
1.81      www      9697: sub modifyuser {
1.206     matthew  9698:     my ($udom,    $uname, $uid,
                   9699:         $umode,   $upass, $first,
                   9700:         $middle,  $last,  $gene,
1.1058    raeburn  9701:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9702:     $udom= &LONCAPA::clean_domain($udom);
                   9703:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9704:     my $showcandelete = 'none';
                   9705:     if (ref($candelete) eq 'ARRAY') {
                   9706:         if (@{$candelete} > 0) {
                   9707:             $showcandelete = join(', ',@{$candelete});
                   9708:         }
                   9709:     }
1.81      www      9710:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9711:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9712: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9713:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9714:                                      ' desiredhome not specified'). 
1.620     albertel 9715:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9716:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9717:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9718:     my $newuser;
                   9719:     if ($uhome eq 'no_host') {
                   9720:         $newuser = 1;
1.1368    raeburn  9721:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9722:                 ($umode eq 'lti')) {
                   9723:             return 'error: more information needed to create new user';
                   9724:         }
1.1075    raeburn  9725:     }
1.80      www      9726: # ----------------------------------------------------------------- Create User
1.406     albertel 9727:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9728: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9729:         my $unhome='';
1.844     albertel 9730:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9731:             $unhome = $desiredhome;
1.620     albertel 9732: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9733: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9734:         } else { # load balancing routine for determining $unhome
1.81      www      9735:             my $loadm=10000000;
1.841     albertel 9736: 	    my %servers = &get_servers($udom,'library');
                   9737: 	    foreach my $tryserver (keys(%servers)) {
                   9738: 		my $answer=reply('load',$tryserver);
                   9739: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9740: 		    $loadm=$answer;
                   9741: 		    $unhome=$tryserver;
                   9742: 		}
1.80      www      9743: 	    }
                   9744:         }
                   9745:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9746: 	    return 'error: unable to find a home server for '.$uname.
                   9747:                    ' in domain '.$udom;
1.80      www      9748:         }
                   9749:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9750:                          &escape($upass),$unhome);
                   9751: 	unless ($reply eq 'ok') {
                   9752:             return 'error: '.$reply;
                   9753:         }   
1.230     stredwic 9754:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9755:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9756: 	    return 'error: unable verify users home machine.';
1.80      www      9757:         }
1.209     matthew  9758:     }   # End of creation of new user
1.80      www      9759: # ---------------------------------------------------------------------- Add ID
                   9760:     if ($uid) {
                   9761:        $uid=~tr/A-Z/a-z/;
                   9762:        my %uidhash=&idrget($udom,$uname);
1.196     www      9763:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9764:          && (!$forceid)) {
1.80      www      9765: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9766: 	      return 'error: user id "'.$uid.'" does not match '.
                   9767:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9768:           }
                   9769:        } else {
1.1300    raeburn  9770: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9771:        }
                   9772:     }
                   9773: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9774:     my @tmp=&get('environment',
1.899     raeburn  9775: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9776:                     'permanentemail','inststatus'],
1.134     albertel 9777: 		   $udom,$uname);
1.1075    raeburn  9778:     my (%names,%oldnames);
1.313     matthew  9779:     if ($tmp[0] =~ m/^error:.*/) { 
                   9780:         %names=(); 
                   9781:     } else {
                   9782:         %names = @tmp;
1.1075    raeburn  9783:         %oldnames = %names;
1.313     matthew  9784:     }
1.388     www      9785: #
1.1058    raeburn  9786: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9787: # of users did not contain them), do not overwrite existing values
                   9788: # unless field is in $candelete array ref.  
                   9789: #
                   9790: 
                   9791:     my @fields = ('firstname','middlename','lastname','generation',
                   9792:                   'permanentemail','id');
                   9793:     my %newvalues;
                   9794:     if (ref($candelete) eq 'ARRAY') {
                   9795:         foreach my $field (@fields) {
                   9796:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9797:                 if ($field eq 'firstname') {
                   9798:                     $names{$field} = $first;
                   9799:                 } elsif ($field eq 'middlename') {
                   9800:                     $names{$field} = $middle;
                   9801:                 } elsif ($field eq 'lastname') {
                   9802:                     $names{$field} = $last;
                   9803:                 } elsif ($field eq 'generation') { 
                   9804:                     $names{$field} = $gene;
                   9805:                 } elsif ($field eq 'permanentemail') {
                   9806:                     $names{$field} = $email;
                   9807:                 } elsif ($field eq 'id') {
                   9808:                     $names{$field}  = $uid;
                   9809:                 }
                   9810:             }
                   9811:         }
                   9812:     }
1.388     www      9813:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9814:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9815:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9816:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9817:     if ($email) {
                   9818:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9819:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9820:     }
1.899     raeburn  9821:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9822:     if (defined($inststatus)) {
                   9823:         $names{'inststatus'} = '';
                   9824:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9825:         if (ref($usertypes) eq 'HASH') {
                   9826:             my @okstatuses; 
                   9827:             foreach my $item (split(/:/,$inststatus)) {
                   9828:                 if (defined($usertypes->{$item})) {
                   9829:                     push(@okstatuses,$item);  
                   9830:                 }
                   9831:             }
                   9832:             if (@okstatuses) {
                   9833:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9834:             }
                   9835:         }
                   9836:     }
1.1075    raeburn  9837:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9838:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9839:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9840:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9841:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9842:     } else {
                   9843:         $logmsg .= ' during self creation';
                   9844:     }
1.1075    raeburn  9845:     my $changed;
                   9846:     if ($newuser) {
                   9847:         $changed = 1;
                   9848:     } else {
                   9849:         foreach my $field (@fields) {
                   9850:             if ($names{$field} ne $oldnames{$field}) {
                   9851:                 $changed = 1;
                   9852:                 last;
                   9853:             }
                   9854:         }
                   9855:     }
                   9856:     unless ($changed) {
                   9857:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9858:         &logthis($logmsg);
                   9859:         return 'ok';
                   9860:     }
                   9861:     my $reply = &put('environment', \%names, $udom,$uname);
                   9862:     if ($reply ne 'ok') { 
                   9863:         return 'error: '.$reply;
                   9864:     }
1.1087    raeburn  9865:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9866:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9867:     }
1.1075    raeburn  9868:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9869:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9870:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9871:     &logthis($logmsg);
1.134     albertel 9872:     return 'ok';
1.80      www      9873: }
                   9874: 
1.81      www      9875: # -------------------------------------------------------------- Modify student
1.80      www      9876: 
1.81      www      9877: sub modifystudent {
                   9878:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9879:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9880:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9881:     if (!$cid) {
1.620     albertel 9882: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9883: 	    return 'not_in_class';
                   9884: 	}
1.80      www      9885:     }
                   9886: # --------------------------------------------------------------- Make the user
1.81      www      9887:     my $reply=&modifyuser
1.209     matthew  9888: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9889:          $desiredhome,$email,$inststatus);
1.80      www      9890:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9891:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9892:     # student's environment
1.297     matthew  9893:     $uid = undef if (!$forceid);
1.455     albertel 9894:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9895:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9896:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9897:     return $reply;
                   9898: }
                   9899: 
                   9900: sub modify_student_enrollment {
1.1216    raeburn  9901:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9902:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9903:     my ($cdom,$cnum,$chome);
                   9904:     if (!$cid) {
1.620     albertel 9905: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9906: 	    return 'not_in_class';
                   9907: 	}
1.620     albertel 9908: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9909: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9910:     } else {
                   9911: 	($cdom,$cnum)=split(/_/,$cid);
                   9912:     }
1.620     albertel 9913:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9914:     if (!$chome) {
1.457     raeburn  9915: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9916:     }
1.455     albertel 9917:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9918:     # Make sure the user exists
1.81      www      9919:     my $uhome=&homeserver($uname,$udom);
                   9920:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9921: 	return 'error: no such user';
                   9922:     }
1.297     matthew  9923:     # Get student data if we were not given enough information
                   9924:     if (!defined($first)  || $first  eq '' || 
                   9925:         !defined($last)   || $last   eq '' || 
                   9926:         !defined($uid)    || $uid    eq '' || 
                   9927:         !defined($middle) || $middle eq '' || 
                   9928:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9929:         # They did not supply us with enough data to enroll the student, so
                   9930:         # we need to pick up more information.
1.297     matthew  9931:         my %tmp = &get('environment',
1.294     matthew  9932:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9933:                        ,$udom,$uname);
                   9934: 
1.800     albertel 9935:         #foreach my $key (keys(%tmp)) {
                   9936:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9937:         #}
1.294     matthew  9938:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9939:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9940:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9941:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9942:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9943:     }
1.556     albertel 9944:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9945:     my $user = "$uname:$udom";
                   9946:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9947:     my $reply=cput('classlist',
1.1148    raeburn  9948: 		   {$user => 
1.1314    raeburn  9949: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9950: 		   $cdom,$cnum);
1.1148    raeburn  9951:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9952:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9953:     } else { 
1.81      www      9954: 	return 'error: '.$reply;
                   9955:     }
1.297     matthew  9956:     # Add student role to user
1.83      www      9957:     my $uurl='/'.$cid;
1.81      www      9958:     $uurl=~s/\_/\//g;
                   9959:     if ($usec) {
                   9960: 	$uurl.='/'.$usec;
                   9961:     }
1.1148    raeburn  9962:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9963:                              $selfenroll,$context);
                   9964:     if ($result ne 'ok') {
                   9965:         if ($old_entry{$user} ne '') {
                   9966:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9967:         } else {
                   9968:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9969:         }
                   9970:     }
                   9971:     return $result; 
1.21      www      9972: }
                   9973: 
1.556     albertel 9974: sub format_name {
                   9975:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9976:     my $name;
                   9977:     if ($first ne 'lastname') {
                   9978: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9979:     } else {
                   9980: 	if ($lastname=~/\S/) {
                   9981: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9982: 	    $name=~s/\s+,/,/;
                   9983: 	} else {
                   9984: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9985: 	}
                   9986:     }
                   9987:     $name=~s/^\s+//;
                   9988:     $name=~s/\s+$//;
                   9989:     $name=~s/\s+/ /g;
                   9990:     return $name;
                   9991: }
                   9992: 
1.84      www      9993: # ------------------------------------------------- Write to course preferences
                   9994: 
                   9995: sub writecoursepref {
                   9996:     my ($courseid,%prefs)=@_;
                   9997:     $courseid=~s/^\///;
                   9998:     $courseid=~s/\_/\//g;
                   9999:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10000:     my $chome=homeserver($cnum,$cdomain);
                   10001:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10002: 	return 'error: no such course';
                   10003:     }
                   10004:     my $cstring='';
1.800     albertel 10005:     foreach my $pref (keys(%prefs)) {
                   10006: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10007:     }
1.84      www      10008:     $cstring=~s/\&$//;
                   10009:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10010: }
                   10011: 
                   10012: # ---------------------------------------------------------- Make/modify course
                   10013: 
                   10014: sub createcourse {
1.741     raeburn  10015:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10016:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10017:     $url=&declutter($url);
                   10018:     my $cid='';
1.1028    raeburn  10019:     if ($context eq 'requestcourses') {
                   10020:         my $can_create = 0;
                   10021:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10022:         if ($udom eq $ownerdom) {
                   10023:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10024:                                   $context)) {
                   10025:                 $can_create = 1;
                   10026:             }
                   10027:         } else {
                   10028:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10029:                                            $category);
                   10030:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10031:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10032:                 if (@curr > 0) {
                   10033:                     my @options = qw(approval validate autolimit);
                   10034:                     my $optregex = join('|',@options);
                   10035:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10036:                         $can_create = 1;
                   10037:                     }
                   10038:                 }
                   10039:             }
                   10040:         }
                   10041:         if ($can_create) {
                   10042:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10043:                 unless (&allowed('ccc',$udom)) {
                   10044:                     return 'refused'; 
                   10045:                 }
1.1017    raeburn  10046:             }
                   10047:         } else {
                   10048:             return 'refused';
                   10049:         }
1.1028    raeburn  10050:     } elsif (!&allowed('ccc',$udom)) {
                   10051:         return 'refused';
1.84      www      10052:     }
1.1011    raeburn  10053: # --------------------------------------------------------------- Get Unique ID
                   10054:     my $uname;
                   10055:     if ($cnum =~ /^$match_courseid$/) {
                   10056:         my $chome=&homeserver($cnum,$udom,'true');
                   10057:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10058:             $uname = $cnum;
                   10059:         } else {
1.1038    raeburn  10060:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10061:         }
                   10062:     } else {
1.1038    raeburn  10063:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10064:     }
                   10065:     return $uname if ($uname =~ /^error/);
                   10066: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10067:     if (!defined($course_server)) {
                   10068:         if (defined(&domain($udom,'primary'))) {
                   10069:             $course_server = &domain($udom,'primary');
                   10070:         } else {
                   10071:             $course_server = $env{'user.home'}; 
                   10072:         }
                   10073:     }
                   10074:     my %host_servers =
                   10075:         &Apache::lonnet::get_servers($udom,'library');
                   10076:     unless ($host_servers{$course_server}) {
                   10077:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10078:     }
1.84      www      10079: # ------------------------------------------------------------- Make the course
                   10080:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10081:                       $course_server);
1.84      www      10082:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10083:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10084:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10085: 	return 'error: no such course';
                   10086:     }
1.271     www      10087: # ----------------------------------------------------------------- Course made
1.516     raeburn  10088: # log existence
1.1029    raeburn  10089:     my $now = time;
1.918     raeburn  10090:     my $newcourse = {
                   10091:                     $udom.'_'.$uname => {
1.921     raeburn  10092:                                      description => $description,
                   10093:                                      inst_code   => $inst_code,
                   10094:                                      owner       => $course_owner,
                   10095:                                      type        => $crstype,
1.1029    raeburn  10096:                                      creator     => $env{'user.name'}.':'.
                   10097:                                                     $env{'user.domain'},
                   10098:                                      created     => $now,
                   10099:                                      context     => $context,
1.918     raeburn  10100:                                                 },
                   10101:                     };
1.921     raeburn  10102:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10103: # set toplevel url
1.271     www      10104:     my $topurl=$url;
                   10105:     unless ($nonstandard) {
                   10106: # ------------------------------------------ For standard courses, make top url
                   10107:         my $mapurl=&clutter($url);
1.278     www      10108:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10109:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10110: <map>
                   10111: <resource id="1" type="start"></resource>
                   10112: <resource id="2" src="$mapurl"></resource>
                   10113: <resource id="3" type="finish"></resource>
                   10114: <link index="1" from="1" to="2"></link>
                   10115: <link index="2" from="2" to="3"></link>
                   10116: </map>
                   10117: ENDINITMAP
                   10118:         $topurl=&declutter(
1.638     albertel 10119:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10120:                           );
                   10121:     }
                   10122: # ----------------------------------------------------------- Write preferences
1.84      www      10123:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10124:                      ('description'              => $description,
                   10125:                       'url'                      => $topurl,
                   10126:                       'internal.creator'         => $env{'user.name'}.':'.
                   10127:                                                     $env{'user.domain'},
                   10128:                       'internal.created'         => $now,
                   10129:                       'internal.creationcontext' => $context)
                   10130:                     );
1.84      www      10131:     return '/'.$udom.'/'.$uname;
                   10132: }
                   10133: 
1.1011    raeburn  10134: # ------------------------------------------------------------------- Create ID
                   10135: sub generate_coursenum {
1.1038    raeburn  10136:     my ($udom,$crstype) = @_;
1.1011    raeburn  10137:     my $domdesc = &domain($udom);
                   10138:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10139:     my $first;
                   10140:     if ($crstype eq 'Community') {
                   10141:         $first = '0';
                   10142:     } else {
                   10143:         $first = int(1+rand(9)); 
                   10144:     } 
                   10145:     my $uname=$first.
1.1011    raeburn  10146:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10147:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10148:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10149: # ----------------------------------------------- Make sure that does not exist
                   10150:     my $uhome=&homeserver($uname,$udom,'true');
                   10151:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10152:         if ($crstype eq 'Community') {
                   10153:             $first = '0';
                   10154:         } else {
                   10155:             $first = int(1+rand(9));
                   10156:         }
                   10157:         $uname=$first.
1.1011    raeburn  10158:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10159:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10160:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10161:         $uhome=&homeserver($uname,$udom,'true');
                   10162:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10163:             return 'error: unable to generate unique course-ID';
                   10164:         }
                   10165:     }
                   10166:     return $uname;
                   10167: }
                   10168: 
1.813     albertel 10169: sub is_course {
1.1167    droeschl 10170:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10171:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10172: 
1.1381    raeburn  10173:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10174:     my $uhome=&homeserver($cnum,$cdom);
                   10175:     my $iscourse;
                   10176:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10177:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10178:     } else {
                   10179:         my $hashid = $cdom.':'.$cnum;
                   10180:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10181:         unless (defined($cached)) {
                   10182:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10183:                                         $cnum,undef,undef,'.');
                   10184:             $iscourse = 0;
                   10185:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10186:                 $iscourse = 1;
                   10187:             }
                   10188:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10189:         }
                   10190:     }
                   10191:     return unless ($iscourse);
1.1167    droeschl 10192:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10193: }
                   10194: 
1.1015    raeburn  10195: sub store_userdata {
                   10196:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10197:     my $result;
1.1016    raeburn  10198:     if ($datakey ne '') {
1.1013    raeburn  10199:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10200:             if ($udom eq '' || $uname eq '') {
                   10201:                 $udom = $env{'user.domain'};
                   10202:                 $uname = $env{'user.name'};
                   10203:             }
                   10204:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10205:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10206:                 $result = 'error: no_host';
                   10207:             } else {
                   10208:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10209:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10210: 
                   10211:                 my $namevalue='';
                   10212:                 foreach my $key (keys(%{$storehash})) {
                   10213:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10214:                 }
                   10215:                 $namevalue=~s/\&$//;
1.1224    raeburn  10216:                 unless ($namespace eq 'courserequests') {
                   10217:                     $datakey = &escape($datakey);
                   10218:                 }
1.1105    raeburn  10219:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10220:                                   $namevalue,$uhome);
1.1013    raeburn  10221:             }
                   10222:         } else {
                   10223:             $result = 'error: data to store was not a hash reference'; 
                   10224:         }
                   10225:     } else {
                   10226:         $result= 'error: invalid requestkey'; 
                   10227:     }
                   10228:     return $result;
                   10229: }
                   10230: 
1.21      www      10231: # ---------------------------------------------------------- Assign Custom Role
                   10232: 
                   10233: sub assigncustomrole {
1.957     raeburn  10234:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10235:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10236:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10237: }
                   10238: 
                   10239: # ----------------------------------------------------------------- Revoke Role
                   10240: 
                   10241: sub revokerole {
1.957     raeburn  10242:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10243:     my $now=time;
1.965     raeburn  10244:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10245: }
                   10246: 
                   10247: # ---------------------------------------------------------- Revoke Custom Role
                   10248: 
                   10249: sub revokecustomrole {
1.957     raeburn  10250:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10251:     my $now=time;
1.357     www      10252:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10253:            $deleteflag,$selfenroll,$context);
1.17      www      10254: }
                   10255: 
1.533     banghart 10256: # ------------------------------------------------------------ Disk usage
1.535     albertel 10257: sub diskusage {
1.955     raeburn  10258:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10259:     $directorypath =~ s/\/$//;
                   10260:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10261:                        .&escape($getpropath).':'.&escape($uname).':'
                   10262:                        .&escape($udom),homeserver($uname,$udom));
                   10263:     if ($listing eq 'unknown_cmd') {
                   10264:         if ($getpropath) {
                   10265:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10266:         }
                   10267:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10268:     }
1.514     albertel 10269:     return $listing;
1.512     banghart 10270: }
                   10271: 
1.566     banghart 10272: sub is_locked {
1.1096    raeburn  10273:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10274:     my @check;
                   10275:     my $is_locked;
1.1093    raeburn  10276:     push (@check,$file_name);
1.613     albertel 10277:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10278: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10279:     my ($tmp)=keys(%locked);
                   10280:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10281:     
1.566     banghart 10282:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10283:         $is_locked = 'false';
                   10284:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10285:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10286:                $is_locked = 'true';
1.1096    raeburn  10287:                if (ref($which) eq 'ARRAY') {
                   10288:                    push(@{$which},$entry);
                   10289:                } else {
                   10290:                    last;
                   10291:                }
1.745     raeburn  10292:            }
                   10293:        }
1.566     banghart 10294:     } else {
                   10295:         $is_locked = 'false';
                   10296:     }
1.1093    raeburn  10297:     return $is_locked;
1.566     banghart 10298: }
                   10299: 
1.759     albertel 10300: sub declutter_portfile {
                   10301:     my ($file) = @_;
1.833     albertel 10302:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10303:     return $file;
                   10304: }
                   10305: 
1.559     banghart 10306: # ------------------------------------------------------------- Mark as Read Only
                   10307: 
                   10308: sub mark_as_readonly {
                   10309:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10310:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10311:     my ($tmp)=keys(%current_permissions);
                   10312:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10313:     foreach my $file (@{$files}) {
1.759     albertel 10314: 	$file = &declutter_portfile($file);
1.561     banghart 10315:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10316:     }
1.613     albertel 10317:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10318:     return;
                   10319: }
                   10320: 
1.572     banghart 10321: # ------------------------------------------------------------Save Selected Files
                   10322: 
                   10323: sub save_selected_files {
                   10324:     my ($user, $path, @files) = @_;
                   10325:     my $filename = $user."savedfiles";
1.573     banghart 10326:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10327:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10328:     foreach my $file (@files) {
1.620     albertel 10329:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10330:     }
                   10331:     foreach my $file (@other_files) {
1.574     banghart 10332:         print (OUT $file."\n");
1.572     banghart 10333:     }
1.574     banghart 10334:     close (OUT);
1.572     banghart 10335:     return 'ok';
                   10336: }
                   10337: 
1.574     banghart 10338: sub clear_selected_files {
                   10339:     my ($user) = @_;
                   10340:     my $filename = $user."savedfiles";
1.1359    raeburn  10341:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10342:     print (OUT undef);
                   10343:     close (OUT);
                   10344:     return ("ok");    
                   10345: }
                   10346: 
1.572     banghart 10347: sub files_in_path {
                   10348:     my ($user, $path) = @_;
                   10349:     my $filename = $user."savedfiles";
                   10350:     my %return_files;
1.1359    raeburn  10351:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10352:     while (my $line_in = <IN>) {
1.574     banghart 10353:         chomp ($line_in);
                   10354:         my @paths_and_file = split (m!/!, $line_in);
                   10355:         my $file_part = pop (@paths_and_file);
                   10356:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10357:         $path_part.='/';
                   10358:         my $path_and_file = $path_part.$file_part;
                   10359:         if ($path_part eq $path) {
                   10360:             $return_files{$file_part}= 'selected';
                   10361:         }
                   10362:     }
1.574     banghart 10363:     close (IN);
                   10364:     return (\%return_files);
1.572     banghart 10365: }
                   10366: 
                   10367: # called in portfolio select mode, to show files selected NOT in current directory
                   10368: sub files_not_in_path {
                   10369:     my ($user, $path) = @_;
                   10370:     my $filename = $user."savedfiles";
                   10371:     my @return_files;
                   10372:     my $path_part;
1.1359    raeburn  10373:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10374:     while (my $line = <IN>) {
1.572     banghart 10375:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10376:         my @paths_and_file = split(m|/|, $line);
                   10377:         my $file_part = pop(@paths_and_file);
                   10378:         chomp($file_part);
                   10379:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10380:         $path_part .= '/';
                   10381:         my $path_and_file = $path_part.$file_part;
                   10382:         if ($path_part ne $path) {
1.800     albertel 10383:             push(@return_files, ($path_and_file));
1.572     banghart 10384:         }
                   10385:     }
1.800     albertel 10386:     close(OUT);
1.574     banghart 10387:     return (@return_files);
1.572     banghart 10388: }
                   10389: 
1.1273    raeburn  10390: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10391:  
                   10392: sub portfiles_versioning {
                   10393:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10394:     my $portfolio_root = '/userfiles/portfolio';
                   10395:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10396:     foreach my $file (@{$portfiles}) {
                   10397:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10398:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10399:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10400:         my $getpropath = 1;
                   10401:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10402:                                              $stu_name,$getpropath);
                   10403:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10404:         my $new_answer = 
                   10405:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10406:         if ($new_answer ne 'problem getting file') {
                   10407:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10408:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10409:                               [$symb,$env{'request.course.id'},'graded']);
                   10410:         }
                   10411:     }
                   10412: }
                   10413: 
                   10414: sub get_next_version {
                   10415:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10416:     my $version;
                   10417:     if (ref($dir_list) eq 'ARRAY') {
                   10418:         foreach my $row (@{$dir_list}) {
                   10419:             my ($file) = split(/\&/,$row,2);
                   10420:             my ($file_name,$file_version,$file_ext) =
                   10421:                 &file_name_version_ext($file);
                   10422:             if (($file_name eq $answer_name) &&
                   10423:                 ($file_ext eq $answer_ext)) {
                   10424:                      # gets here if filename and extension match,
                   10425:                      # regardless of version
                   10426:                 if ($file_version ne '') {
                   10427:                     # a versioned file is found  so save it for later
                   10428:                     if ($file_version > $version) {
                   10429:                         $version = $file_version;
                   10430:                     }
                   10431:                 }
                   10432:             }
                   10433:         }
                   10434:     }
                   10435:     $version ++;
                   10436:     return($version);
                   10437: }
                   10438: 
                   10439: sub version_selected_portfile {
                   10440:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10441:     my ($answer_name,$answer_ver,$answer_ext) =
                   10442:         &file_name_version_ext($file_name);
                   10443:     my $new_answer;
                   10444:     $env{'form.copy'} =
                   10445:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10446:     if($env{'form.copy'} eq '-1') {
                   10447:         $new_answer = 'problem getting file';
                   10448:     } else {
                   10449:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10450:         my $copy_result = 
                   10451:             &finishuserfileupload($stu_name,$domain,'copy',
                   10452:                                   '/portfolio'.$directory.$new_answer);
                   10453:     }
                   10454:     undef($env{'form.copy'});
                   10455:     return ($new_answer);
                   10456: }
                   10457: 
                   10458: sub file_name_version_ext {
                   10459:     my ($file)=@_;
                   10460:     my @file_parts = split(/\./, $file);
                   10461:     my ($name,$version,$ext);
                   10462:     if (@file_parts > 1) {
                   10463:         $ext=pop(@file_parts);
                   10464:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10465:             $version=pop(@file_parts);
                   10466:         }
                   10467:         $name=join('.',@file_parts);
                   10468:     } else {
                   10469:         $name=join('.',@file_parts);
                   10470:     }
                   10471:     return($name,$version,$ext);
                   10472: }
                   10473: 
1.745     raeburn  10474: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10475: 
1.745     raeburn  10476: sub get_portfile_permissions {
                   10477:     my ($domain,$user) = @_;
1.613     albertel 10478:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10479:     my ($tmp)=keys(%current_permissions);
                   10480:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10481:     return \%current_permissions;
                   10482: }
                   10483: 
                   10484: #---------------------------------------------Get portfolio file access controls
                   10485: 
1.749     raeburn  10486: sub get_access_controls {
1.745     raeburn  10487:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10488:     my %access;
                   10489:     my $real_file = $file;
                   10490:     $file =~ s/\.meta$//;
1.745     raeburn  10491:     if (defined($file)) {
1.749     raeburn  10492:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10493:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10494:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10495:             }
                   10496:         }
1.745     raeburn  10497:     } else {
1.749     raeburn  10498:         foreach my $key (keys(%{$current_permissions})) {
                   10499:             if ($key =~ /\0accesscontrol$/) {
                   10500:                 if (defined($group)) {
                   10501:                     if ($key !~ m-^\Q$group\E/-) {
                   10502:                         next;
                   10503:                     }
                   10504:                 }
                   10505:                 my ($fullpath) = split(/\0/,$key);
                   10506:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10507:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10508:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10509:                     }
                   10510:                 }
                   10511:             }
                   10512:         }
                   10513:     }
                   10514:     return %access;
                   10515: }
                   10516: 
                   10517: sub modify_access_controls {
                   10518:     my ($file_name,$changes,$domain,$user)=@_;
                   10519:     my ($outcome,$deloutcome);
                   10520:     my %store_permissions;
                   10521:     my %new_values;
                   10522:     my %new_control;
                   10523:     my %translation;
                   10524:     my @deletions = ();
                   10525:     my $now = time;
                   10526:     if (exists($$changes{'activate'})) {
                   10527:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10528:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10529:             my $numnew = scalar(@newitems);
                   10530:             for (my $i=0; $i<$numnew; $i++) {
                   10531:                 my $newkey = $newitems[$i];
                   10532:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10533:                 if ($newkey =~ /^\d+:/) { 
                   10534:                     $newkey =~ s/^(\d+)/$newid/;
                   10535:                     $translation{$1} = $newid;
                   10536:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10537:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10538:                     $translation{$1} = $newid;
                   10539:                 }
1.749     raeburn  10540:                 $new_values{$file_name."\0".$newkey} = 
                   10541:                                           $$changes{'activate'}{$newitems[$i]};
                   10542:                 $new_control{$newkey} = $now;
                   10543:             }
                   10544:         }
                   10545:     }
                   10546:     my %todelete;
                   10547:     my %changed_items;
                   10548:     foreach my $action ('delete','update') {
                   10549:         if (exists($$changes{$action})) {
                   10550:             if (ref($$changes{$action}) eq 'HASH') {
                   10551:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10552:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10553:                     if ($action eq 'delete') { 
                   10554:                         $todelete{$itemnum} = 1;
                   10555:                     } else {
                   10556:                         $changed_items{$itemnum} = $key;
                   10557:                     }
                   10558:                 }
1.745     raeburn  10559:             }
                   10560:         }
1.749     raeburn  10561:     }
                   10562:     # get lock on access controls for file.
                   10563:     my $lockhash = {
                   10564:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10565:                                                        ':'.$env{'user.domain'},
                   10566:                    }; 
                   10567:     my $tries = 0;
                   10568:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10569:    
1.1288    damieng  10570:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10571:         $tries ++;
1.1289    damieng  10572:         sleep(0.1);
1.749     raeburn  10573:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10574:     }
                   10575:     if ($gotlock eq 'ok') {
                   10576:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10577:         my ($tmp)=keys(%curr_permissions);
                   10578:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10579:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10580:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10581:             if (ref($curr_controls) eq 'HASH') {
                   10582:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10583:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10584:                     if (defined($todelete{$itemnum})) {
                   10585:                         push(@deletions,$file_name."\0".$control_item);
                   10586:                     } else {
                   10587:                         if (defined($changed_items{$itemnum})) {
                   10588:                             $new_control{$changed_items{$itemnum}} = $now;
                   10589:                             push(@deletions,$file_name."\0".$control_item);
                   10590:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10591:                         } else {
                   10592:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10593:                         }
                   10594:                     }
1.745     raeburn  10595:                 }
                   10596:             }
                   10597:         }
1.970     raeburn  10598:         my ($group);
                   10599:         if (&is_course($domain,$user)) {
                   10600:             ($group,my $file) = split(/\//,$file_name,2);
                   10601:         }
1.749     raeburn  10602:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10603:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10604:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10605:         #  remove lock
                   10606:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10607:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10608:         my $sqlresult =
1.970     raeburn  10609:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10610:                                     $group);
1.749     raeburn  10611:     } else {
                   10612:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10613:     }
1.749     raeburn  10614:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10615: }
                   10616: 
1.827     raeburn  10617: sub make_public_indefinitely {
1.1271    raeburn  10618:     my (@requrl) = @_;
                   10619:     return &automated_portfile_access('public',\@requrl);
                   10620: }
                   10621: 
                   10622: sub automated_portfile_access {
                   10623:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10624:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10625:         return 'invalid';
                   10626:     }
1.1271    raeburn  10627:     my %urls;
                   10628:     if (ref($addsref) eq 'ARRAY') {
                   10629:         foreach my $requrl (@{$addsref}) {
                   10630:             if (&is_portfolio_url($requrl)) {
                   10631:                 unless (exists($urls{$requrl})) {
                   10632:                     $urls{$requrl} = 'add';
                   10633:                 }
                   10634:             }
                   10635:         }
                   10636:     }
                   10637:     if (ref($delsref) eq 'ARRAY') {
                   10638:         foreach my $requrl (@{$delsref}) { 
                   10639:             if (&is_portfolio_url($requrl)) {
                   10640:                 unless (exists($urls{$requrl})) {
                   10641:                     $urls{$requrl} = 'delete'; 
                   10642:                 }
                   10643:             }
                   10644:         }
                   10645:     }
                   10646:     unless (keys(%urls)) {
                   10647:         return 'invalid';
                   10648:     }
                   10649:     my $ip;
                   10650:     if ($accesstype eq 'ip') {
                   10651:         if (ref($info) eq 'HASH') {
                   10652:             if ($info->{'ip'} ne '') {
                   10653:                 $ip = $info->{'ip'};
                   10654:             }
                   10655:         }
                   10656:         if ($ip eq '') {
                   10657:             return 'invalid';
                   10658:         }
                   10659:     }
                   10660:     my $errors;
1.827     raeburn  10661:     my $now = time;
1.1271    raeburn  10662:     my %current_perms;
                   10663:     foreach my $requrl (sort(keys(%urls))) {
                   10664:         my $action;
                   10665:         if ($urls{$requrl} eq 'add') {
                   10666:             $action = 'activate';
                   10667:         } else {
                   10668:             $action = 'none';
                   10669:         }
                   10670:         my $aclnum = 0;
1.827     raeburn  10671:         my (undef,$udom,$unum,$file_name,$group) =
                   10672:             &parse_portfolio_url($requrl);
1.1271    raeburn  10673:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10674:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10675:         }
                   10676:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10677:                                                    $group,$file_name);
                   10678:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10679:             my ($num,$scope,$end,$start) = 
                   10680:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10681:             if ($scope eq $accesstype) {
                   10682:                 if (($start <= $now) && ($end == 0)) {
                   10683:                     if ($accesstype eq 'ip') {
                   10684:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10685:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10686:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10687:                                     if ($urls{$requrl} eq 'add') {
                   10688:                                         $action = 'none';
                   10689:                                         last;
                   10690:                                     } else {
                   10691:                                         $action = 'delete';
                   10692:                                         $aclnum = $num;
                   10693:                                         last;
                   10694:                                     }
                   10695:                                 }
                   10696:                             }
                   10697:                         }
                   10698:                     } elsif ($accesstype eq 'public') {
                   10699:                         if ($urls{$requrl} eq 'add') {
                   10700:                             $action = 'none';
                   10701:                             last;
                   10702:                         } else {
                   10703:                             $action = 'delete';
                   10704:                             $aclnum = $num;
                   10705:                             last;
                   10706:                         }
                   10707:                     }
                   10708:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10709:                     $action = 'update';
                   10710:                     $aclnum = $num;
1.1271    raeburn  10711:                     last;
1.827     raeburn  10712:                 }
                   10713:             }
                   10714:         }
                   10715:         if ($action eq 'none') {
1.1271    raeburn  10716:             next;
1.827     raeburn  10717:         } else {
                   10718:             my %changes;
                   10719:             my $newend = 0;
                   10720:             my $newstart = $now;
1.1271    raeburn  10721:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10722:             $changes{$action}{$newkey} = {
1.1271    raeburn  10723:                 type => $accesstype,
1.827     raeburn  10724:                 time => {
                   10725:                     start => $newstart,
                   10726:                     end   => $newend,
                   10727:                 },
                   10728:             };
1.1271    raeburn  10729:             if ($accesstype eq 'ip') {
                   10730:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10731:             }
1.827     raeburn  10732:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10733:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10734:             unless ($outcome eq 'ok') {
                   10735:                 $errors .= $outcome.' ';
                   10736:             }
1.827     raeburn  10737:         }
1.1271    raeburn  10738:     }
                   10739:     if ($errors) {
                   10740:         $errors =~ s/\s$//;
                   10741:         return $errors;
1.827     raeburn  10742:     } else {
1.1271    raeburn  10743:         return 'ok';
1.827     raeburn  10744:     }
                   10745: }
                   10746: 
1.745     raeburn  10747: #------------------------------------------------------Get Marked as Read Only
                   10748: 
                   10749: sub get_marked_as_readonly {
                   10750:     my ($domain,$user,$what,$group) = @_;
                   10751:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10752:     my @readonly_files;
1.629     banghart 10753:     my $cmp1=$what;
                   10754:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10755:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10756:         if (defined($group)) {
                   10757:             if ($file_name !~ m-^\Q$group\E/-) {
                   10758:                 next;
                   10759:             }
                   10760:         }
1.561     banghart 10761:         if (ref($value) eq "ARRAY"){
                   10762:             foreach my $stored_what (@{$value}) {
1.629     banghart 10763:                 my $cmp2=$stored_what;
1.759     albertel 10764:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10765:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10766:                 }
1.629     banghart 10767:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10768:                     push(@readonly_files, $file_name);
1.745     raeburn  10769:                     last;
1.563     banghart 10770:                 } elsif (!defined($what)) {
                   10771:                     push(@readonly_files, $file_name);
1.745     raeburn  10772:                     last;
1.561     banghart 10773:                 }
                   10774:             }
1.745     raeburn  10775:         }
1.561     banghart 10776:     }
                   10777:     return @readonly_files;
                   10778: }
1.577     banghart 10779: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10780: 
1.577     banghart 10781: sub get_marked_as_readonly_hash {
1.745     raeburn  10782:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10783:     my %readonly_files;
1.745     raeburn  10784:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10785:         if (defined($group)) {
                   10786:             if ($file_name !~ m-^\Q$group\E/-) {
                   10787:                 next;
                   10788:             }
                   10789:         }
1.577     banghart 10790:         if (ref($value) eq "ARRAY"){
                   10791:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10792:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10793:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10794:                         if ($lock_descriptor eq 'graded') {
                   10795:                             $readonly_files{$file_name} = 'graded';
                   10796:                         } elsif ($lock_descriptor eq 'handback') {
                   10797:                             $readonly_files{$file_name} = 'handback';
                   10798:                         } else {
                   10799:                             if (!exists($readonly_files{$file_name})) {
                   10800:                                 $readonly_files{$file_name} = 'locked';
                   10801:                             }
                   10802:                         }
1.745     raeburn  10803:                     }
1.750     banghart 10804:                 } 
1.577     banghart 10805:             }
                   10806:         } 
                   10807:     }
                   10808:     return %readonly_files;
                   10809: }
1.559     banghart 10810: # ------------------------------------------------------------ Unmark as Read Only
                   10811: 
                   10812: sub unmark_as_readonly {
1.629     banghart 10813:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10814:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10815:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10816:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10817:     my $symb_crs = $what;
                   10818:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10819:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10820:     my ($tmp)=keys(%current_permissions);
                   10821:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10822:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10823:     foreach my $file (@readonly_files) {
1.759     albertel 10824: 	my $clean_file = &declutter_portfile($file);
                   10825: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10826: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10827:         my @new_locks;
                   10828:         my @del_keys;
                   10829:         if (ref($current_locks) eq "ARRAY"){
                   10830:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10831:                 my $compare=$locker;
1.749     raeburn  10832:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10833:                     $compare=join('',@{$locker});
1.746     raeburn  10834:                     if ($compare ne $symb_crs) {
                   10835:                         push(@new_locks, $locker);
                   10836:                     }
1.563     banghart 10837:                 }
                   10838:             }
1.650     albertel 10839:             if (scalar(@new_locks) > 0) {
1.563     banghart 10840:                 $current_permissions{$file} = \@new_locks;
                   10841:             } else {
                   10842:                 push(@del_keys, $file);
1.613     albertel 10843:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10844:                 delete($current_permissions{$file});
1.563     banghart 10845:             }
                   10846:         }
1.561     banghart 10847:     }
1.613     albertel 10848:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10849:     return;
                   10850: }
1.512     banghart 10851: 
1.17      www      10852: # ------------------------------------------------------------ Directory lister
                   10853: 
                   10854: sub dirlist {
1.955     raeburn  10855:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10856:     $uri=~s/^\///;
                   10857:     $uri=~s/\/$//;
1.253     stredwic 10858:     my ($udom, $uname);
1.955     raeburn  10859:     if ($getuserdir) {
1.253     stredwic 10860:         $udom = $userdomain;
                   10861:         $uname = $username;
1.955     raeburn  10862:     } else {
                   10863:         (undef,$udom,$uname)=split(/\//,$uri);
                   10864:         if(defined($userdomain)) {
                   10865:             $udom = $userdomain;
                   10866:         }
                   10867:         if(defined($username)) {
                   10868:             $uname = $username;
                   10869:         }
1.253     stredwic 10870:     }
1.955     raeburn  10871:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10872: 
1.955     raeburn  10873:     $dirRoot = $perlvar{'lonDocRoot'};
                   10874:     if (defined($getpropath)) {
                   10875:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10876:         $dirRoot =~ s/\/$//;
1.955     raeburn  10877:     } elsif (defined($getuserdir)) {
                   10878:         my $subdir=$uname.'__';
                   10879:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10880:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10881:                    ."/$udom/$subdir/$uname";
                   10882:     } elsif (defined($alternateRoot)) {
                   10883:         $dirRoot = $alternateRoot;
1.751     banghart 10884:     }
1.253     stredwic 10885: 
                   10886:     if($udom) {
                   10887:         if($uname) {
1.1135    raeburn  10888:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10889:             if ($uhome eq 'no_host') {
                   10890:                 return ([],'no_host');
                   10891:             }
1.955     raeburn  10892:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10893:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10894:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10895:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10896:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10897:             } else {
                   10898:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10899:             }
1.605     matthew  10900:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10901:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10902:                 @listing_results = split(/:/,$listing);
                   10903:             } else {
                   10904:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10905:             }
1.1135    raeburn  10906:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10907:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10908:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10909:                 return ([],$listing);
                   10910:             } else {
                   10911:                 return (\@listing_results);
1.1135    raeburn  10912:             }
1.955     raeburn  10913:         } elsif(!$alternateRoot) {
1.1136    raeburn  10914:             my (%allusers,%listerror);
1.841     albertel 10915: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10916:  	    foreach my $tryserver (keys(%servers)) {
                   10917:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10918:                                   &escape($udom),$tryserver);
                   10919:                 if ($listing eq 'unknown_cmd') {
                   10920: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10921: 				      $udom, $tryserver);
                   10922:                 } else {
                   10923:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10924:                 }
1.841     albertel 10925: 		if ($listing eq 'unknown_cmd') {
                   10926: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10927: 				      $udom, $tryserver);
                   10928: 		    @listing_results = split(/:/,$listing);
                   10929: 		} else {
                   10930: 		    @listing_results =
                   10931: 			map { &unescape($_); } split(/:/,$listing);
                   10932: 		}
1.1136    raeburn  10933:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10934:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10935:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10936:                     $listerror{$tryserver} = $listing;
                   10937:                 } else {
1.841     albertel 10938: 		    foreach my $line (@listing_results) {
                   10939: 			my ($entry) = split(/&/,$line,2);
                   10940: 			$allusers{$entry} = 1;
                   10941: 		    }
                   10942: 		}
1.253     stredwic 10943:             }
1.1136    raeburn  10944:             my @alluserslist=();
1.800     albertel 10945:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10946:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10947:             }
1.1318    droeschl 10948: 
                   10949:             if (!%listerror) {
                   10950:                 # no errors
                   10951:                 return (\@alluserslist);
                   10952:             } elsif (scalar(keys(%servers)) == 1) {
                   10953:                 # one library server, one error 
                   10954:                 my ($key) = keys(%listerror);
                   10955:                 return (\@alluserslist, $listerror{$key});
                   10956:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10957:                 # con_lost indicates that we might miss data from at least one
                   10958:                 # library server
                   10959:                 return (\@alluserslist, 'con_lost');
                   10960:             } else {
                   10961:                 # multiple library servers and no con_lost -> data should be
                   10962:                 # complete. 
                   10963:                 return (\@alluserslist);
                   10964:             }
                   10965: 
1.253     stredwic 10966:         } else {
1.1136    raeburn  10967:             return ([],'missing username');
1.253     stredwic 10968:         }
1.955     raeburn  10969:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10970:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10971:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10972:         return (\@all_domains);
1.955     raeburn  10973:     } else {
1.1136    raeburn  10974:         return ([],'missing domain');
1.275     stredwic 10975:     }
                   10976: }
                   10977: 
                   10978: # --------------------------------------------- GetFileTimestamp
                   10979: # This function utilizes dirlist and returns the date stamp for
                   10980: # when it was last modified.  It will also return an error of -1
                   10981: # if an error occurs
                   10982: 
                   10983: sub GetFileTimestamp {
1.955     raeburn  10984:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10985:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10986:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10987:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10988:                                     undef,$getuserdir);
                   10989:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10990:         return -1;
                   10991:     }
                   10992:     if (ref($fileref) eq 'ARRAY') {
                   10993:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10994:         # @stats contains first the filename, then the stat output
                   10995:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10996:     } else {
                   10997:         return -1;
1.253     stredwic 10998:     }
1.26      www      10999: }
                   11000: 
1.712     albertel 11001: sub stat_file {
                   11002:     my ($uri) = @_;
1.787     albertel 11003:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11004: 
1.955     raeburn  11005:     my ($udom,$uname,$file);
1.712     albertel 11006:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11007: 	($udom,$uname,$file) =
1.811     albertel 11008: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11009: 	$file = 'userfiles/'.$file;
                   11010:     }
                   11011:     if ($uri =~ m-^/res/-) {
                   11012: 	($udom,$uname) = 
1.807     albertel 11013: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11014: 	$file = $uri;
                   11015:     }
                   11016: 
                   11017:     if (!$udom || !$uname || !$file) {
                   11018: 	# unable to handle the uri
                   11019: 	return ();
                   11020:     }
1.956     raeburn  11021:     my $getpropath;
                   11022:     if ($file =~ /^userfiles\//) {
                   11023:         $getpropath = 1;
                   11024:     }
1.1136    raeburn  11025:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11026:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11027:         return ();
                   11028:     } else {
                   11029:         if (ref($listref) eq 'ARRAY') {
                   11030:             my @stats = split('&',$listref->[0]);
                   11031: 	    shift(@stats); #filename is first
                   11032: 	    return @stats;
                   11033:         }
1.712     albertel 11034:     }
                   11035:     return ();
                   11036: }
                   11037: 
1.1313    raeburn  11038: # --------------------------------------------------------- recursedirs
                   11039: # Recursive function to traverse either a specific user's Authoring Space
                   11040: # or corresponding Published Resource Space, and populate the hash ref:
                   11041: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11042: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11043: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11044: # files in Authoring Space.
                   11045: #
                   11046: # Inputs:
                   11047: #
                   11048: # $is_home - true if current server is home server for user's space
                   11049: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11050: # $docroot - Document root (i.e., /home/httpd/html
                   11051: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11052: # $relpath - Current path (relative to top level).
                   11053: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11054: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11055: #
                   11056: # Returns: nothing
                   11057: #
                   11058: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11059: #
                   11060: # Currently used by interface/londocs.pm to create linked select boxes for
                   11061: # directory and filename to import a Course "Author" resource into a course, and
                   11062: # also to create linked select boxes for Authoring Space and Directory to choose
                   11063: # save location for creation of a new "standard" problem from the Course Editor.
                   11064: #
                   11065: 
                   11066: sub recursedirs {
                   11067:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11068:     return unless (ref($dirhashref) eq 'HASH');
                   11069:     my $currpath = $docroot.$toppath;
                   11070:     if ($relpath) {
                   11071:         $currpath .= "/$relpath";
                   11072:     }
                   11073:     my $savefile;
                   11074:     if (ref($filehashref)) {
                   11075:         $savefile = 1;
                   11076:     }
                   11077:     if ($is_home) {
                   11078:         if (opendir(my $dirh,$currpath)) {
                   11079:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11080:                 next if ($item eq '');
                   11081:                 if (-d "$currpath/$item") {
                   11082:                     my $newpath;
                   11083:                     if ($relpath) {
                   11084:                         $newpath = "$relpath/$item";
                   11085:                     } else {
                   11086:                         $newpath = $item;
                   11087:                     }
                   11088:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11089:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11090:                 } elsif ($savefile) {
                   11091:                     if ($context eq 'priv') {
                   11092:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11093:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11094:                         }
                   11095:                     } else {
                   11096:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11097:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11098:                         }
                   11099:                     }
                   11100:                 }
                   11101:             }
                   11102:             closedir($dirh);
                   11103:         }
                   11104:     } else {
                   11105:         my ($dirlistref,$listerror) =
                   11106:             &dirlist($toppath.$relpath);
                   11107:         my @dir_lines;
                   11108:         my $dirptr=16384;
                   11109:         if (ref($dirlistref) eq 'ARRAY') {
                   11110:             foreach my $dir_line (sort
                   11111:                               {
                   11112:                                   my ($afile)=split('&',$a,2);
                   11113:                                   my ($bfile)=split('&',$b,2);
                   11114:                                   return (lc($afile) cmp lc($bfile));
                   11115:                               } (@{$dirlistref})) {
                   11116:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11117:                     split(/\&/,$dir_line,16);
                   11118:                 $item =~ s/\s+$//;
                   11119:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11120:                 if ($dirptr&$testdir) {
                   11121:                     my $newpath;
                   11122:                     if ($relpath) {
                   11123:                         $newpath = "$relpath/$item";
                   11124:                     } else {
                   11125:                         $relpath = '/';
                   11126:                         $newpath = $item;
                   11127:                     }
                   11128:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11129:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11130:                 } elsif ($savefile) {
                   11131:                     if ($context eq 'priv') {
                   11132:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11133:                             $filehashref->{$relpath}{$item} = 1;
                   11134:                         }
                   11135:                     } else {
                   11136:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11137:                             $filehashref->{$relpath}{$item} = 1;
                   11138:                         }
                   11139:                     }
                   11140:                 }
                   11141:             }
                   11142:         }
                   11143:     }
                   11144:     return;
                   11145: }
                   11146: 
1.26      www      11147: # -------------------------------------------------------- Value of a Condition
                   11148: 
1.713     albertel 11149: # gets the value of a specific preevaluated condition
                   11150: #    stored in the string  $env{user.state.<cid>}
                   11151: # or looks up a condition reference in the bighash and if if hasn't
                   11152: # already been evaluated recurses into docondval to get the value of
                   11153: # the condition, then memoizing it to 
                   11154: #   $env{user.state.<cid>.<condition>}
1.40      www      11155: sub directcondval {
                   11156:     my $number=shift;
1.620     albertel 11157:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11158: 	&Apache::lonuserstate::evalstate();
                   11159:     }
1.713     albertel 11160:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11161: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11162:     } elsif ($number =~ /^_/) {
                   11163: 	my $sub_condition;
                   11164: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11165: 		&GDBM_READER(),0640)) {
                   11166: 	    $sub_condition=$bighash{'conditions'.$number};
                   11167: 	    untie(%bighash);
                   11168: 	}
                   11169: 	my $value = &docondval($sub_condition);
1.949     raeburn  11170: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11171: 	return $value;
                   11172:     }
1.620     albertel 11173:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11174:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11175:     } else {
                   11176:        return 2;
                   11177:     }
                   11178: }
                   11179: 
1.713     albertel 11180: # get the collection of conditions for this resource
1.26      www      11181: sub condval {
                   11182:     my $condidx=shift;
1.54      www      11183:     my $allpathcond='';
1.713     albertel 11184:     foreach my $cond (split(/\|/,$condidx)) {
                   11185: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11186: 	    $allpathcond.=
                   11187: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11188: 	}
1.191     harris41 11189:     }
1.54      www      11190:     $allpathcond=~s/\|$//;
1.713     albertel 11191:     return &docondval($allpathcond);
                   11192: }
                   11193: 
                   11194: #evaluates an expression of conditions
                   11195: sub docondval {
                   11196:     my ($allpathcond) = @_;
                   11197:     my $result=0;
                   11198:     if ($env{'request.course.id'}
                   11199: 	&& defined($allpathcond)) {
                   11200: 	my $operand='|';
                   11201: 	my @stack;
                   11202: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11203: 	    if ($chunk eq '(') {
                   11204: 		push @stack,($operand,$result);
                   11205: 	    } elsif ($chunk eq ')') {
                   11206: 		my $before=pop @stack;
                   11207: 		if (pop @stack eq '&') {
                   11208: 		    $result=$result>$before?$before:$result;
                   11209: 		} else {
                   11210: 		    $result=$result>$before?$result:$before;
                   11211: 		}
                   11212: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11213: 		$operand=$chunk;
                   11214: 	    } else {
                   11215: 		my $new=directcondval($chunk);
                   11216: 		if ($operand eq '&') {
                   11217: 		    $result=$result>$new?$new:$result;
                   11218: 		} else {
                   11219: 		    $result=$result>$new?$result:$new;
                   11220: 		}
                   11221: 	    }
                   11222: 	}
1.26      www      11223:     }
                   11224:     return $result;
1.421     albertel 11225: }
                   11226: 
                   11227: # ---------------------------------------------------- Devalidate courseresdata
                   11228: 
                   11229: sub devalidatecourseresdata {
                   11230:     my ($coursenum,$coursedomain)=@_;
                   11231:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11232:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11233: }
                   11234: 
1.763     www      11235: 
1.200     www      11236: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11237: #
                   11238: #  Parameters:
                   11239: #      $coursenum    - Number of the course.
                   11240: #      $coursedomain - Domain at which the course was created.
                   11241: #  Returns:
                   11242: #     A hash of the course parameters along (I think) with timestamps
                   11243: #     and version info.
1.877     foxr     11244: 
1.624     albertel 11245: sub get_courseresdata {
                   11246:     my ($coursenum,$coursedomain)=@_;
1.200     www      11247:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11248:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11249:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11250:     my %dumpreply;
1.417     albertel 11251:     unless (defined($cached)) {
1.624     albertel 11252: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11253: 	$result=\%dumpreply;
1.251     albertel 11254: 	my ($tmp) = keys(%dumpreply);
                   11255: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11256: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11257: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11258: 	    return $tmp;
1.416     albertel 11259: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11260: 	    $result=undef;
1.599     albertel 11261: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11262: 	}
                   11263:     }
1.624     albertel 11264:     return $result;
                   11265: }
                   11266: 
1.633     albertel 11267: sub devalidateuserresdata {
                   11268:     my ($uname,$udom)=@_;
                   11269:     my $hashid="$udom:$uname";
                   11270:     &devalidate_cache_new('userres',$hashid);
                   11271: }
                   11272: 
1.624     albertel 11273: sub get_userresdata {
                   11274:     my ($uname,$udom)=@_;
                   11275:     #most student don\'t have any data set, check if there is some data
                   11276:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11277: 
                   11278:     my $hashid="$udom:$uname";
                   11279:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11280:     if (!defined($cached)) {
                   11281: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11282: 	$result=\%resourcedata;
                   11283: 	&do_cache_new('userres',$hashid,$result,600);
                   11284:     }
                   11285:     my ($tmp)=keys(%$result);
                   11286:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11287: 	return $result;
                   11288:     }
                   11289:     #error 2 occurs when the .db doesn't exist
                   11290:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11291:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11292: 	    &logthis("<font color=\"blue\">WARNING:".
                   11293: 		     " Trying to get resource data for ".
                   11294: 		     $uname." at ".$udom.": ".
                   11295: 		     $tmp."</font>");
                   11296:         }
1.624     albertel 11297:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11298: 	#&EXT_cache_set($udom,$uname);
                   11299: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11300: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11301:     }
                   11302:     return $tmp;
                   11303: }
1.879     foxr     11304: #----------------------------------------------- resdata - return resource data
                   11305: #  Purpose:
                   11306: #    Return resource data for either users or for a course.
                   11307: #  Parameters:
                   11308: #     $name      - Course/user name.
                   11309: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11310: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11311: #     $mapp      - decluttered URL of enclosing map  
                   11312: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11313: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11314: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11315: #     $courseid  - CourseID (first part of param identifier).
                   11316: #     $modifier  - Middle part of param identifier.
                   11317: #     $what      - Last part of param identifier.
1.879     foxr     11318: #     @which     - Array of names of resources desired.
                   11319: #  Returns:
                   11320: #     The value of the first reasource in @which that is found in the
                   11321: #     resource hash.
                   11322: #  Exceptional Conditions:
                   11323: #     If the $type passed in is not valid (not the string 'course' or 
                   11324: #     'user', an undefined  reference is returned.
                   11325: #     If none of the resources are found, an undef is returned
1.624     albertel 11326: sub resdata {
1.1301    raeburn  11327:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11328:         $modifier,$what,@which)=@_;
1.624     albertel 11329:     my $result;
                   11330:     if ($type eq 'course') {
                   11331: 	$result=&get_courseresdata($name,$domain);
                   11332:     } elsif ($type eq 'user') {
                   11333: 	$result=&get_userresdata($name,$domain);
                   11334:     }
                   11335:     if (!ref($result)) { return $result; }    
1.251     albertel 11336:     foreach my $item (@which) {
1.1301    raeburn  11337:         if ($item->[1] eq 'course') {
                   11338:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11339:                 unless ($$recursed) {
1.1302    raeburn  11340:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11341:                     $$recursed = 1;
                   11342:                 }
                   11343:                 foreach my $item (@${recurseup}) {
                   11344:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11345:                     last if (defined($result->{$norecursechk}));
                   11346:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11347:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11348:                 }
                   11349:             }
                   11350:         }
                   11351:         if (defined($result->{$item->[0]})) {
1.927     albertel 11352: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11353: 	}
1.250     albertel 11354:     }
1.291     albertel 11355:     return undef;
1.200     www      11356: }
                   11357: 
1.1360    raeburn  11358: sub get_domain_lti {
                   11359:     my ($cdom,$context) = @_;
                   11360:     my ($name,%lti);
                   11361:     if ($context eq 'consumer') {
                   11362:         $name = 'ltitools';
                   11363:     } elsif ($context eq 'provider') {
                   11364:         $name = 'lti';
                   11365:     } else {
                   11366:         return %lti;
                   11367:     }
                   11368:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11369:     if (defined($cached)) {
                   11370:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11371:             %lti = %{$result};
1.1298    raeburn  11372:         }
                   11373:     } else {
1.1360    raeburn  11374:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11375:         if (ref($domconfig{$name}) eq 'HASH') {
                   11376:             %lti = %{$domconfig{$name}};
                   11377:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11378:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11379:                 foreach my $id (keys(%lti)) {
                   11380:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11381:                         foreach my $item ('key','secret') {
1.1360    raeburn  11382:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11383:                         }
                   11384:                     }
                   11385:                 }
                   11386:             }
1.1298    raeburn  11387:         }
                   11388:         my $cachetime = 24*60*60;
1.1360    raeburn  11389:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11390:     }
1.1360    raeburn  11391:     return %lti;
1.1298    raeburn  11392: }
                   11393: 
1.1236    raeburn  11394: sub get_numsuppfiles {
                   11395:     my ($cnum,$cdom,$ignorecache)=@_;
                   11396:     my $hashid=$cnum.':'.$cdom;
                   11397:     my ($suppcount,$cached);
                   11398:     unless ($ignorecache) {
                   11399:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11400:     }
                   11401:     unless (defined($cached)) {
                   11402:         my $chome=&homeserver($cnum,$cdom);
                   11403:         unless ($chome eq 'no_host') {
1.1366    raeburn  11404:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11405:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11406:             ($suppcount,$supptools,$errors) =
                   11407:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11408:                                                          $supptools,$errors);
1.1236    raeburn  11409:         }
                   11410:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11411:     }
                   11412:     return $suppcount;
                   11413: }
                   11414: 
1.379     matthew  11415: #
                   11416: # EXT resource caching routines
                   11417: #
                   11418: 
1.1302    raeburn  11419: {
                   11420: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11421: #
                   11422: # The course for which we cache
                   11423: my $cachedmapkey='';
                   11424: # The cached recursive maps for this course
                   11425: my %cachedmaps=();
                   11426: # When this was last done
                   11427: my $cachedmaptime='';
                   11428: 
1.379     matthew  11429: sub clear_EXT_cache_status {
1.383     albertel 11430:     &delenv('cache.EXT.');
1.379     matthew  11431: }
                   11432: 
                   11433: sub EXT_cache_status {
                   11434:     my ($target_domain,$target_user) = @_;
1.383     albertel 11435:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11436:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11437:         # We know already the user has no data
                   11438:         return 1;
                   11439:     } else {
                   11440:         return 0;
                   11441:     }
                   11442: }
                   11443: 
                   11444: sub EXT_cache_set {
                   11445:     my ($target_domain,$target_user) = @_;
1.383     albertel 11446:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11447:     #&appenv({$cachename => time});
1.379     matthew  11448: }
                   11449: 
1.28      www      11450: # --------------------------------------------------------- Value of a Variable
1.58      www      11451: sub EXT {
1.715     albertel 11452: 
1.1228    raeburn  11453:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11454:     unless ($varname) { return ''; }
1.218     albertel 11455:     #get real user name/domain, courseid and symb
                   11456:     my $courseid;
1.359     albertel 11457:     my $publicuser;
1.427     www      11458:     if ($symbparm) {
                   11459: 	$symbparm=&get_symb_from_alias($symbparm);
                   11460:     }
1.218     albertel 11461:     if (!($uname && $udom)) {
1.790     albertel 11462:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11463:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11464:     } else {
1.620     albertel 11465: 	$courseid=$env{'request.course.id'};
1.218     albertel 11466:     }
1.48      www      11467:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11468:     my $rest;
1.320     albertel 11469:     if (defined($therest[0])) {
1.48      www      11470:        $rest=join('.',@therest);
                   11471:     } else {
                   11472:        $rest='';
                   11473:     }
1.320     albertel 11474: 
1.57      www      11475:     my $qualifierrest=$qualifier;
                   11476:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11477:     my $spacequalifierrest=$space;
                   11478:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11479:     if ($realm eq 'user') {
1.48      www      11480: # --------------------------------------------------------------- user.resource
                   11481: 	if ($space eq 'resource') {
1.651     albertel 11482: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11483: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11484: 		 &&
1.744     albertel 11485: 		 ($symbparm eq &symbread()) ) {	
                   11486: 		# if we are in the middle of processing the resource the
                   11487: 		# get the value we are planning on committing
                   11488:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11489:                     return $Apache::lonhomework::results{$qualifierrest};
                   11490:                 } else {
                   11491:                     return $Apache::lonhomework::history{$qualifierrest};
                   11492:                 }
1.335     albertel 11493: 	    } else {
1.359     albertel 11494: 		my %restored;
1.620     albertel 11495: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11496: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11497: 		} else {
                   11498: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11499: 		}
1.335     albertel 11500: 		return $restored{$qualifierrest};
                   11501: 	    }
1.48      www      11502: # ----------------------------------------------------------------- user.access
                   11503:         } elsif ($space eq 'access') {
1.218     albertel 11504: 	    # FIXME - not supporting calls for a specific user
1.48      www      11505:             return &allowed($qualifier,$rest);
                   11506: # ------------------------------------------ user.preferences, user.environment
                   11507:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11508: 	    if (($uname eq $env{'user.name'}) &&
                   11509: 		($udom eq $env{'user.domain'})) {
                   11510: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11511: 	    } else {
1.359     albertel 11512: 		my %returnhash;
                   11513: 		if (!$publicuser) {
                   11514: 		    %returnhash=&userenvironment($udom,$uname,
                   11515: 						 $qualifierrest);
                   11516: 		}
1.218     albertel 11517: 		return $returnhash{$qualifierrest};
                   11518: 	    }
1.48      www      11519: # ----------------------------------------------------------------- user.course
                   11520:         } elsif ($space eq 'course') {
1.218     albertel 11521: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11522:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11523: # ------------------------------------------------------------------- user.role
                   11524:         } elsif ($space eq 'role') {
1.218     albertel 11525: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11526:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11527:             if ($qualifier eq 'value') {
                   11528: 		return $role;
                   11529:             } elsif ($qualifier eq 'extent') {
                   11530:                 return $where;
                   11531:             }
                   11532: # ----------------------------------------------------------------- user.domain
                   11533:         } elsif ($space eq 'domain') {
1.218     albertel 11534:             return $udom;
1.48      www      11535: # ------------------------------------------------------------------- user.name
                   11536:         } elsif ($space eq 'name') {
1.218     albertel 11537:             return $uname;
1.48      www      11538: # ---------------------------------------------------- Any other user namespace
1.29      www      11539:         } else {
1.359     albertel 11540: 	    my %reply;
                   11541: 	    if (!$publicuser) {
                   11542: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11543: 	    }
                   11544: 	    return $reply{$qualifierrest};
1.48      www      11545:         }
1.236     www      11546:     } elsif ($realm eq 'query') {
                   11547: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11548:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11549: 						[$spacequalifierrest]);
1.620     albertel 11550: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11551:    } elsif ($realm eq 'request') {
1.48      www      11552: # ------------------------------------------------------------- request.browser
                   11553:         if ($space eq 'browser') {
1.1145    bisitz   11554:             return $env{'browser.'.$qualifier};
1.57      www      11555: # ------------------------------------------------------------ request.filename
                   11556:         } else {
1.620     albertel 11557:             return $env{'request.'.$spacequalifierrest};
1.29      www      11558:         }
1.28      www      11559:     } elsif ($realm eq 'course') {
1.48      www      11560: # ---------------------------------------------------------- course.description
1.620     albertel 11561:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11562:     } elsif ($realm eq 'resource') {
1.165     www      11563: 
1.620     albertel 11564: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11565: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11566: 	}
1.693     albertel 11567: 
1.1232    raeburn  11568:         if ($qualifier eq '') {
                   11569: 	    if ($space eq 'title') {
                   11570: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11571: 	        return &gettitle($symbparm);
                   11572: 	    }
1.693     albertel 11573: 	
1.1232    raeburn  11574: 	    if ($space eq 'map') {
                   11575: 	        my ($map) = &decode_symb($symbparm);
                   11576: 	        return &symbread($map);
                   11577: 	    }
                   11578:             if ($space eq 'maptitle') {
                   11579:                 my ($map) = &decode_symb($symbparm);
                   11580:                 return &gettitle($map);
                   11581:             }
                   11582: 	    if ($space eq 'filename') {
                   11583: 	        if ($symbparm) {
                   11584: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11585: 	        }
                   11586: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11587: 	    }
1.1232    raeburn  11588: 
1.1233    raeburn  11589:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11590:                 if ($space eq 'visibleparts') {
                   11591:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11592:                     my $item;
                   11593:                     if (ref($navmap)) {
                   11594:                         my $res = $navmap->getBySymb($symbparm);
                   11595:                         my $parts = $res->parts();
                   11596:                         if (ref($parts) eq 'ARRAY') {
                   11597:                             $item = join(',',@{$parts});
                   11598:                         }
                   11599:                         undef($navmap);
1.1232    raeburn  11600:                     }
1.1233    raeburn  11601:                     return $item;
1.1232    raeburn  11602:                 }
                   11603:             }
                   11604:         }
1.693     albertel 11605: 
1.1301    raeburn  11606: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11607: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11608:         if (($courseid eq '') && ($cid)) {
                   11609:             $courseid = $cid;
                   11610:         }
                   11611: 	if (($symbparm && $courseid) && 
                   11612: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11613: 
1.218     albertel 11614: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11615: 
1.60      www      11616: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11617: 	    my $symbp=$symbparm;
1.1301    raeburn  11618: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11619: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11620:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11621: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11622: 	    if (($env{'user.name'} eq $uname) &&
                   11623: 		($env{'user.domain'} eq $udom)) {
                   11624: 		$section=$env{'request.course.sec'};
1.733     raeburn  11625:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11626:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11627: 	    } else {
1.539     albertel 11628: 		if (! defined($usection)) {
1.551     albertel 11629: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11630: 		} else {
                   11631: 		    $section = $usection;
                   11632: 		}
1.733     raeburn  11633:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11634: 	    }
                   11635: 
                   11636: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11637: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11638:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11639: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11640: 
1.593     albertel 11641: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11642: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11643:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11644: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11645: 
1.60      www      11646: # ----------------------------------------------------------- first, check user
1.624     albertel 11647: 
1.1301    raeburn  11648: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11649:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11650: 				       ([$courselevelr,'resource'],
                   11651: 					[$courselevelm,'map'     ],
1.1301    raeburn  11652:                                         [$courseleveli,'map'     ],
1.927     albertel 11653: 					[$courselevel, 'course'  ]));
1.931     albertel 11654: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11655: 
1.594     albertel 11656: # ------------------------------------------------ second, check some of course
1.684     raeburn  11657:             my $coursereply;
1.691     raeburn  11658:             if (@groups > 0) {
                   11659:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11660:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11661:                                        $mapp,\$recursed,\@recurseup);
                   11662:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11663:             }
1.96      www      11664: 
1.684     raeburn  11665: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11666: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11667: 				  'course',$mapp,\$recursed,\@recurseup,
                   11668:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11669: 				  ([$seclevelr,   'resource'],
                   11670: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11671:                                    [$secleveli,   'map'     ],
1.927     albertel 11672: 				   [$seclevel,    'course'  ],
                   11673: 				   [$courselevelr,'resource']));
                   11674: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11675: 
1.60      www      11676: # ------------------------------------------------------ third, check map parms
1.218     albertel 11677: 	    my %parmhash=();
                   11678: 	    my $thisparm='';
                   11679: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11680: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11681: 		    &GDBM_READER(),0640)) {
1.218     albertel 11682: 		$thisparm=$parmhash{$symbparm};
                   11683: 		untie(%parmhash);
                   11684: 	    }
1.927     albertel 11685: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11686: 	}
1.594     albertel 11687: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11688:  
                   11689:         my $what = $spacequalifierrest;
                   11690: 	$what=~s/\./\_/;
1.282     albertel 11691: 	my $filename;
                   11692: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11693: 	if ($symbparm) {
1.409     www      11694: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11695: 	} else {
1.620     albertel 11696: 	    $filename=$env{'request.filename'};
1.282     albertel 11697: 	}
1.1362    raeburn  11698:         my $toolsymb;
                   11699:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11700:             $toolsymb = $symbparm;
                   11701:         }
                   11702: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11703: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11704: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11705: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11706: 
1.1301    raeburn  11707: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11708: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11709: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11710: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11711: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11712: 				     'course',$mapp,\$recursed,\@recurseup,
                   11713:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11714: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11715:                                       [$courseleveli,'map'   ],
1.927     albertel 11716: 				      [$courselevel, 'course']));
                   11717: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11718: 	}
1.145     www      11719: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11720: 	unless ($space eq '0') {
1.336     albertel 11721: 	    my @parts=split(/_/,$space);
                   11722: 	    my $id=pop(@parts);
                   11723: 	    my $part=join('_',@parts);
                   11724: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11725: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11726: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11727: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11728: 	}
1.395     albertel 11729: 	if ($recurse) { return undef; }
1.1362    raeburn  11730: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11731: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11732: # ---------------------------------------------------- Any other user namespace
                   11733:     } elsif ($realm eq 'environment') {
                   11734: # ----------------------------------------------------------------- environment
1.620     albertel 11735: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11736: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11737: 	} else {
1.770     albertel 11738: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11739: 		return '';
                   11740: 	    }
1.219     albertel 11741: 	    my %returnhash=&userenvironment($udom,$uname,
                   11742: 					    $spacequalifierrest);
                   11743: 	    return $returnhash{$spacequalifierrest};
                   11744: 	}
1.28      www      11745:     } elsif ($realm eq 'system') {
1.48      www      11746: # ----------------------------------------------------------------- system.time
                   11747: 	if ($space eq 'time') {
                   11748: 	    return time;
                   11749:         }
1.696     albertel 11750:     } elsif ($realm eq 'server') {
                   11751: # ----------------------------------------------------------------- system.time
                   11752: 	if ($space eq 'name') {
                   11753: 	    return $ENV{'SERVER_NAME'};
                   11754:         }
1.28      www      11755:     }
1.48      www      11756:     return '';
1.61      www      11757: }
                   11758: 
1.927     albertel 11759: sub get_reply {
                   11760:     my ($reply_value) = @_;
1.940     raeburn  11761:     if (ref($reply_value) eq 'ARRAY') {
                   11762:         if (wantarray) {
                   11763: 	    return @$reply_value;
                   11764:         }
                   11765:         return $reply_value->[0];
                   11766:     } else {
                   11767:         return $reply_value;
1.927     albertel 11768:     }
                   11769: }
                   11770: 
1.691     raeburn  11771: sub check_group_parms {
1.1301    raeburn  11772:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11773:         $recursed,$recurseupref) = @_;
                   11774:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11775:                   [$what,'course']);
                   11776:     my $coursereply;
1.691     raeburn  11777:     foreach my $group (@{$groups}) {
1.1301    raeburn  11778:         my @groupitems = ();
1.691     raeburn  11779:         foreach my $level (@levels) {
1.927     albertel 11780:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11781:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11782:         }
1.1301    raeburn  11783:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11784:                                    $env{'course.'.$courseid.'.domain'},
                   11785:                                    'course',$mapp,$recursed,$recurseupref,
                   11786:                                    $courseid,'.['.$group.'].',$what,
                   11787:                                    @groupitems);
                   11788:         last if (defined($coursereply));
1.691     raeburn  11789:     }
                   11790:     return $coursereply;
                   11791: }
                   11792: 
1.1301    raeburn  11793: sub get_map_hierarchy {
1.1302    raeburn  11794:     my ($mapname,$courseid) = @_;
                   11795:     my @recurseup = ();
1.1301    raeburn  11796:     if ($mapname) {
1.1302    raeburn  11797:         if (($cachedmapkey eq $courseid) &&
                   11798:             (abs($cachedmaptime-time)<5)) {
                   11799:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11800:                 return @{$cachedmaps{$mapname}};
                   11801:             }
                   11802:         }
1.1301    raeburn  11803:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11804:         if (ref($navmap)) {
                   11805:             @recurseup = $navmap->recurseup_maps($mapname);
                   11806:             undef($navmap);
1.1302    raeburn  11807:             $cachedmaps{$mapname} = \@recurseup;
                   11808:             $cachedmaptime=time;
                   11809:             $cachedmapkey=$courseid;
1.1301    raeburn  11810:         }
                   11811:     }
                   11812:     return @recurseup;
                   11813: }
                   11814: 
1.1302    raeburn  11815: }
                   11816: 
1.691     raeburn  11817: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11818:     my ($courseid,@groups) = @_;
                   11819:     @groups = sort(@groups);
1.691     raeburn  11820:     return @groups;
                   11821: }
                   11822: 
1.395     albertel 11823: sub packages_tab_default {
1.1362    raeburn  11824:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11825:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11826: 
                   11827:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11828:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11829: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11830: 	if ($pack_type eq 'default') {
                   11831: 	    $do_default=1;
                   11832: 	} elsif ($pack_type eq 'extension') {
                   11833: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11834: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11835: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11836: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11837: 	}
                   11838:     }
                   11839:     # first look for a package that matches the requested part id
                   11840:     foreach my $package (@specifics) {
                   11841: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11842: 	next if ($pack_part ne $part);
                   11843: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11844: 	    return $packagetab{"$pack_type&$name&default"};
                   11845: 	}
                   11846:     }
                   11847:     # look for any possible matching non extension_ package
                   11848:     foreach my $package (@specifics) {
                   11849: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11850: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11851: 	    return $packagetab{"$pack_type&$name&default"};
                   11852: 	}
1.585     albertel 11853: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11854: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11855: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11856: 	}
                   11857:     }
1.738     albertel 11858:     # look for any posible extension_ match
                   11859:     foreach my $package (@extension) {
                   11860: 	my ($package,$pack_type)=@{$package};
                   11861: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11862: 	    return $packagetab{"$pack_type&$name&default"};
                   11863: 	}
                   11864: 	if (defined($packagetab{$package."&$name&default"})) {
                   11865: 	    return $packagetab{$package."&$name&default"};
                   11866: 	}
                   11867:     }
                   11868:     # look for a global default setting
                   11869:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11870: 	return $packagetab{"default&$name&default"};
                   11871:     }
1.395     albertel 11872:     return undef;
                   11873: }
                   11874: 
1.334     albertel 11875: sub add_prefix_and_part {
                   11876:     my ($prefix,$part)=@_;
                   11877:     my $keyroot;
                   11878:     if (defined($prefix) && $prefix !~ /^__/) {
                   11879: 	# prefix that has a part already
                   11880: 	$keyroot=$prefix;
                   11881:     } elsif (defined($prefix)) {
                   11882: 	# prefix that is missing a part
                   11883: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11884:     } else {
                   11885: 	# no prefix at all
                   11886: 	if (defined($part)) { $keyroot='_'.$part; }
                   11887:     }
                   11888:     return $keyroot;
                   11889: }
                   11890: 
1.71      www      11891: # ---------------------------------------------------------------- Get metadata
                   11892: 
1.599     albertel 11893: my %metaentry;
1.1070    www      11894: my %importedpartids;
1.1369    raeburn  11895: my %importedrespids;
1.71      www      11896: sub metadata {
1.1362    raeburn  11897:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11898:     $uri=&declutter($uri);
1.288     albertel 11899:     # if it is a non metadata possible uri return quickly
1.529     albertel 11900:     if (($uri eq '') || 
                   11901: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11902: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11903:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11904: 	return undef;
                   11905:     }
1.1261    raeburn  11906:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11907: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11908: 	return undef;
1.288     albertel 11909:     }
1.73      www      11910:     my $filename=$uri;
                   11911:     $uri=~s/\.meta$//;
1.172     www      11912: #
                   11913: # Is the metadata already cached?
1.177     www      11914: # Look at timestamp of caching
1.172     www      11915: # Everything is cached by the main uri, libraries are never directly cached
                   11916: #
1.428     albertel 11917:     if (!defined($liburi)) {
1.599     albertel 11918: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11919: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11920:     }
1.1362    raeburn  11921: 
                   11922: #
                   11923: # If the uri is for an external tool the file from
                   11924: # which metadata should be retrieved depends on whether
                   11925: # the tool had been configured to be gradable (set in the Course
                   11926: # Editor or Resource Editor).
                   11927: #
                   11928: # If a valid symb has been included as the third arg in the call
                   11929: # to &metadata() that can be used to retrieve the value of
                   11930: # parameter_0_gradable set for the resource, and included in the
                   11931: # uploaded map containing the tool. The value is retrieved via
                   11932: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11933: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11934: # is retrieved via &get().
                   11935: #
                   11936: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11937: # hiddenresource and encrypturl (during course initialization)
                   11938: # the map-level parameter for resource.0.gradable included in the 
                   11939: # uploaded map containing the tool will not yet have been stored
                   11940: # in the user_course_parms.db file for the user's session, so in 
                   11941: # this case fall back to retrieving gradable status from the
                   11942: # exttool_$marker.db file.
1.1362    raeburn  11943: #
                   11944: # In order to avoid an infinite loop, &metadata() will return
                   11945: # before a call to &EXT(), if the uri is for an external tool
                   11946: # and the $what for which metadata is being requested is
                   11947: # parameter_0_gradable or 0_gradable.
                   11948: #
                   11949: 
                   11950:     if ($uri =~ /ext\.tool$/) {
                   11951:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11952:             return;
                   11953:         } else {
                   11954:             my ($checked,$use_passback);
                   11955:             if ($toolsymb ne '') {
                   11956:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11957:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11958:                     $checked = 1;
                   11959:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11960:                         $use_passback = 1;
                   11961:                     }
                   11962:                 }
                   11963:             }
                   11964:             unless ($checked) {
                   11965:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11966:                 $marker=~s/\D//g;
1.1363    raeburn  11967:                 if ($marker) {
1.1362    raeburn  11968:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11969:                     $use_passback = $toolsettings{'gradable'};
                   11970:                 }
                   11971:             }
                   11972:             if ($use_passback) {
                   11973:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11974:             } else {
                   11975:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11976:             }
                   11977:         }
                   11978:     }
                   11979: 
1.428     albertel 11980:     {
1.1069    www      11981: # Imported parts would go here
1.1369    raeburn  11982:         my @origfiletagids=();
1.1069    www      11983:         my $importedparts=0;
1.1369    raeburn  11984: 
                   11985: # Imported responseids would go here
                   11986:         my $importedresponses=0;
1.172     www      11987: #
                   11988: # Is this a recursive call for a library?
                   11989: #
1.599     albertel 11990: #	if (! exists($metacache{$uri})) {
                   11991: #	    $metacache{$uri}={};
                   11992: #	}
1.924     albertel 11993: 	my $cachetime = 60*60;
1.171     www      11994:         if ($liburi) {
                   11995: 	    $liburi=&declutter($liburi);
                   11996:             $filename=$liburi;
1.401     bowersj2 11997:         } else {
1.599     albertel 11998: 	    &devalidate_cache_new('meta',$uri);
                   11999: 	    undef(%metaentry);
1.401     bowersj2 12000: 	}
1.140     www      12001:         my %metathesekeys=();
1.73      www      12002:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12003: 	my $metastring;
1.1140    www      12004: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12005: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12006: 	    $metastring = 
1.929     albertel 12007: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12008: 					  ('grade_target' => 'meta'));
                   12009: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12010: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12011:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12012: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12013: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12014: 	    $metastring=&getfile($file);
1.489     albertel 12015: 	}
1.208     albertel 12016:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12017:         my $token;
1.140     www      12018:         undef %metathesekeys;
1.71      www      12019:         while ($token=$parser->get_token) {
1.339     albertel 12020: 	    if ($token->[0] eq 'S') {
                   12021: 		if (defined($token->[2]->{'package'})) {
1.172     www      12022: #
                   12023: # This is a package - get package info
                   12024: #
1.339     albertel 12025: 		    my $package=$token->[2]->{'package'};
                   12026: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12027: 		    if (defined($token->[2]->{'id'})) { 
                   12028: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12029: 		    }
1.599     albertel 12030: 		    if ($metaentry{':packages'}) {
                   12031: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12032: 		    } else {
1.599     albertel 12033: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12034: 		    }
1.736     albertel 12035: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12036: 			my $part=$keyroot;
                   12037: 			$part=~s/^\_//;
1.736     albertel 12038: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12039: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12040: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12041: 			    # ignore package.tab specified default values
                   12042:                             # here &package_tab_default() will fetch those
                   12043: 			    if ($subp eq 'default') { next; }
1.736     albertel 12044: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12045: 			    my $unikey;
                   12046: 			    if ($pack =~ /_0$/) {
                   12047: 				$unikey='parameter_0_'.$name;
                   12048: 				$part=0;
                   12049: 			    } else {
                   12050: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12051: 			    }
1.339     albertel 12052: 			    if ($subp eq 'display') {
                   12053: 				$value.=' [Part: '.$part.']';
                   12054: 			    }
1.599     albertel 12055: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12056: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12057: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12058: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12059: 			    }
1.599     albertel 12060: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12061: 				$metaentry{':'.$unikey}=
                   12062: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12063: 			    }
1.339     albertel 12064: 			}
                   12065: 		    }
                   12066: 		} else {
1.172     www      12067: #
                   12068: # This is not a package - some other kind of start tag
1.339     albertel 12069: #
                   12070: 		    my $entry=$token->[1];
1.1068    www      12071: 		    my $unikey='';
1.175     www      12072: 
1.339     albertel 12073: 		    if ($entry eq 'import') {
1.175     www      12074: #
                   12075: # Importing a library here
1.339     albertel 12076: #
1.1067    www      12077:                         my $location=$parser->get_text('/import');
                   12078:                         my $dir=$filename;
                   12079:                         $dir=~s|[^/]*$||;
                   12080:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12081: 
                   12082:                         my $importid=$token->[2]->{'id'};
1.1068    www      12083:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12084: #
                   12085: # Check metadata for imported file to
                   12086: # see if it contained response items
                   12087: #
1.1372    raeburn  12088:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12089:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12090:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12091:                                                            $depthcount+1));
                   12092:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12093:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12094:                                                              undef,$depthcount+1);
                   12095:                             if ($libresponseorder ne '') {
                   12096:                                 if ($#origfiletagids<0) {
                   12097:                                     undef(%importedrespids);
                   12098:                                     undef(%importedpartids);
                   12099:                                 }
1.1373    raeburn  12100:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12101:                                 if (@respids) {
                   12102:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12103:                                 }
                   12104:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12105:                                     $importedresponses = 1;
1.1369    raeburn  12106: # We need to get the original file and the imported file to get the response order correct
                   12107: # Load and inspect original file
1.1372    raeburn  12108:                                     if ($#origfiletagids<0) {
                   12109:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12110:                                         $origfile=&getfile($origfilelocation);
                   12111:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12112:                                     }
1.1369    raeburn  12113:                                 }
                   12114:                             }
                   12115:                         }
1.1370    raeburn  12116: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12117: # hash populated for imported library file
                   12118:                         %metaentry = %currmetaentry;
                   12119:                         undef(%currmetaentry);
1.1374    raeburn  12120:                         if ($importmode eq 'part') {
1.1068    www      12121: # Import as part(s)
1.1069    www      12122:                            $importedparts=1;
                   12123: # We need to get the original file and the imported file to get the part order correct
                   12124: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12125: # Load and inspect original file if we didn't do that already
                   12126:                            if ($#origfiletagids<0) {
                   12127:                                undef(%importedrespids);
                   12128:                                undef(%importedpartids);
                   12129:                                if ($origfile eq '') {
                   12130:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12131:                                    $origfile=&getfile($origfilelocation);
                   12132:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12133:                                }
1.1070    www      12134:                            }
1.1372    raeburn  12135:                            my @impfilepartids;
                   12136: # If <partorder> tag is included in metadata for the imported file
                   12137: # get the parts in the imported file from that.
                   12138:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12139:                                %currmetaentry = %metaentry;
                   12140:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12141:                                                             $depthcount+1);
                   12142:                                %metaentry = %currmetaentry;
                   12143:                                undef(%currmetaentry);
                   12144:                                if ($libpartorder ne '') {
                   12145:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12146:                                }
                   12147:                            } else {
                   12148: # If no <partorder> tag available, load and inspect imported file
                   12149:                                my $impfile=&getfile($location);
                   12150:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12151:                            }
1.1069    www      12152:                            if ($#impfilepartids>=0) {
                   12153: # This problem had parts
1.1070    www      12154:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12155:                            } else {
                   12156: # Importing by turning a single problem into a problem part
                   12157: # It gets the import-tags ID as part-ID
                   12158:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12159:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12160:                            }
1.1068    www      12161:                         } else {
1.1374    raeburn  12162: # Import as problem or as normal import
                   12163:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12164:                             unless ($importmode eq 'problem') {
1.1068    www      12165: # Normal import
1.1374    raeburn  12166:                                 if (defined($token->[2]->{'id'})) {
                   12167:                                     $unikey.='_'.$token->[2]->{'id'};
                   12168:                                 }
                   12169:                             }
                   12170: # Check metadata for imported file to
                   12171: # see if it contained parts
                   12172:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12173:                                 %currmetaentry = %metaentry;
                   12174:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12175:                                                              $depthcount+1);
                   12176:                                 %metaentry = %currmetaentry;
                   12177:                                 undef(%currmetaentry);
                   12178:                                 if ($libpartorder ne '') {
                   12179:                                     $importedparts = 1;
                   12180:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12181:                                 }
                   12182:                             }
1.1067    www      12183:                         }
1.339     albertel 12184: 			if ($depthcount<20) {
1.736     albertel 12185: 			    my $metadata = 
1.1362    raeburn  12186: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12187: 					  $depthcount+1);
                   12188: 			    foreach my $meta (split(',',$metadata)) {
                   12189: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12190: 				$metathesekeys{$meta}=1;
1.339     albertel 12191: 			    }
1.1068    www      12192:                         }
1.1067    www      12193: 		    } else {
                   12194: #
                   12195: # Not importing, some other kind of non-package, non-library start tag
                   12196: # 
                   12197:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12198:                         if (defined($token->[2]->{'id'})) {
                   12199:                             $unikey.='_'.$token->[2]->{'id'};
                   12200:                         }
1.339     albertel 12201: 			if (defined($token->[2]->{'name'})) { 
                   12202: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12203: 			}
                   12204: 			$metathesekeys{$unikey}=1;
1.736     albertel 12205: 			foreach my $param (@{$token->[3]}) {
                   12206: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12207: 				$token->[2]->{$param};
1.339     albertel 12208: 			}
                   12209: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12210: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12211: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12212: 		 # only ws inside the tag, and not in default, so use default
                   12213: 		 # as value
1.599     albertel 12214: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12215: 			} elsif ( $internaltext =~ /\S/ ) {
                   12216: 		  # something interesting inside the tag
                   12217: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12218: 			} else {
1.908     albertel 12219: 		  # no interesting values, don't set a default
1.339     albertel 12220: 			}
1.172     www      12221: # end of not-a-package not-a-library import
1.339     albertel 12222: 		    }
1.172     www      12223: # end of not-a-package start tag
1.339     albertel 12224: 		}
1.172     www      12225: # the next is the end of "start tag"
1.339     albertel 12226: 	    }
                   12227: 	}
1.483     albertel 12228: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12229: 	$extension = lc($extension);
                   12230: 	if ($extension eq 'htm') { $extension='html'; }
                   12231: 
1.737     albertel 12232: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12233: 	    #no specific packages #how's our extension
                   12234: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12235: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12236: 					 \%metathesekeys);
                   12237: 	}
1.883     albertel 12238: 
                   12239: 	if (!exists($metaentry{':packages'})
                   12240: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12241: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12242: 		#no specific packages well let's get default then
                   12243: 		if ($key!~/^default&/) { next; }
1.488     albertel 12244: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12245: 					     \%metathesekeys);
                   12246: 	    }
                   12247: 	}
1.338     www      12248: # are there custom rights to evaluate
1.599     albertel 12249: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12250: 
1.338     www      12251:     #
                   12252:     # Importing a rights file here
1.339     albertel 12253:     #
                   12254: 	    unless ($depthcount) {
1.599     albertel 12255: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12256: 		my $dir=$filename;
                   12257: 		$dir=~s|[^/]*$||;
                   12258: 		$location=&filelocation($dir,$location);
1.736     albertel 12259: 		my $rights_metadata =
1.1362    raeburn  12260: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12261: 			      $depthcount+1);
                   12262: 		foreach my $rights (split(',',$rights_metadata)) {
                   12263: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12264: 		    $metathesekeys{$rights}=1;
1.339     albertel 12265: 		}
                   12266: 	    }
                   12267: 	}
1.737     albertel 12268: 	# uniqifiy package listing
                   12269: 	my %seen;
                   12270: 	my @uniq_packages =
                   12271: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12272: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12273: 
1.1369    raeburn  12274:         if (($importedresponses) || ($importedparts)) {
                   12275:             if ($importedparts) {
1.1070    www      12276: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12277:                 $metaentry{':partorder'}='';
                   12278:                 $metathesekeys{'partorder'}=1;
                   12279:             }
                   12280:             if ($importedresponses) {
                   12281: # We had imported responses and need to rebuil responseorder
                   12282:                 $metaentry{':responseorder'}='';
                   12283:                 $metathesekeys{'responseorder'}=1;
                   12284:             }
                   12285:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12286:                 my $origid = $origfiletagids[$index+1];
                   12287:                 if ($origfiletagids[$index] eq 'part') {
                   12288: # Original part, part of the problem
                   12289:                     if ($importedparts) {
                   12290:                         $metaentry{':partorder'}.=','.$origid;
                   12291:                     }
                   12292:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12293:                     if ($importedparts) {
                   12294: # We have imported parts at this position
1.1373    raeburn  12295:                         if ($importedpartids{$origid} ne '') {
                   12296:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12297:                         }
1.1369    raeburn  12298:                     }
                   12299:                     if ($importedresponses) {
                   12300: # We have imported responses at this position
1.1373    raeburn  12301:                         if ($importedrespids{$origid} ne '') {
                   12302:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12303:                         }
                   12304:                     }
                   12305:                 } else {
                   12306: # Original response item, part of the problem
                   12307:                     if ($importedresponses) {
                   12308:                         $metaentry{':responseorder'}.=','.$origid;
                   12309:                     }
                   12310:                 }
                   12311:             }
                   12312:             if ($importedparts) {
                   12313:                 $metaentry{':partorder'}=~s/^\,//;
                   12314:             }
                   12315:             if ($importedresponses) {
                   12316:                 $metaentry{':responseorder'}=~s/^\,//;
                   12317:             }
1.1070    www      12318:         }
1.737     albertel 12319: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12320: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12321: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12322:         unless ($liburi) {
                   12323: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12324:         }
1.177     www      12325: # this is the end of "was not already recently cached
1.71      www      12326:     }
1.599     albertel 12327:     return $metaentry{':'.$what};
1.261     albertel 12328: }
                   12329: 
1.488     albertel 12330: sub metadata_create_package_def {
1.483     albertel 12331:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12332:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12333:     if ($subp eq 'default') { next; }
                   12334:     
1.599     albertel 12335:     if (defined($metaentry{':packages'})) {
                   12336: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12337:     } else {
1.599     albertel 12338: 	$metaentry{':packages'}=$package;
1.483     albertel 12339:     }
                   12340:     my $value=$packagetab{$key};
                   12341:     my $unikey;
                   12342:     $unikey='parameter_0_'.$name;
1.599     albertel 12343:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12344:     $$metathesekeys{$unikey}=1;
1.599     albertel 12345:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12346: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12347:     }
1.599     albertel 12348:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12349: 	$metaentry{':'.$unikey}=
                   12350: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12351:     }
                   12352: }
                   12353: 
1.261     albertel 12354: sub metadata_generate_part0 {
                   12355:     my ($metadata,$metacache,$uri) = @_;
                   12356:     my %allnames;
1.737     albertel 12357:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12358: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12359: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12360: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12361: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12362: 	    $allnames{$name}=$part;
                   12363: 	  }
                   12364: 	}
                   12365:     }
                   12366:     foreach my $name (keys(%allnames)) {
                   12367:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12368:       my $key=":parameter_0_$name";
1.261     albertel 12369:       $$metacache{"$key.part"}='0';
                   12370:       $$metacache{"$key.name"}=$name;
1.428     albertel 12371:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12372: 					   $allnames{$name}.'_'.$name.
                   12373: 					   '.type'};
1.428     albertel 12374:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12375: 			     '.display'};
1.644     www      12376:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12377:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12378:       $$metacache{"$key.display"}=$olddis;
                   12379:     }
1.71      www      12380: }
                   12381: 
1.764     albertel 12382: # ------------------------------------------------------ Devalidate title cache
                   12383: 
                   12384: sub devalidate_title_cache {
                   12385:     my ($url)=@_;
                   12386:     if (!$env{'request.course.id'}) { return; }
                   12387:     my $symb=&symbread($url);
                   12388:     if (!$symb) { return; }
                   12389:     my $key=$env{'request.course.id'}."\0".$symb;
                   12390:     &devalidate_cache_new('title',$key);
                   12391: }
                   12392: 
1.1014    droeschl 12393: # ------------------------------------------------- Get the title of a course
                   12394: 
                   12395: sub current_course_title {
                   12396:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12397: }
1.301     www      12398: # ------------------------------------------------- Get the title of a resource
                   12399: 
                   12400: sub gettitle {
                   12401:     my $urlsymb=shift;
                   12402:     my $symb=&symbread($urlsymb);
1.534     albertel 12403:     if ($symb) {
1.620     albertel 12404: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12405: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12406: 	if (defined($cached)) { 
                   12407: 	    return $result;
                   12408: 	}
1.534     albertel 12409: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12410: 	my $title='';
1.907     albertel 12411: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12412: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12413: 	} else {
                   12414: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12415: 		    &GDBM_READER(),0640)) {
                   12416: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12417: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12418: 		untie(%bighash);
                   12419: 	    }
1.534     albertel 12420: 	}
                   12421: 	$title=~s/\&colon\;/\:/gs;
                   12422: 	if ($title) {
1.1159    www      12423: # Remember both $symb and $title for dynamic metadata
                   12424:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12425:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12426: # Cache this title and then return it
1.599     albertel 12427: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12428: 	}
                   12429: 	$urlsymb=$url;
                   12430:     }
                   12431:     my $title=&metadata($urlsymb,'title');
                   12432:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12433:     return $title;
1.301     www      12434: }
1.613     albertel 12435: 
1.614     albertel 12436: sub get_slot {
                   12437:     my ($which,$cnum,$cdom)=@_;
                   12438:     if (!$cnum || !$cdom) {
1.790     albertel 12439: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12440: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12441: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12442:     }
1.703     albertel 12443:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12444:     my %slotinfo;
                   12445:     if (exists($remembered{$key})) {
                   12446: 	$slotinfo{$which} = $remembered{$key};
                   12447:     } else {
                   12448: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12449: 	&Apache::lonhomework::showhash(%slotinfo);
                   12450: 	my ($tmp)=keys(%slotinfo);
                   12451: 	if ($tmp=~/^error:/) { return (); }
                   12452: 	$remembered{$key} = $slotinfo{$which};
                   12453:     }
1.616     albertel 12454:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12455: 	return %{$slotinfo{$which}};
                   12456:     }
                   12457:     return $slotinfo{$which};
1.614     albertel 12458: }
1.1150    raeburn  12459: 
                   12460: sub get_reservable_slots {
                   12461:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12462:     my $now = time;
                   12463:     my $reservable_info;
                   12464:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12465:     if (exists($remembered{$key})) {
                   12466:         $reservable_info = $remembered{$key};
                   12467:     } else {
                   12468:         my %resv;
                   12469:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12470:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12471:         $reservable_info = \%resv;
                   12472:         $remembered{$key} = $reservable_info;
                   12473:     }
                   12474:     return $reservable_info;
                   12475: }
                   12476: 
                   12477: sub get_course_slots {
                   12478:     my ($cnum,$cdom) = @_;
                   12479:     my $hashid=$cnum.':'.$cdom;
                   12480:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12481:     if (defined($cached)) {
                   12482:         if (ref($result) eq 'HASH') {
                   12483:             return %{$result};
                   12484:         }
                   12485:     } else {
                   12486:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12487:         my ($tmp) = keys(%slots);
                   12488:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12489:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12490:             return %slots;
                   12491:         }
                   12492:     }
                   12493:     return;
                   12494: }
                   12495: 
                   12496: sub devalidate_slots_cache {
                   12497:     my ($cnum,$cdom)=@_;
                   12498:     my $hashid=$cnum.':'.$cdom;
                   12499:     &devalidate_cache_new('allslots',$hashid);
                   12500: }
                   12501: 
1.1181    raeburn  12502: sub get_coursechange {
                   12503:     my ($cdom,$cnum) = @_;
                   12504:     if ($cdom eq '' || $cnum eq '') {
                   12505:         return unless ($env{'request.course.id'});
                   12506:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12507:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12508:     }
                   12509:     my $hashid=$cdom.'_'.$cnum;
                   12510:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12511:     if ((defined($cached)) && ($change ne '')) {
                   12512:         return $change;
                   12513:     } else {
                   12514:         my %crshash;
                   12515:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12516:         if ($crshash{'internal.contentchange'} eq '') {
                   12517:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12518:             if ($change eq '') {
                   12519:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12520:                 $change = $crshash{'internal.created'};
                   12521:             }
                   12522:         } else {
                   12523:             $change = $crshash{'internal.contentchange'};
                   12524:         }
                   12525:         my $cachetime = 600;
                   12526:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12527:     }
                   12528:     return $change;
                   12529: }
                   12530: 
                   12531: sub devalidate_coursechange_cache {
                   12532:     my ($cnum,$cdom)=@_;
                   12533:     my $hashid=$cnum.':'.$cdom;
                   12534:     &devalidate_cache_new('crschange',$hashid);
                   12535: }
                   12536: 
1.31      www      12537: # ------------------------------------------------- Update symbolic store links
                   12538: 
                   12539: sub symblist {
                   12540:     my ($mapname,%newhash)=@_;
1.438     www      12541:     $mapname=&deversion(&declutter($mapname));
1.31      www      12542:     my %hash;
1.620     albertel 12543:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12544:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12545:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12546: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12547: 		next if ($url eq 'last_known'
                   12548: 			 && $env{'form.no_update_last_known'});
                   12549: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12550: 						    $newhash{$url}->[1],
                   12551: 						    $newhash{$url}->[0]);
1.191     harris41 12552:             }
1.31      www      12553:             if (untie(%hash)) {
                   12554: 		return 'ok';
                   12555:             }
                   12556:         }
                   12557:     }
                   12558:     return 'error';
1.212     www      12559: }
                   12560: 
                   12561: # --------------------------------------------------------------- Verify a symb
                   12562: 
                   12563: sub symbverify {
1.1190    raeburn  12564:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12565:     my $thisfn=$thisurl;
1.439     www      12566:     $thisfn=&declutter($thisfn);
1.215     www      12567: # direct jump to resource in page or to a sequence - will construct own symbs
                   12568:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12569: # check URL part
1.409     www      12570:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12571: 
1.431     www      12572:     unless ($url eq $thisfn) { return 0; }
1.213     www      12573: 
1.216     www      12574:     $symb=&symbclean($symb);
1.510     www      12575:     $thisurl=&deversion($thisurl);
1.439     www      12576:     $thisfn=&deversion($thisfn);
1.213     www      12577: 
                   12578:     my %bighash;
                   12579:     my $okay=0;
1.431     www      12580: 
1.620     albertel 12581:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12582:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12583:         my $noclutter;
1.1032    raeburn  12584:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12585:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12586:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12587:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12588:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12589:                 $noclutter = 1;
                   12590:             }
                   12591:         }
                   12592:         my $ids;
                   12593:         if ($noclutter) {
                   12594:             $ids=$bighash{'ids_'.$thisurl};
                   12595:         } else {
                   12596:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12597:         }
1.1102    raeburn  12598:         unless ($ids) {
                   12599:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12600:             $ids=$bighash{$idkey};
1.216     www      12601:         }
                   12602:         if ($ids) {
                   12603: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12604:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12605:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12606:             }
1.800     albertel 12607: 	    foreach my $id (split(/\,/,$ids)) {
                   12608: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12609:                if (
                   12610:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12611:    eq $symb) {
                   12612:                    if (ref($encstate)) {
                   12613:                        $$encstate = $bighash{'encrypted_'.$id};
                   12614:                    }
1.620     albertel 12615: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12616: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12617:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12618: 		       $okay=1;
1.1202    raeburn  12619:                        last;
1.582     albertel 12620: 		   }
                   12621: 	       }
1.216     www      12622: 	   }
                   12623:         }
1.213     www      12624: 	untie(%bighash);
                   12625:     }
                   12626:     return $okay;
1.31      www      12627: }
                   12628: 
1.210     www      12629: # --------------------------------------------------------------- Clean-up symb
                   12630: 
                   12631: sub symbclean {
                   12632:     my $symb=shift;
1.568     albertel 12633:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12634: # remove version from map
                   12635:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12636: 
1.210     www      12637: # remove version from URL
                   12638:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12639: 
1.507     www      12640: # remove wrapper
                   12641: 
1.510     www      12642:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12643:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12644:     return $symb;
1.409     www      12645: }
                   12646: 
                   12647: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12648: 
                   12649: sub encode_symb {
                   12650:     my ($map,$resid,$url)=@_;
                   12651:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12652: }
1.409     www      12653: 
                   12654: sub decode_symb {
1.568     albertel 12655:     my $symb=shift;
                   12656:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12657:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12658:     return (&fixversion($map),$resid,&fixversion($url));
                   12659: }
                   12660: 
                   12661: sub fixversion {
                   12662:     my $fn=shift;
1.609     banghart 12663:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12664:     my %bighash;
                   12665:     my $uri=&clutter($fn);
1.620     albertel 12666:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12667: # is this cached?
1.599     albertel 12668:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12669:     if (defined($cached)) { return $result; }
                   12670: # unfortunately not cached, or expired
1.620     albertel 12671:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12672: 	    &GDBM_READER(),0640)) {
                   12673:  	if ($bighash{'version_'.$uri}) {
                   12674:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12675:  	    unless (($version eq 'mostrecent') || 
                   12676: 		    ($version==&getversion($uri))) {
1.440     www      12677:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12678:  	    }
                   12679:  	}
                   12680:  	untie %bighash;
1.413     www      12681:     }
1.599     albertel 12682:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12683: }
                   12684: 
                   12685: sub deversion {
                   12686:     my $url=shift;
                   12687:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12688:     return $url;
1.210     www      12689: }
                   12690: 
1.31      www      12691: # ------------------------------------------------------ Return symb list entry
                   12692: 
                   12693: sub symbread {
1.1282    raeburn  12694:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12695:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12696:     if (defined($env{$cache_str})) {
                   12697:         if ($ignorecachednull) {
                   12698:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12699:         } else {
                   12700:             return $env{$cache_str};
                   12701:         }
                   12702:     }
1.242     www      12703: # no filename provided? try from environment
1.1265    raeburn  12704:     unless ($thisfn) {
1.620     albertel 12705:         if ($env{'request.symb'}) {
                   12706: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12707: 	}
1.620     albertel 12708: 	$thisfn=$env{'request.filename'};
1.44      www      12709:     }
1.569     albertel 12710:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12711: # is that filename actually a symb? Verify, clean, and return
                   12712:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12713: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12714: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12715: 	}
1.242     www      12716:     }
1.44      www      12717:     $thisfn=declutter($thisfn);
1.31      www      12718:     my %hash;
1.37      www      12719:     my %bighash;
                   12720:     my $syval='';
1.620     albertel 12721:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12722:         my $targetfn = $thisfn;
1.609     banghart 12723:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12724:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12725:         }
1.687     albertel 12726: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12727: 	    $targetfn=$1;
                   12728: 	}
1.620     albertel 12729:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12730:                       &GDBM_READER(),0640)) {
1.481     raeburn  12731: 	    $syval=$hash{$targetfn};
1.37      www      12732:             untie(%hash);
                   12733:         }
                   12734: # ---------------------------------------------------------- There was an entry
                   12735:         if ($syval) {
1.601     albertel 12736: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12737: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12738: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12739: 		    #return $env{$cache_str}='';
1.601     albertel 12740: 		#}    
                   12741: 		#$syval.=$1;
                   12742: 	    #}
1.37      www      12743:         } else {
                   12744: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12745:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12746:                             &GDBM_READER(),0640)) {
1.37      www      12747: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12748:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12749:               unless ($ids) { 
                   12750:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12751:               }
                   12752:               unless ($ids) {
                   12753: # alias?
                   12754: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12755:               }
1.37      www      12756:               if ($ids) {
                   12757: # ------------------------------------------------------------------- Has ID(s)
                   12758:                  my @possibilities=split(/\,/,$ids);
1.39      www      12759:                  if ($#possibilities==0) {
                   12760: # ----------------------------------------------- There is only one possibility
1.37      www      12761: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12762: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12763: 						    $resid,$thisfn);
1.1282    raeburn  12764:                      if (ref($possibles) eq 'HASH') {
                   12765:                          $possibles->{$syval} = 1;    
                   12766:                      }
                   12767:                      if ($checkforblock) {
                   12768:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12769:                          if (@blockers) {
                   12770:                              $syval = '';
                   12771:                              return;
                   12772:                          }
                   12773:                      }
                   12774:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12775: # ------------------------------------------ There is more than one possibility
                   12776:                      my $realpossible=0;
1.800     albertel 12777:                      foreach my $id (@possibilities) {
                   12778: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12779:                          my $canaccess;
                   12780:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12781:                              $canaccess = 1;
                   12782:                          } else { 
                   12783:                              $canaccess = &allowed('bre',$file);
                   12784:                          }
                   12785:                          if ($canaccess) {
                   12786:          		     my ($mapid,$resid)=split(/\./,$id);
                   12787:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12788:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12789: 						             $resid,$thisfn);
                   12790:                                  if (ref($possibles) eq 'HASH') {
                   12791:                                      $possibles->{$syval} = 1;
                   12792:                                  }
                   12793:                                  if ($checkforblock) {
                   12794:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12795:                                      unless (@blockers > 0) {
                   12796:                                          $syval = $poss_syval;
                   12797:                                          $realpossible++;
                   12798:                                      }
                   12799:                                  } else {
                   12800:                                      $syval = $poss_syval;
                   12801:                                      $realpossible++;
                   12802:                                  }
                   12803:                              }
1.39      www      12804: 			 }
1.191     harris41 12805:                      }
1.39      www      12806: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12807:                  } else {
                   12808:                      $syval='';
1.37      www      12809:                  }
                   12810: 	      }
1.1282    raeburn  12811:               untie(%bighash);
1.481     raeburn  12812:            }
1.31      www      12813:         }
1.62      www      12814:         if ($syval) {
1.620     albertel 12815: 	    return $env{$cache_str}=$syval;
1.62      www      12816:         }
1.31      www      12817:     }
1.949     raeburn  12818:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12819:     return $env{$cache_str}='';
1.31      www      12820: }
                   12821: 
                   12822: # ---------------------------------------------------------- Return random seed
                   12823: 
1.32      www      12824: sub numval {
                   12825:     my $txt=shift;
                   12826:     $txt=~tr/A-J/0-9/;
                   12827:     $txt=~tr/a-j/0-9/;
                   12828:     $txt=~tr/K-T/0-9/;
                   12829:     $txt=~tr/k-t/0-9/;
                   12830:     $txt=~tr/U-Z/0-5/;
                   12831:     $txt=~tr/u-z/0-5/;
                   12832:     $txt=~s/\D//g;
1.564     albertel 12833:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12834:     return int($txt);
1.368     albertel 12835: }
                   12836: 
1.484     albertel 12837: sub numval2 {
                   12838:     my $txt=shift;
                   12839:     $txt=~tr/A-J/0-9/;
                   12840:     $txt=~tr/a-j/0-9/;
                   12841:     $txt=~tr/K-T/0-9/;
                   12842:     $txt=~tr/k-t/0-9/;
                   12843:     $txt=~tr/U-Z/0-5/;
                   12844:     $txt=~tr/u-z/0-5/;
                   12845:     $txt=~s/\D//g;
                   12846:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12847:     my $total;
                   12848:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12849:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12850:     return int($total);
                   12851: }
                   12852: 
1.575     albertel 12853: sub numval3 {
                   12854:     use integer;
                   12855:     my $txt=shift;
                   12856:     $txt=~tr/A-J/0-9/;
                   12857:     $txt=~tr/a-j/0-9/;
                   12858:     $txt=~tr/K-T/0-9/;
                   12859:     $txt=~tr/k-t/0-9/;
                   12860:     $txt=~tr/U-Z/0-5/;
                   12861:     $txt=~tr/u-z/0-5/;
                   12862:     $txt=~s/\D//g;
                   12863:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12864:     my $total;
                   12865:     foreach my $val (@txts) { $total+=$val; }
                   12866:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12867:     return $total;
                   12868: }
                   12869: 
1.675     albertel 12870: sub digest {
                   12871:     my ($data)=@_;
                   12872:     my $digest=&Digest::MD5::md5($data);
                   12873:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12874:     my ($e,$f);
                   12875:     {
                   12876:         use integer;
                   12877:         $e=($a+$b);
                   12878:         $f=($c+$d);
                   12879:         if ($_64bit) {
                   12880:             $e=(($e<<32)>>32);
                   12881:             $f=(($f<<32)>>32);
                   12882:         }
                   12883:     }
                   12884:     if (wantarray) {
                   12885: 	return ($e,$f);
                   12886:     } else {
                   12887: 	my $g;
                   12888: 	{
                   12889: 	    use integer;
                   12890: 	    $g=($e+$f);
                   12891: 	    if ($_64bit) {
                   12892: 		$g=(($g<<32)>>32);
                   12893: 	    }
                   12894: 	}
                   12895: 	return $g;
                   12896:     }
                   12897: }
                   12898: 
1.368     albertel 12899: sub latest_rnd_algorithm_id {
1.675     albertel 12900:     return '64bit5';
1.366     albertel 12901: }
1.32      www      12902: 
1.503     albertel 12903: sub get_rand_alg {
                   12904:     my ($courseid)=@_;
1.790     albertel 12905:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12906:     if ($courseid) {
1.620     albertel 12907: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12908:     }
                   12909:     return &latest_rnd_algorithm_id();
                   12910: }
                   12911: 
1.562     albertel 12912: sub validCODE {
                   12913:     my ($CODE)=@_;
                   12914:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12915:     return 0;
                   12916: }
                   12917: 
1.491     albertel 12918: sub getCODE {
1.620     albertel 12919:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12920:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12921: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12922: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12923: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12924:     }
                   12925:     return undef;
                   12926: }
1.1133    foxr     12927: #
                   12928: #  Determines the random seed for a specific context:
                   12929: #
                   12930: # parameters:
                   12931: #   symb      - in course context the symb for the seed.
                   12932: #   course_id - The course id of the form domain_coursenum.
                   12933: #   domain    - Domain for the user.
                   12934: #   course    - Course for the user.
                   12935: #   cenv      - environment of the course.
                   12936: #
                   12937: # NOTE:
                   12938: #   All parameters are picked out of the environment if missing
                   12939: #   or not defined.
                   12940: #   If a symb cannot be determined the current time is used instead.
                   12941: #
                   12942: #  For a given well defined symb, courside, domain, username,
                   12943: #  and course environment, the seed is reproducible.
                   12944: #
1.31      www      12945: sub rndseed {
1.1133    foxr     12946:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12947:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12948:     if (!defined($symb)) {
1.366     albertel 12949: 	unless ($symb=$wsymb) { return time; }
                   12950:     }
1.1146    foxr     12951:     if (!defined $courseid) { 
                   12952: 	$courseid=$wcourseid; 
                   12953:     }
                   12954:     if (!defined $domain) { $domain=$wdomain; }
                   12955:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12956: 
                   12957:     my $which;
                   12958:     if (defined($cenv->{'rndseed'})) {
                   12959: 	$which = $cenv->{'rndseed'};
                   12960:     } else {
                   12961: 	$which =&get_rand_alg($courseid);
                   12962:     }
1.491     albertel 12963:     if (defined(&getCODE())) {
1.1133    foxr     12964: 
1.675     albertel 12965: 	if ($which eq '64bit5') {
                   12966: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12967: 	} elsif ($which eq '64bit4') {
1.575     albertel 12968: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12969: 	} else {
                   12970: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12971: 	}
1.675     albertel 12972:     } elsif ($which eq '64bit5') {
                   12973: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12974:     } elsif ($which eq '64bit4') {
                   12975: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12976:     } elsif ($which eq '64bit3') {
                   12977: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12978:     } elsif ($which eq '64bit2') {
                   12979: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12980:     } elsif ($which eq '64bit') {
                   12981: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12982:     }
                   12983:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12984: }
                   12985: 
                   12986: sub rndseed_32bit {
                   12987:     my ($symb,$courseid,$domain,$username)=@_;
                   12988:     {
                   12989: 	use integer;
                   12990: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12991: 	my $symbseed=numval($symb) << 22;
                   12992: 	my $namechck=unpack("%32C*",$username) << 17;
                   12993: 	my $nameseed=numval($username) << 12;
                   12994: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12995: 	my $courseseed=unpack("%32C*",$courseid);
                   12996: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12997: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12998: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12999: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13000: 	return $num;
                   13001:     }
                   13002: }
                   13003: 
                   13004: sub rndseed_64bit {
                   13005:     my ($symb,$courseid,$domain,$username)=@_;
                   13006:     {
                   13007: 	use integer;
                   13008: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13009: 	my $symbseed=numval($symb) << 10;
                   13010: 	my $namechck=unpack("%32S*",$username);
                   13011: 	
                   13012: 	my $nameseed=numval($username) << 21;
                   13013: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13014: 	my $courseseed=unpack("%32S*",$courseid);
                   13015: 	
                   13016: 	my $num1=$symbchck+$symbseed+$namechck;
                   13017: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13018: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13019: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13020: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13021: 	return "$num1,$num2";
1.155     albertel 13022:     }
1.366     albertel 13023: }
                   13024: 
1.443     albertel 13025: sub rndseed_64bit2 {
                   13026:     my ($symb,$courseid,$domain,$username)=@_;
                   13027:     {
                   13028: 	use integer;
                   13029: 	# strings need to be an even # of cahracters long, it it is odd the
                   13030:         # last characters gets thrown away
                   13031: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13032: 	my $symbseed=numval($symb) << 10;
                   13033: 	my $namechck=unpack("%32S*",$username.' ');
                   13034: 	
                   13035: 	my $nameseed=numval($username) << 21;
1.501     albertel 13036: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13037: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13038: 	
                   13039: 	my $num1=$symbchck+$symbseed+$namechck;
                   13040: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13041: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13042: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13043: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13044: 	return "$num1,$num2";
                   13045:     }
                   13046: }
                   13047: 
                   13048: sub rndseed_64bit3 {
                   13049:     my ($symb,$courseid,$domain,$username)=@_;
                   13050:     {
                   13051: 	use integer;
                   13052: 	# strings need to be an even # of cahracters long, it it is odd the
                   13053:         # last characters gets thrown away
                   13054: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13055: 	my $symbseed=numval2($symb) << 10;
                   13056: 	my $namechck=unpack("%32S*",$username.' ');
                   13057: 	
                   13058: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13059: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13060: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13061: 	
                   13062: 	my $num1=$symbchck+$symbseed+$namechck;
                   13063: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13064: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13065: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13066: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13067: 	
1.503     albertel 13068: 	return "$num1:$num2";
1.443     albertel 13069:     }
                   13070: }
                   13071: 
1.575     albertel 13072: sub rndseed_64bit4 {
                   13073:     my ($symb,$courseid,$domain,$username)=@_;
                   13074:     {
                   13075: 	use integer;
                   13076: 	# strings need to be an even # of cahracters long, it it is odd the
                   13077:         # last characters gets thrown away
                   13078: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13079: 	my $symbseed=numval3($symb) << 10;
                   13080: 	my $namechck=unpack("%32S*",$username.' ');
                   13081: 	
                   13082: 	my $nameseed=numval3($username) << 21;
                   13083: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13084: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13085: 	
                   13086: 	my $num1=$symbchck+$symbseed+$namechck;
                   13087: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13088: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13089: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13090: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13091: 	
1.575     albertel 13092: 	return "$num1:$num2";
                   13093:     }
                   13094: }
                   13095: 
1.675     albertel 13096: sub rndseed_64bit5 {
                   13097:     my ($symb,$courseid,$domain,$username)=@_;
                   13098:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13099:     return "$num1:$num2";
                   13100: }
                   13101: 
1.366     albertel 13102: sub rndseed_CODE_64bit {
                   13103:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13104:     {
1.366     albertel 13105: 	use integer;
1.443     albertel 13106: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13107: 	my $symbseed=numval2($symb);
1.491     albertel 13108: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13109: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13110: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13111: 	my $num1=$symbseed+$CODEchck;
                   13112: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13113: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13114: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13115: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13116: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13117: 	return "$num1:$num2";
1.366     albertel 13118:     }
                   13119: }
                   13120: 
1.575     albertel 13121: sub rndseed_CODE_64bit4 {
                   13122:     my ($symb,$courseid,$domain,$username)=@_;
                   13123:     {
                   13124: 	use integer;
                   13125: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13126: 	my $symbseed=numval3($symb);
                   13127: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13128: 	my $CODEseed=numval3(&getCODE());
                   13129: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13130: 	my $num1=$symbseed+$CODEchck;
                   13131: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13132: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13133: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13134: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13135: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13136: 	return "$num1:$num2";
                   13137:     }
                   13138: }
                   13139: 
1.675     albertel 13140: sub rndseed_CODE_64bit5 {
                   13141:     my ($symb,$courseid,$domain,$username)=@_;
                   13142:     my $code = &getCODE();
                   13143:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13144:     return "$num1:$num2";
                   13145: }
                   13146: 
1.366     albertel 13147: sub setup_random_from_rndseed {
                   13148:     my ($rndseed)=@_;
1.503     albertel 13149:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13150:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13151:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13152:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13153:         } else {
                   13154:             &Math::Random::random_set_seed($num1,$num2);
                   13155:         }
1.366     albertel 13156:     } else {
                   13157: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13158:     }
1.36      albertel 13159: }
                   13160: 
1.474     albertel 13161: sub latest_receipt_algorithm_id {
1.835     albertel 13162:     return 'receipt3';
1.474     albertel 13163: }
                   13164: 
1.480     www      13165: sub recunique {
                   13166:     my $fucourseid=shift;
                   13167:     my $unique;
1.835     albertel 13168:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13169: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13170: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13171:     } else {
                   13172: 	$unique=$perlvar{'lonReceipt'};
                   13173:     }
                   13174:     return unpack("%32C*",$unique);
                   13175: }
                   13176: 
                   13177: sub recprefix {
                   13178:     my $fucourseid=shift;
                   13179:     my $prefix;
1.835     albertel 13180:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13181: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13182: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13183:     } else {
                   13184: 	$prefix=$perlvar{'lonHostID'};
                   13185:     }
                   13186:     return unpack("%32C*",$prefix);
                   13187: }
                   13188: 
1.76      www      13189: sub ireceipt {
1.474     albertel 13190:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13191: 
                   13192:     my $return =&recprefix($fucourseid).'-';
                   13193: 
                   13194:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13195: 	$env{'request.state'} eq 'construct') {
                   13196: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13197: 	return $return;
                   13198:     }
                   13199: 
1.76      www      13200:     my $cuname=unpack("%32C*",$funame);
                   13201:     my $cudom=unpack("%32C*",$fudom);
                   13202:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13203:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13204:     my $cunique=&recunique($fucourseid);
1.474     albertel 13205:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13206:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13207: 
1.790     albertel 13208: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13209: 			       
                   13210: 	$return.= ($cunique%$cuname+
                   13211: 		   $cunique%$cudom+
                   13212: 		   $cusymb%$cuname+
                   13213: 		   $cusymb%$cudom+
                   13214: 		   $cucourseid%$cuname+
                   13215: 		   $cucourseid%$cudom+
                   13216: 		   $cpart%$cuname+
                   13217: 		   $cpart%$cudom);
                   13218:     } else {
                   13219: 	$return.= ($cunique%$cuname+
                   13220: 		   $cunique%$cudom+
                   13221: 		   $cusymb%$cuname+
                   13222: 		   $cusymb%$cudom+
                   13223: 		   $cucourseid%$cuname+
                   13224: 		   $cucourseid%$cudom);
                   13225:     }
                   13226:     return $return;
1.76      www      13227: }
                   13228: 
                   13229: sub receipt {
1.474     albertel 13230:     my ($part)=@_;
1.790     albertel 13231:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13232:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13233: }
1.260     ng       13234: 
1.790     albertel 13235: sub whichuser {
                   13236:     my ($passedsymb)=@_;
                   13237:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13238:     if (defined($env{'form.grade_symb'})) {
                   13239: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13240: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13241: 	if (!$allowed &&
                   13242: 	    exists($env{'request.course.sec'}) &&
                   13243: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13244: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13245: 			      '/'.$env{'request.course.sec'});
                   13246: 	}
                   13247: 	if ($allowed) {
                   13248: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13249: 	    $courseid=$tmp_courseid;
                   13250: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13251: 	    ($name)=&get_env_multiple('form.grade_username');
                   13252: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13253: 	}
                   13254:     }
                   13255:     if (!$passedsymb) {
                   13256: 	$symb=&symbread();
                   13257:     } else {
                   13258: 	$symb=$passedsymb;
                   13259:     }
                   13260:     $courseid=$env{'request.course.id'};
                   13261:     $domain=$env{'user.domain'};
                   13262:     $name=$env{'user.name'};
                   13263:     if ($name eq 'public' && $domain eq 'public') {
                   13264: 	if (!defined($env{'form.username'})) {
                   13265: 	    $env{'form.username'}.=time.rand(10000000);
                   13266: 	}
                   13267: 	$name.=$env{'form.username'};
                   13268:     }
                   13269:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13270: 
                   13271: }
                   13272: 
1.36      albertel 13273: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13274: # returns either the contents of the file or 
                   13275: # -1 if the file doesn't exist
1.481     raeburn  13276: #
                   13277: # if the target is a file that was uploaded via DOCS, 
                   13278: # a check will be made to see if a current copy exists on the local server,
                   13279: # if it does this will be served, otherwise a copy will be retrieved from
                   13280: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13281: # the local server.   
1.472     albertel 13282: 
1.36      albertel 13283: sub getfile {
1.538     albertel 13284:     my ($file) = @_;
1.609     banghart 13285:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13286:     &repcopy($file);
                   13287:     return &readfile($file);
                   13288: }
                   13289: 
                   13290: sub repcopy_userfile {
                   13291:     my ($file)=@_;
1.1142    raeburn  13292:     my $londocroot = $perlvar{'lonDocRoot'};
                   13293:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13294:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13295:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13296: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13297:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13298:     if (-e "$file") {
1.828     www      13299: # we already have a local copy, check it out
1.538     albertel 13300: 	my @fileinfo = stat($file);
1.828     www      13301: 	my $rtncode;
                   13302: 	my $info;
1.538     albertel 13303: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13304: 	if ($lwpresp ne 'ok') {
1.828     www      13305: # there is no such file anymore, even though we had a local copy
1.482     albertel 13306: 	    if ($rtncode eq '404') {
1.538     albertel 13307: 		unlink($file);
1.482     albertel 13308: 	    }
                   13309: 	    return -1;
                   13310: 	}
                   13311: 	if ($info < $fileinfo[9]) {
1.828     www      13312: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13313: 	    return 'ok';
1.828     www      13314: 	} else {
                   13315: # the file is outdated, get rid of it
                   13316: 	    unlink($file);
1.482     albertel 13317: 	}
1.828     www      13318:     }
                   13319: # one way or the other, at this point, we don't have the file
                   13320: # construct the correct path for the file
                   13321:     my @parts = ($cdom,$cnum); 
                   13322:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13323: 	push @parts, split(/\//,$1);
                   13324:     }
                   13325:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13326:     foreach my $part (@parts) {
                   13327: 	$path .= '/'.$part;
                   13328: 	if (!-e $path) {
                   13329: 	    mkdir($path,0770);
1.482     albertel 13330: 	}
                   13331:     }
1.828     www      13332: # now the path exists for sure
                   13333: # get a user agent
                   13334:     my $transferfile=$file.'.in.transfer';
                   13335: # FIXME: this should flock
                   13336:     if (-e $transferfile) { return 'ok'; }
                   13337:     my $request;
                   13338:     $uri=~s/^\///;
1.980     raeburn  13339:     my $homeserver = &homeserver($cnum,$cdom);
                   13340:     my $protocol = $protocol{$homeserver};
                   13341:     $protocol = 'http' if ($protocol ne 'https');
                   13342:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13343:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13344: # did it work?
                   13345:     if ($response->is_error()) {
                   13346: 	unlink($transferfile);
                   13347: 	&logthis("Userfile repcopy failed for $uri");
                   13348: 	return -1;
                   13349:     }
                   13350: # worked, rename the transfer file
                   13351:     rename($transferfile,$file);
1.607     raeburn  13352:     return 'ok';
1.481     raeburn  13353: }
                   13354: 
1.517     albertel 13355: sub tokenwrapper {
                   13356:     my $uri=shift;
1.980     raeburn  13357:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13358:     $uri=~s|^/||;
1.620     albertel 13359:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13360:     my $token=$1;
1.552     albertel 13361:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13362:     if ($udom && $uname && $file) {
                   13363: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13364:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13365:         my $homeserver = &homeserver($uname,$udom);
                   13366:         my $protocol = $protocol{$homeserver};
                   13367:         $protocol = 'http' if ($protocol ne 'https');
                   13368:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13369:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13370:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13371:     } else {
                   13372:         return '/adm/notfound.html';
                   13373:     }
                   13374: }
                   13375: 
1.828     www      13376: # call with reqtype HEAD: get last modification time
                   13377: # call with reqtype GET: get the file contents
                   13378: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13379: #
1.481     raeburn  13380: sub getuploaded {
                   13381:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13382:     $uri=~s/^\///;
1.980     raeburn  13383:     my $homeserver = &homeserver($cnum,$cdom);
                   13384:     my $protocol = $protocol{$homeserver};
                   13385:     $protocol = 'http' if ($protocol ne 'https');
                   13386:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13387:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13388:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13389:     $$rtncode = $response->code;
1.482     albertel 13390:     if (! $response->is_success()) {
                   13391: 	return 'failed';
                   13392:     }      
                   13393:     if ($reqtype eq 'HEAD') {
1.486     www      13394: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13395:     } elsif ($reqtype eq 'GET') {
                   13396: 	$$info = $response->content;
1.472     albertel 13397:     }
1.482     albertel 13398:     return 'ok';
1.36      albertel 13399: }
                   13400: 
1.481     raeburn  13401: sub readfile {
                   13402:     my $file = shift;
                   13403:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13404:     my $fh;
1.1359    raeburn  13405:     open($fh,"<",$file);
1.481     raeburn  13406:     my $a='';
1.800     albertel 13407:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13408:     return $a;
                   13409: }
                   13410: 
1.36      albertel 13411: sub filelocation {
1.590     banghart 13412:     my ($dir,$file) = @_;
                   13413:     my $location;
                   13414:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13415: 
                   13416:     if ($file =~ m-^/adm/-) {
                   13417: 	$file=~s-^/adm/wrapper/-/-;
                   13418: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13419:     }
1.882     albertel 13420: 
1.1139    www      13421:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13422:         $location = $file;
1.609     banghart 13423:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13424:         my ($udom,$uname,$filename)=
1.811     albertel 13425:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13426:         my $home=&homeserver($uname,$udom);
                   13427:         my $is_me=0;
                   13428:         my @ids=&current_machine_ids();
                   13429:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13430:         if ($is_me) {
1.1117    foxr     13431:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13432:         } else {
                   13433:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13434:   	      $udom.'/'.$uname.'/'.$filename;
                   13435:         }
1.882     albertel 13436:     } elsif ($file =~ m-^/adm/-) {
                   13437: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13438:     } else {
                   13439:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13440:         $file=~s:^/(res|priv)/:/:;
                   13441:         my $space=$1;
1.590     banghart 13442:         if ( !( $file =~ m:^/:) ) {
                   13443:             $location = $dir. '/'.$file;
                   13444:         } else {
1.1142    raeburn  13445:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13446:         }
1.59      albertel 13447:     }
1.590     banghart 13448:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13449:     while ($location=~m{/\.\./}) {
                   13450: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13451: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13452: 	} else {
                   13453: 	    $location=~ s{/\.\./}{/}g;
                   13454: 	}
                   13455:     } #remove dir/..
1.590     banghart 13456:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13457:     return $location;
1.46      www      13458: }
1.36      albertel 13459: 
1.46      www      13460: sub hreflocation {
                   13461:     my ($dir,$file)=@_;
1.980     raeburn  13462:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13463: 	$file=filelocation($dir,$file);
1.700     albertel 13464:     } elsif ($file=~m-^/adm/-) {
                   13465: 	$file=~s-^/adm/wrapper/-/-;
                   13466: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13467:     }
                   13468:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13469: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13470:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13471: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13472: 	        {/uploaded/$1/$2/}x;
1.46      www      13473:     }
1.913     albertel 13474:     if ($file=~ m{^/userfiles/}) {
                   13475: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13476:     }
1.462     albertel 13477:     return $file;
1.465     albertel 13478: }
                   13479: 
1.1139    www      13480: 
                   13481: 
                   13482: 
                   13483: 
1.465     albertel 13484: sub current_machine_domains {
1.853     albertel 13485:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13486: }
                   13487: 
                   13488: sub machine_domains {
                   13489:     my ($hostname) = @_;
1.465     albertel 13490:     my @domains;
1.838     albertel 13491:     my %hostname = &all_hostnames();
1.465     albertel 13492:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13493: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13494: 	if ($hostname eq $name) {
1.844     albertel 13495: 	    push(@domains,&host_domain($id));
1.465     albertel 13496: 	}
                   13497:     }
                   13498:     return @domains;
                   13499: }
                   13500: 
                   13501: sub current_machine_ids {
1.853     albertel 13502:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13503: }
                   13504: 
                   13505: sub machine_ids {
                   13506:     my ($hostname) = @_;
                   13507:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13508:     my @ids;
1.888     albertel 13509:     my %name_to_host = &all_names();
1.889     albertel 13510:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13511: 	return @{ $name_to_host{$hostname} };
                   13512:     }
                   13513:     return;
1.31      www      13514: }
                   13515: 
1.824     raeburn  13516: sub additional_machine_domains {
                   13517:     my @domains;
1.1359    raeburn  13518:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13519:     while( my $line = <$fh>) {
                   13520:         $line =~ s/\s//g;
                   13521:         push(@domains,$line);
                   13522:     }
                   13523:     return @domains;
                   13524: }
                   13525: 
                   13526: sub default_login_domain {
                   13527:     my $domain = $perlvar{'lonDefDomain'};
                   13528:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13529:     foreach my $posdom (&current_machine_domains(),
                   13530:                         &additional_machine_domains()) {
                   13531:         if (lc($posdom) eq lc($testdomain)) {
                   13532:             $domain=$posdom;
                   13533:             last;
                   13534:         }
                   13535:     }
                   13536:     return $domain;
                   13537: }
                   13538: 
1.31      www      13539: # ------------------------------------------------------------- Declutters URLs
                   13540: 
                   13541: sub declutter {
                   13542:     my $thisfn=shift;
1.569     albertel 13543:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13544:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13545:         $thisfn=~s{^/home/httpd/html}{};
                   13546:     }
1.31      www      13547:     $thisfn=~s/^\///;
1.697     albertel 13548:     $thisfn=~s|^adm/wrapper/||;
                   13549:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13550:     $thisfn=~s/^res\///;
1.1172    bisitz   13551:     $thisfn=~s/^priv\///;
1.1032    raeburn  13552:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13553:         $thisfn=~s/\?.+$//;
                   13554:     }
1.268     www      13555:     return $thisfn;
                   13556: }
                   13557: 
                   13558: # ------------------------------------------------------------- Clutter up URLs
                   13559: 
                   13560: sub clutter {
                   13561:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13562:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13563: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13564:        $thisfn='/res'.$thisfn; 
                   13565:     }
1.1031    raeburn  13566:     if ($thisfn !~m|^/adm|) {
                   13567: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13568: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13569: 	} else {
                   13570: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13571: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13572: 	    if ($embstyle eq 'ssi'
                   13573: 		|| ($embstyle eq 'hdn')
                   13574: 		|| ($embstyle eq 'rat')
                   13575: 		|| ($embstyle eq 'prv')
                   13576: 		|| ($embstyle eq 'ign')) {
                   13577: 		#do nothing with these
                   13578: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13579: 		|| ($embstyle eq 'emb')
                   13580: 		|| ($embstyle eq 'wrp')) {
                   13581: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13582: 	    } elsif ($embstyle eq 'unk'
                   13583: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13584: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13585: 	    } else {
1.718     www      13586: #		&logthis("Got a blank emb style");
1.695     albertel 13587: 	    }
1.694     albertel 13588: 	}
1.1343    raeburn  13589:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13590:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13591:     }
1.31      www      13592:     return $thisfn;
1.12      www      13593: }
                   13594: 
1.787     albertel 13595: sub clutter_with_no_wrapper {
                   13596:     my $uri = &clutter(shift);
                   13597:     if ($uri =~ m-^/adm/-) {
                   13598: 	$uri =~ s-^/adm/wrapper/-/-;
                   13599: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13600:     }
                   13601:     return $uri;
                   13602: }
                   13603: 
1.557     albertel 13604: sub freeze_escape {
                   13605:     my ($value)=@_;
                   13606:     if (ref($value)) {
                   13607: 	$value=&nfreeze($value);
                   13608: 	return '__FROZEN__'.&escape($value);
                   13609:     }
                   13610:     return &escape($value);
                   13611: }
                   13612: 
1.11      www      13613: 
1.557     albertel 13614: sub thaw_unescape {
                   13615:     my ($value)=@_;
                   13616:     if ($value =~ /^__FROZEN__/) {
                   13617: 	substr($value,0,10,undef);
                   13618: 	$value=&unescape($value);
                   13619: 	return &thaw($value);
                   13620:     }
                   13621:     return &unescape($value);
                   13622: }
                   13623: 
1.436     albertel 13624: sub correct_line_ends {
                   13625:     my ($result)=@_;
                   13626:     $$result =~s/\r\n/\n/mg;
                   13627:     $$result =~s/\r/\n/mg;
1.415     albertel 13628: }
1.1       albertel 13629: # ================================================================ Main Program
                   13630: 
1.184     www      13631: sub goodbye {
1.204     albertel 13632:    &logthis("Starting Shut down");
1.443     albertel 13633: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13634:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13635: #converted
1.599     albertel 13636: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13637:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13638: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13639: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13640: #1.1 only
1.870     albertel 13641: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13642: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13643: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13644: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13645:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13646:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13647:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13648:    &flushcourselogs();
                   13649:    &logthis("Shutting down");
                   13650: }
                   13651: 
1.852     albertel 13652: sub get_dns {
1.1210    raeburn  13653:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13654:     if (!$ignore_cache) {
                   13655: 	my ($content,$cached)=
                   13656: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13657: 	if ($cached) {
1.1210    raeburn  13658: 	    &$func($content,$hashref);
1.869     albertel 13659: 	    return;
                   13660: 	}
                   13661:     }
                   13662: 
                   13663:     my %alldns;
1.1379    raeburn  13664:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13665:         foreach my $dns (<$config>) {
                   13666: 	    next if ($dns !~ /^\^(\S*)/x);
                   13667:             my $line = $1;
                   13668:             my ($host,$protocol) = split(/:/,$line);
                   13669:             if ($protocol ne 'https') {
                   13670:                 $protocol = 'http';
                   13671:             }
                   13672: 	    $alldns{$host} = $protocol;
1.979     raeburn  13673:         }
1.1379    raeburn  13674:         close($config);
1.869     albertel 13675:     }
                   13676:     while (%alldns) {
1.1263    raeburn  13677: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13678: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13679:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13680:         delete($alldns{$dns});
1.852     albertel 13681: 	next if ($response->is_error());
1.1379    raeburn  13682:         if ($url eq '/adm/dns/loncapaCRL') {
                   13683:             return &$func($response);
                   13684:         } else {
                   13685: 	    my @content = split("\n",$response->content);
                   13686: 	    unless ($nocache) {
                   13687: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   13688: 	    }
                   13689: 	    &$func(\@content,$hashref);
                   13690:             return;
                   13691:         }
                   13692:     }
                   13693:     my $which = (split('/',$url,4))[3];
                   13694:     if ($which eq 'loncapaCRL') {
                   13695:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   13696:         if (-e $diskfile) {
                   13697:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   13698:         } else {
                   13699:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   13700:         }
                   13701:     } else {
                   13702:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13703:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13704:             my @content = <$config>;
                   13705:             close($config);
                   13706:             &$func(\@content,$hashref);
                   13707:         }
1.852     albertel 13708:     }
1.1210    raeburn  13709:     return;
                   13710: }
                   13711: 
                   13712: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13713: sub parse_dns_checksums_tab {
1.1210    raeburn  13714:     my ($lines,$hashref) = @_;
1.1264    raeburn  13715:     my $lonhost = $perlvar{'lonHostID'};
                   13716:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13717:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13718:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13719:     my $webconfdir = '/etc/httpd/conf';
                   13720:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13721:         $webconfdir = '/etc/apache2';
                   13722:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13723:         if ($1 >= 10) {
                   13724:             $webconfdir = '/etc/apache2';
                   13725:         }
                   13726:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13727:         if ($1 >= 10.0) {
                   13728:             $webconfdir = '/etc/apache2';
                   13729:         }
                   13730:     }
1.1210    raeburn  13731:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13732:     my (%chksum,%revnum);
                   13733:     if (ref($lines) eq 'ARRAY') {
                   13734:         chomp(@{$lines});
1.1238    raeburn  13735:         my $version = shift(@{$lines});
                   13736:         if ($version eq $release) {  
1.1210    raeburn  13737:             foreach my $line (@{$lines}) {
1.1238    raeburn  13738:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13739:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13740:                     if ($webconfdir eq '/etc/apache2') {
                   13741:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13742:                     }
                   13743:                 }
1.1238    raeburn  13744:                 $chksum{$file} = $shasum;
                   13745:                 $revnum{$file} = $version;
1.1210    raeburn  13746:             }
                   13747:             if (ref($hashref) eq 'HASH') {
                   13748:                 %{$hashref} = (
                   13749:                                 sums     => \%chksum,
                   13750:                                 versions => \%revnum,
                   13751:                               );
                   13752:             }
                   13753:         }
                   13754:     }
1.869     albertel 13755:     return;
1.852     albertel 13756: }
1.1210    raeburn  13757: 
                   13758: sub fetch_dns_checksums {
1.1238    raeburn  13759:     my %checksums;
                   13760:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13761:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13762:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13763:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13764:              \%checksums);
1.1210    raeburn  13765:     return \%checksums;
                   13766: }
                   13767: 
1.1379    raeburn  13768: sub fetch_crl_pemfile {
                   13769:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   13770: }
                   13771: 
                   13772: sub save_crl_pem {
                   13773:     my ($response) = @_;
1.1380    raeburn  13774:     my ($msg,$hadchanges);
1.1379    raeburn  13775:     if (ref($response)) {
                   13776:         my $now = time;
                   13777:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   13778:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   13779:         if (open(my $fh,'>',"$tmpcrl")) {
                   13780:             print $fh $response->content;
                   13781:             close($fh);
                   13782:             if (-e $lonca) {
                   13783:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   13784:                     my $check = <PIPE>;
                   13785:                     close(PIPE);
                   13786:                     chomp($check);
                   13787:                     if ($check eq 'verify OK') {
                   13788:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  13789:                         my $backup;
1.1379    raeburn  13790:                         if (-e $dest) {
1.1380    raeburn  13791:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   13792:                                 $backup = 'ok';
                   13793:                             }
1.1379    raeburn  13794:                         }
                   13795:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   13796:                             $msg = 'ok';
1.1380    raeburn  13797:                             if ($backup) {
                   13798:                                 my (%oldnums,%newnums);
                   13799:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   13800:                                     while (<PIPE>) {
                   13801:                                         $oldnums{(split(/:/))[1]} = 1;
                   13802:                                     }
                   13803:                                     close(PIPE);
                   13804:                                 }
                   13805:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   13806:                                     while(<PIPE>) {
                   13807:                                         $newnums{(split(/:/))[1]} = 1;
                   13808:                                     }
                   13809:                                     close(PIPE);
                   13810:                                 }
                   13811:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   13812:                                     unless (exists($oldnums{$key})) {
                   13813:                                         $hadchanges = 1;
                   13814:                                         last;
                   13815:                                     }
                   13816:                                 }
                   13817:                                 unless ($hadchanges) {
                   13818:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   13819:                                         unless (exists($newnums{$key})) {
                   13820:                                             $hadchanges = 1;
                   13821:                                             last;
                   13822:                                         }
                   13823:                                     }
                   13824:                                 }
                   13825:                             }
1.1379    raeburn  13826:                         }
                   13827:                     } else {
                   13828:                         unlink($tmpcrl);
                   13829:                     }
                   13830:                 } else {
                   13831:                     unlink($tmpcrl);
                   13832:                 }
                   13833:             } else {
                   13834:                 unlink($tmpcrl);
                   13835:             }
                   13836:         }
                   13837:     }
1.1380    raeburn  13838:     return ($msg,$hadchanges);
1.1379    raeburn  13839: }
                   13840: 
1.327     albertel 13841: # ------------------------------------------------------------ Read domain file
                   13842: {
1.852     albertel 13843:     my $loaded;
1.846     albertel 13844:     my %domain;
                   13845: 
1.852     albertel 13846:     sub parse_domain_tab {
                   13847: 	my ($lines) = @_;
                   13848: 	foreach my $line (@$lines) {
                   13849: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13850: 
1.846     albertel 13851: 	    chomp($line);
1.852     albertel 13852: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13853: 	    my %this_domain;
                   13854: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13855: 			       'lang_def', 'city', 'longi', 'lati',
                   13856: 			       'primary') {
                   13857: 		$this_domain{$field} = shift(@elements);
                   13858: 	    }
                   13859: 	    $domain{$name} = \%this_domain;
1.852     albertel 13860: 	}
                   13861:     }
1.864     albertel 13862: 
                   13863:     sub reset_domain_info {
                   13864: 	undef($loaded);
                   13865: 	undef(%domain);
                   13866:     }
                   13867: 
1.852     albertel 13868:     sub load_domain_tab {
1.1293    raeburn  13869: 	my ($ignore_cache,$nocache) = @_;
                   13870: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13871: 	my $fh;
1.1359    raeburn  13872: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13873: 	    my @lines = <$fh>;
                   13874: 	    &parse_domain_tab(\@lines);
1.448     albertel 13875: 	}
1.852     albertel 13876: 	close($fh);
                   13877: 	$loaded = 1;
1.327     albertel 13878:     }
1.846     albertel 13879: 
                   13880:     sub domain {
1.852     albertel 13881: 	&load_domain_tab() if (!$loaded);
                   13882: 
1.846     albertel 13883: 	my ($name,$what) = @_;
                   13884: 	return if ( !exists($domain{$name}) );
                   13885: 
                   13886: 	if (!$what) {
                   13887: 	    return $domain{$name}{'description'};
                   13888: 	}
                   13889: 	return $domain{$name}{$what};
                   13890:     }
1.974     raeburn  13891: 
                   13892:     sub domain_info {
                   13893:         &load_domain_tab() if (!$loaded);
                   13894:         return %domain;
                   13895:     }
                   13896: 
1.327     albertel 13897: }
                   13898: 
                   13899: 
1.1       albertel 13900: # ------------------------------------------------------------- Read hosts file
                   13901: {
1.838     albertel 13902:     my %hostname;
1.844     albertel 13903:     my %hostdom;
1.845     albertel 13904:     my %libserv;
1.852     albertel 13905:     my $loaded;
1.888     albertel 13906:     my %name_to_host;
1.1074    raeburn  13907:     my %internetdom;
1.1107    raeburn  13908:     my %LC_dns_serv;
1.852     albertel 13909: 
                   13910:     sub parse_hosts_tab {
                   13911: 	my ($file) = @_;
                   13912: 	foreach my $configline (@$file) {
                   13913: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13914:             chomp($configline);
                   13915: 	    if ($configline =~ /^\^/) {
                   13916:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13917:                     $LC_dns_serv{$1} = 1;
                   13918:                 }
                   13919:                 next;
                   13920:             }
1.1074    raeburn  13921: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13922: 	    $name=~s/\s//g;
                   13923: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13924:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13925:                     my $curr = $hostname{$id};
                   13926:                     my $skip;
                   13927:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13928:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13929:                             $skip = 1;
                   13930:                         } else {
                   13931:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13932:                         }
                   13933:                     }
                   13934:                     unless ($skip) {
                   13935:                         push(@{$name_to_host{$name}},$id);
                   13936:                     }
                   13937:                 } else {
                   13938:                     push(@{$name_to_host{$name}},$id);
                   13939:                 }
1.852     albertel 13940: 		$hostname{$id}=$name;
                   13941: 		$hostdom{$id}=$domain;
                   13942: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13943:                 if (defined($protocol)) {
                   13944:                     if ($protocol eq 'https') {
                   13945:                         $protocol{$id} = $protocol;
                   13946:                     } else {
                   13947:                         $protocol{$id} = 'http'; 
                   13948:                     }
1.968     raeburn  13949:                 } else {
1.969     raeburn  13950:                     $protocol{$id} = 'http';
1.968     raeburn  13951:                 }
1.1074    raeburn  13952:                 if (defined($intdom)) {
                   13953:                     $internetdom{$id} = $intdom;
                   13954:                 }
1.852     albertel 13955: 	    }
                   13956: 	}
                   13957:     }
1.864     albertel 13958:     
                   13959:     sub reset_hosts_info {
1.897     albertel 13960: 	&purge_remembered();
1.864     albertel 13961: 	&reset_domain_info();
                   13962: 	&reset_hosts_ip_info();
1.1339    raeburn  13963:         undef(%internetdom);
1.892     albertel 13964: 	undef(%name_to_host);
1.864     albertel 13965: 	undef(%hostname);
                   13966: 	undef(%hostdom);
                   13967: 	undef(%libserv);
                   13968: 	undef($loaded);
                   13969:     }
1.1       albertel 13970: 
1.852     albertel 13971:     sub load_hosts_tab {
1.1293    raeburn  13972: 	my ($ignore_cache,$nocache) = @_;
                   13973: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13974: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13975: 	my @config = <$config>;
                   13976: 	&parse_hosts_tab(\@config);
                   13977: 	close($config);
                   13978: 	$loaded=1;
1.1       albertel 13979:     }
1.852     albertel 13980: 
1.838     albertel 13981:     sub hostname {
1.852     albertel 13982: 	&load_hosts_tab() if (!$loaded);
                   13983: 
1.838     albertel 13984: 	my ($lonid) = @_;
                   13985: 	return $hostname{$lonid};
                   13986:     }
1.845     albertel 13987: 
1.838     albertel 13988:     sub all_hostnames {
1.852     albertel 13989: 	&load_hosts_tab() if (!$loaded);
                   13990: 
1.838     albertel 13991: 	return %hostname;
                   13992:     }
1.845     albertel 13993: 
1.888     albertel 13994:     sub all_names {
1.1293    raeburn  13995:         my ($ignore_cache,$nocache) = @_;
                   13996: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13997: 
                   13998: 	return %name_to_host;
                   13999:     }
                   14000: 
1.974     raeburn  14001:     sub all_host_domain {
                   14002:         &load_hosts_tab() if (!$loaded);
                   14003:         return %hostdom;
                   14004:     }
                   14005: 
1.1339    raeburn  14006:     sub all_host_intdom {
                   14007:         &load_hosts_tab() if (!$loaded);
                   14008:         return %internetdom;
                   14009:     }
                   14010: 
1.845     albertel 14011:     sub is_library {
1.852     albertel 14012: 	&load_hosts_tab() if (!$loaded);
                   14013: 
1.845     albertel 14014: 	return exists($libserv{$_[0]});
                   14015:     }
                   14016: 
                   14017:     sub all_library {
1.852     albertel 14018: 	&load_hosts_tab() if (!$loaded);
                   14019: 
1.845     albertel 14020: 	return %libserv;
                   14021:     }
                   14022: 
1.1062    droeschl 14023:     sub unique_library {
                   14024: 	#2x reverse removes all hostnames that appear more than once
                   14025:         my %unique = reverse &all_library();
                   14026:         return reverse %unique;
                   14027:     }
                   14028: 
1.841     albertel 14029:     sub get_servers {
1.852     albertel 14030: 	&load_hosts_tab() if (!$loaded);
                   14031: 
1.841     albertel 14032: 	my ($domain,$type) = @_;
                   14033: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14034: 	                                          : %hostname;
                   14035: 	my %result;
1.842     albertel 14036: 	if (ref($domain) eq 'ARRAY') {
                   14037: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14038: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14039: 		    $result{$host} = $hostname;
                   14040: 		}
                   14041: 	    }
                   14042: 	} else {
                   14043: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14044: 		if ($hostdom{$host} eq $domain) {
                   14045: 		    $result{$host} = $hostname;
                   14046: 		}
1.841     albertel 14047: 	    }
                   14048: 	}
                   14049: 	return %result;
                   14050:     }
1.845     albertel 14051: 
1.1062    droeschl 14052:     sub get_unique_servers {
                   14053:         my %unique = reverse &get_servers(@_);
                   14054: 	return reverse %unique;
                   14055:     }
                   14056: 
1.844     albertel 14057:     sub host_domain {
1.852     albertel 14058: 	&load_hosts_tab() if (!$loaded);
                   14059: 
1.844     albertel 14060: 	my ($lonid) = @_;
                   14061: 	return $hostdom{$lonid};
                   14062:     }
                   14063: 
1.841     albertel 14064:     sub all_domains {
1.852     albertel 14065: 	&load_hosts_tab() if (!$loaded);
                   14066: 
1.841     albertel 14067: 	my %seen;
                   14068: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14069: 	return @uniq;
                   14070:     }
1.1074    raeburn  14071: 
                   14072:     sub internet_dom {
                   14073:         &load_hosts_tab() if (!$loaded);
                   14074: 
                   14075:         my ($lonid) = @_;
                   14076:         return $internetdom{$lonid};
                   14077:     }
1.1107    raeburn  14078: 
                   14079:     sub is_LC_dns {
                   14080:         &load_hosts_tab() if (!$loaded);
                   14081: 
                   14082:         my ($hostname) = @_;
                   14083:         return exists($LC_dns_serv{$hostname});
                   14084:     }
                   14085: 
1.1       albertel 14086: }
                   14087: 
1.847     albertel 14088: { 
                   14089:     my %iphost;
1.856     albertel 14090:     my %name_to_ip;
                   14091:     my %lonid_to_ip;
1.869     albertel 14092: 
1.847     albertel 14093:     sub get_hosts_from_ip {
                   14094: 	my ($ip) = @_;
                   14095: 	my %iphosts = &get_iphost();
                   14096: 	if (ref($iphosts{$ip})) {
                   14097: 	    return @{$iphosts{$ip}};
                   14098: 	}
                   14099: 	return;
1.839     albertel 14100:     }
1.864     albertel 14101:     
                   14102:     sub reset_hosts_ip_info {
                   14103: 	undef(%iphost);
                   14104: 	undef(%name_to_ip);
                   14105: 	undef(%lonid_to_ip);
                   14106:     }
1.856     albertel 14107: 
                   14108:     sub get_host_ip {
                   14109: 	my ($lonid) = @_;
                   14110: 	if (exists($lonid_to_ip{$lonid})) {
                   14111: 	    return $lonid_to_ip{$lonid};
                   14112: 	}
                   14113: 	my $name=&hostname($lonid);
                   14114:    	my $ip = gethostbyname($name);
                   14115: 	return if (!$ip || length($ip) ne 4);
                   14116: 	$ip=inet_ntoa($ip);
                   14117: 	$name_to_ip{$name}   = $ip;
                   14118: 	$lonid_to_ip{$lonid} = $ip;
                   14119: 	return $ip;
                   14120:     }
1.847     albertel 14121:     
                   14122:     sub get_iphost {
1.1293    raeburn  14123: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14124: 
1.869     albertel 14125: 	if (!$ignore_cache) {
                   14126: 	    if (%iphost) {
                   14127: 		return %iphost;
                   14128: 	    }
                   14129: 	    my ($ip_info,$cached)=
                   14130: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14131: 	    if ($cached) {
                   14132: 		%iphost      = %{$ip_info->[0]};
                   14133: 		%name_to_ip  = %{$ip_info->[1]};
                   14134: 		%lonid_to_ip = %{$ip_info->[2]};
                   14135: 		return %iphost;
                   14136: 	    }
                   14137: 	}
1.894     albertel 14138: 
                   14139: 	# get yesterday's info for fallback
                   14140: 	my %old_name_to_ip;
                   14141: 	my ($ip_info,$cached)=
                   14142: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14143: 	if ($cached) {
                   14144: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14145: 	}
                   14146: 
1.1293    raeburn  14147: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14148: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14149: 	    my $ip;
                   14150: 	    if (!exists($name_to_ip{$name})) {
                   14151: 		$ip = gethostbyname($name);
                   14152: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14153: 		    if (defined($old_name_to_ip{$name})) {
                   14154: 			$ip = $old_name_to_ip{$name};
                   14155: 			&logthis("Can't find $name defaulting to old $ip");
                   14156: 		    } else {
                   14157: 			&logthis("Name $name no IP found");
                   14158: 			next;
                   14159: 		    }
                   14160: 		} else {
                   14161: 		    $ip=inet_ntoa($ip);
1.847     albertel 14162: 		}
                   14163: 		$name_to_ip{$name} = $ip;
                   14164: 	    } else {
                   14165: 		$ip = $name_to_ip{$name};
1.653     albertel 14166: 	    }
1.888     albertel 14167: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14168: 		$lonid_to_ip{$id} = $ip;
                   14169: 	    }
                   14170: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14171: 	}
1.1293    raeburn  14172:         unless ($nocache) {
                   14173: 	    &do_cache_new('iphost','iphost',
                   14174: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14175: 		          48*60*60);
                   14176:         }
1.869     albertel 14177: 
1.847     albertel 14178: 	return %iphost;
1.598     albertel 14179:     }
                   14180: 
1.992     raeburn  14181:     #
                   14182:     #  Given a DNS returns the loncapa host name for that DNS 
                   14183:     # 
                   14184:     sub host_from_dns {
                   14185:         my ($dns) = @_;
                   14186:         my @hosts;
                   14187:         my $ip;
                   14188: 
1.993     raeburn  14189:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14190:             $ip = $name_to_ip{$dns};
                   14191:         }
                   14192:         if (!$ip) {
                   14193:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14194:             if (length($ip) == 4) { 
                   14195: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14196:             }
                   14197:         }
                   14198:         if ($ip) {
                   14199: 	    @hosts = get_hosts_from_ip($ip);
                   14200: 	    return $hosts[0];
                   14201:         }
                   14202:         return undef;
1.986     foxr     14203:     }
1.992     raeburn  14204: 
1.1074    raeburn  14205:     sub get_internet_names {
                   14206:         my ($lonid) = @_;
                   14207:         return if ($lonid eq '');
                   14208:         my ($idnref,$cached)=
                   14209:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14210:         if ($cached) {
                   14211:             return $idnref;
                   14212:         }
                   14213:         my $ip = &get_host_ip($lonid);
                   14214:         my @hosts = &get_hosts_from_ip($ip);
                   14215:         my %iphost = &get_iphost();
                   14216:         my (@idns,%seen);
                   14217:         foreach my $id (@hosts) {
                   14218:             my $dom = &host_domain($id);
                   14219:             my $prim_id = &domain($dom,'primary');
                   14220:             my $prim_ip = &get_host_ip($prim_id);
                   14221:             next if ($seen{$prim_ip});
                   14222:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14223:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14224:                     my $intdom = &internet_dom($id);
                   14225:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14226:                         push(@idns,$intdom);
                   14227:                     }
                   14228:                 }
                   14229:             }
                   14230:             $seen{$prim_ip} = 1;
                   14231:         }
1.1219    raeburn  14232:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14233:     }
                   14234: 
1.986     foxr     14235: }
                   14236: 
1.1079    raeburn  14237: sub all_loncaparevs {
1.1249    raeburn  14238:     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  14239: }
                   14240: 
1.1227    raeburn  14241: # ---------------------------------------------------------- Read loncaparev table
                   14242: {
                   14243:     sub load_loncaparevs { 
                   14244:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14245:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14246:                 while (my $configline=<$config>) {
                   14247:                     chomp($configline);
                   14248:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14249:                     $loncaparevs{$hostid}=$loncaparev;
                   14250:                 }
                   14251:                 close($config);
                   14252:             }
                   14253:         }
                   14254:     }
                   14255: }
                   14256: 
                   14257: # ---------------------------------------------------------- Read serverhostID table
                   14258: {
                   14259:     sub load_serverhomeIDs {
                   14260:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14261:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14262:                 while (my $configline=<$config>) {
                   14263:                     chomp($configline);
                   14264:                     my ($name,$id)=split(/:/,$configline);
                   14265:                     $serverhomeIDs{$name}=$id;
                   14266:                 }
                   14267:                 close($config);
                   14268:             }
                   14269:         }
                   14270:     }
                   14271: }
                   14272: 
                   14273: 
1.862     albertel 14274: BEGIN {
                   14275: 
                   14276: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14277:     unless ($readit) {
                   14278: {
                   14279:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14280:     %perlvar = (%perlvar,%{$configvars});
                   14281: }
                   14282: 
                   14283: 
1.1       albertel 14284: # ------------------------------------------------------ Read spare server file
                   14285: {
1.1359    raeburn  14286:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14287: 
                   14288:     while (my $configline=<$config>) {
                   14289:        chomp($configline);
1.284     matthew  14290:        if ($configline) {
1.784     albertel 14291: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14292: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14293: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14294:        }
                   14295:     }
1.448     albertel 14296:     close($config);
1.1       albertel 14297: }
1.11      www      14298: # ------------------------------------------------------------ Read permissions
                   14299: {
1.1359    raeburn  14300:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14301: 
                   14302:     while (my $configline=<$config>) {
1.448     albertel 14303: 	chomp($configline);
                   14304: 	if ($configline) {
                   14305: 	    my ($role,$perm)=split(/ /,$configline);
                   14306: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14307: 	}
1.11      www      14308:     }
1.448     albertel 14309:     close($config);
1.11      www      14310: }
                   14311: 
                   14312: # -------------------------------------------- Read plain texts for permissions
                   14313: {
1.1359    raeburn  14314:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14315: 
                   14316:     while (my $configline=<$config>) {
1.448     albertel 14317: 	chomp($configline);
                   14318: 	if ($configline) {
1.742     raeburn  14319: 	    my ($short,@plain)=split(/:/,$configline);
                   14320:             %{$prp{$short}} = ();
                   14321: 	    if (@plain > 0) {
                   14322:                 $prp{$short}{'std'} = $plain[0];
                   14323:                 for (my $i=1; $i<@plain; $i++) {
                   14324:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14325:                 }
                   14326:             }
1.448     albertel 14327: 	}
1.135     www      14328:     }
1.448     albertel 14329:     close($config);
1.135     www      14330: }
                   14331: 
                   14332: # ---------------------------------------------------------- Read package table
                   14333: {
1.1359    raeburn  14334:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14335: 
                   14336:     while (my $configline=<$config>) {
1.483     albertel 14337: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14338: 	chomp($configline);
                   14339: 	my ($short,$plain)=split(/:/,$configline);
                   14340: 	my ($pack,$name)=split(/\&/,$short);
                   14341: 	if ($plain ne '') {
                   14342: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14343: 	    $packagetab{$short}=$plain; 
                   14344: 	}
1.11      www      14345:     }
1.448     albertel 14346:     close($config);
1.329     matthew  14347: }
                   14348: 
1.1073    raeburn  14349: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14350: 
                   14351: &load_loncaparevs();
1.1073    raeburn  14352: 
1.1074    raeburn  14353: # ---------------------------------------------------------- Read serverhostID table
                   14354: 
1.1227    raeburn  14355: &load_serverhomeIDs();
                   14356: 
                   14357: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14358: {
                   14359:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14360:     if (-e $file) {
                   14361:         my $parser = HTML::LCParser->new($file);
                   14362:         while (my $token = $parser->get_token()) {
                   14363:             if ($token->[0] eq 'S') {
                   14364:                 my $item = $token->[1];
                   14365:                 my $name = $token->[2]{'name'};
                   14366:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14367:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14368:                 my $namematch = $token->[2]{'namematch'};
                   14369:                 if ($item eq 'parameter') {
                   14370:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14371:                         my $release = $parser->get_text();
                   14372:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14373:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14374:                     }
                   14375:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14376:                     my $release = $parser->get_text();
                   14377:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14378:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14379:                 }
                   14380:             }
                   14381:         }
                   14382:     }
1.1073    raeburn  14383: }
                   14384: 
1.1138    raeburn  14385: # ---------------------------------------------------------- Read managers table
                   14386: {
                   14387:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14388:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14389:             while (my $configline=<$config>) {
                   14390:                 chomp($configline);
                   14391:                 next if ($configline =~ /^\#/);
                   14392:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14393:                     $managerstab{$configline} = 1;
                   14394:                 }
                   14395:             }
                   14396:             close($config);
                   14397:         }
                   14398:     }
                   14399: }
                   14400: 
1.329     matthew  14401: # ------------- set up temporary directory
                   14402: {
1.1117    foxr     14403:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14404: 
1.11      www      14405: }
                   14406: 
1.794     albertel 14407: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14408: 				'compress_threshold'=> 20_000,
                   14409:  			        });
1.185     www      14410: 
1.281     www      14411: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14412: $dumpcount=0;
1.958     www      14413: $locknum=0;
1.22      www      14414: 
1.163     harris41 14415: &logtouch();
1.672     albertel 14416: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14417: $readit=1;
1.564     albertel 14418:     {
                   14419: 	use integer;
                   14420: 	my $test=(2**32)+1;
1.568     albertel 14421: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14422: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14423:     }
1.195     www      14424: }
1.1       albertel 14425: }
1.179     www      14426: 
1.1       albertel 14427: 1;
1.191     harris41 14428: __END__
                   14429: 
1.243     albertel 14430: =pod
                   14431: 
1.191     harris41 14432: =head1 NAME
                   14433: 
1.243     albertel 14434: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14435: 
                   14436: =head1 SYNOPSIS
                   14437: 
1.243     albertel 14438: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14439: 
                   14440:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14441: 
1.243     albertel 14442: Common parameters:
                   14443: 
                   14444: =over 4
                   14445: 
                   14446: =item *
                   14447: 
                   14448: $uname : an internal username (if $cname expecting a course Id specifically)
                   14449: 
                   14450: =item *
                   14451: 
                   14452: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14453: 
                   14454: =item *
                   14455: 
                   14456: $symb : a resource instance identifier
                   14457: 
                   14458: =item *
                   14459: 
                   14460: $namespace : the name of a .db file that contains the data needed or
                   14461: being set.
                   14462: 
                   14463: =back
                   14464: 
1.394     bowersj2 14465: =head1 OVERVIEW
1.191     harris41 14466: 
1.394     bowersj2 14467: lonnet provides subroutines which interact with the
                   14468: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14469: about classes, users, and resources.
1.243     albertel 14470: 
                   14471: For many of these objects you can also use this to store data about
                   14472: them or modify them in various ways.
1.191     harris41 14473: 
1.394     bowersj2 14474: =head2 Symbs
1.191     harris41 14475: 
1.394     bowersj2 14476: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14477: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14478: map, the resource number of the resource in the map, and the URL of
                   14479: the resource itself. The latter is somewhat redundant, but might help
                   14480: if maps change.
                   14481: 
                   14482: An example is
                   14483: 
                   14484:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14485: 
                   14486: The respective map entry is
                   14487: 
                   14488:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14489:   title="Problem 2">
                   14490:  </resource>
                   14491: 
                   14492: Symbs are used by the random number generator, as well as to store and
                   14493: restore data specific to a certain instance of for example a problem.
                   14494: 
                   14495: =head2 Storing And Retrieving Data
                   14496: 
                   14497: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14498: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14499: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14500: is is the non-critical message twin of cstore. These functions are for
                   14501: handlers to store a perl hash to a user's permanent data space in an
                   14502: easy manner, and to retrieve it again on another call. It is expected
                   14503: that a handler would use this once at the beginning to retrieve data,
                   14504: and then again once at the end to send only the new data back.
                   14505: 
                   14506: The data is stored in the user's data directory on the user's
                   14507: homeserver under the ID of the course.
                   14508: 
                   14509: The hash that is returned by restore will have all of the previous
                   14510: value for all of the elements of the hash.
                   14511: 
                   14512: Example:
                   14513: 
                   14514:  #creating a hash
                   14515:  my %hash;
                   14516:  $hash{'foo'}='bar';
                   14517: 
                   14518:  #storing it
                   14519:  &Apache::lonnet::cstore(\%hash);
                   14520: 
                   14521:  #changing a value
                   14522:  $hash{'foo'}='notbar';
                   14523: 
                   14524:  #adding a new value
                   14525:  $hash{'bar'}='foo';
                   14526:  &Apache::lonnet::cstore(\%hash);
                   14527: 
                   14528:  #retrieving the hash
                   14529:  my %history=&Apache::lonnet::restore();
                   14530: 
                   14531:  #print the hash
                   14532:  foreach my $key (sort(keys(%history))) {
                   14533:    print("\%history{$key} = $history{$key}");
                   14534:  }
                   14535: 
                   14536: Will print out:
1.191     harris41 14537: 
1.394     bowersj2 14538:  %history{1:foo} = bar
                   14539:  %history{1:keys} = foo:timestamp
                   14540:  %history{1:timestamp} = 990455579
                   14541:  %history{2:bar} = foo
                   14542:  %history{2:foo} = notbar
                   14543:  %history{2:keys} = foo:bar:timestamp
                   14544:  %history{2:timestamp} = 990455580
                   14545:  %history{bar} = foo
                   14546:  %history{foo} = notbar
                   14547:  %history{timestamp} = 990455580
                   14548:  %history{version} = 2
                   14549: 
                   14550: Note that the special hash entries C<keys>, C<version> and
                   14551: C<timestamp> were added to the hash. C<version> will be equal to the
                   14552: total number of versions of the data that have been stored. The
                   14553: C<timestamp> attribute will be the UNIX time the hash was
                   14554: stored. C<keys> is available in every historical section to list which
                   14555: keys were added or changed at a specific historical revision of a
                   14556: hash.
                   14557: 
                   14558: B<Warning>: do not store the hash that restore returns directly. This
                   14559: will cause a mess since it will restore the historical keys as if the
                   14560: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14561: 
1.394     bowersj2 14562: Calling convention:
1.191     harris41 14563: 
1.1225    raeburn  14564:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14565:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14566: 
1.394     bowersj2 14567: For more detailed information, see lonnet specific documentation.
1.191     harris41 14568: 
1.394     bowersj2 14569: =head1 RETURN MESSAGES
1.191     harris41 14570: 
1.394     bowersj2 14571: =over 4
1.191     harris41 14572: 
1.394     bowersj2 14573: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14574: 
1.394     bowersj2 14575: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14576: when the connection is brought back up
1.191     harris41 14577: 
1.394     bowersj2 14578: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14579: for later delivery
1.191     harris41 14580: 
1.967     bisitz   14581: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14582: 
1.394     bowersj2 14583: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14584: that was requested
1.191     harris41 14585: 
1.243     albertel 14586: =back
1.191     harris41 14587: 
1.243     albertel 14588: =head1 PUBLIC SUBROUTINES
1.191     harris41 14589: 
1.243     albertel 14590: =head2 Session Environment Functions
1.191     harris41 14591: 
1.243     albertel 14592: =over 4
1.191     harris41 14593: 
1.394     bowersj2 14594: =item * 
                   14595: X<appenv()>
1.949     raeburn  14596: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14597: the user envirnoment file, and will be restored for each access this
1.620     albertel 14598: user makes during this session, also modifies the %env for the current
1.949     raeburn  14599: process. Optional rolesarrayref - if defined contains a reference to an array
                   14600: of roles which are exempt from the restriction on modifying user.role entries 
                   14601: in the user's environment.db and in %env.    
1.191     harris41 14602: 
                   14603: =item *
1.394     bowersj2 14604: X<delenv()>
1.987     raeburn  14605: B<delenv($delthis,$regexp)>: removes all items from the session
                   14606: environment file that begin with $delthis. If the 
                   14607: optional second arg - $regexp - is true, $delthis is treated as a 
                   14608: regular expression, otherwise \Q$delthis\E is used. 
                   14609: The values are also deleted from the current processes %env.
1.191     harris41 14610: 
1.795     albertel 14611: =item * get_env_multiple($name) 
                   14612: 
                   14613: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14614: values may be defined and end up as an array ref.
                   14615: 
                   14616: returns an array of values
                   14617: 
1.243     albertel 14618: =back
                   14619: 
                   14620: =head2 User Information
1.191     harris41 14621: 
1.243     albertel 14622: =over 4
1.191     harris41 14623: 
                   14624: =item *
1.394     bowersj2 14625: X<queryauthenticate()>
                   14626: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14627: authentication scheme
                   14628: 
                   14629: =item *
1.394     bowersj2 14630: X<authenticate()>
1.1073    raeburn  14631: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14632: authenticate user from domain's lib servers (first use the current
                   14633: one). C<$upass> should be the users password.
1.1073    raeburn  14634: $checkdefauth is optional (value is 1 if a check should be made to
                   14635:    authenticate user using default authentication method, and allow
                   14636:    account creation if username does not have account in the domain).
                   14637: $clientcancheckhost is optional (value is 1 if checking whether the
                   14638:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14639: 
                   14640: =item *
1.394     bowersj2 14641: X<homeserver()>
                   14642: B<homeserver($uname,$udom)>: find the server which has
                   14643: the user's directory and files (there must be only one), this caches
                   14644: the answer, and also caches if there is a borken connection.
1.191     harris41 14645: 
                   14646: =item *
1.394     bowersj2 14647: X<idget()>
1.1300    raeburn  14648: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14649: a list of student/employee IDs or clicker IDs
                   14650: (student/employee IDs are a unique resource in a domain, there must be 
                   14651: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14652: clickerIDs are not necessarily unique, as students might share clickers.
                   14653: (returns hash: id=>name,id=>name)
1.191     harris41 14654: 
                   14655: =item *
1.394     bowersj2 14656: X<idrget()>
                   14657: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14658: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14659: 
                   14660: =item *
1.394     bowersj2 14661: X<idput()>
1.1300    raeburn  14662: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14663: names and associated student/employee IDs or clicker IDs.
                   14664: 
                   14665: =item *
                   14666: X<iddel()>
                   14667: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14668: student/employee ID or clicker ID username look-ups from domain.
                   14669: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14670: If no $uhome is provided, it will be determined usig &homeserver()
                   14671: for each user.  If no $namespace is provided, the default is ids.
                   14672: 
                   14673: =item *
                   14674: X<updateclickers()>
                   14675: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14676: clicker ID-to-username look-ups in clickers.db on library server.
                   14677: Permitted actions are add or del (i.e., add or delete). The 
                   14678: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14679: value is an escaped comma-separated list of usernames (for whom the
                   14680: library server is the homeserver), who registered that particular ID.
                   14681: If $critical is true, the update will be sent via &critical, otherwise
                   14682: &reply() will be used.
1.191     harris41 14683: 
                   14684: =item *
1.394     bowersj2 14685: X<rolesinit()>
1.1169    droeschl 14686: B<rolesinit($udom,$username)>: get user privileges.
                   14687: returns user role, first access and timer interval hashes
1.243     albertel 14688: 
                   14689: =item *
1.1171    droeschl 14690: X<privileged()>
                   14691: B<privileged($username,$domain)>: returns a true if user has a
                   14692: privileged and active role (i.e. su or dc), false otherwise.
                   14693: 
                   14694: =item *
1.551     albertel 14695: X<getsection()>
                   14696: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14697: course $cname, return section name/number or '' for "not in course"
                   14698: and '-1' for "no section"
                   14699: 
                   14700: =item *
1.394     bowersj2 14701: X<userenvironment()>
                   14702: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14703: passed in @what from the requested user's environment, returns a hash
                   14704: 
1.858     raeburn  14705: =item * 
                   14706: X<userlog_query()>
1.859     albertel 14707: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14708: activity.log file. %filters defines filters applied when parsing the
                   14709: log file. These can be start or end timestamps, or the type of action
                   14710: - log to look for Login or Logout events, check for Checkin or
                   14711: Checkout, role for role selection. The response is in the form
                   14712: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14713: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14714: 
1.243     albertel 14715: =back
                   14716: 
                   14717: =head2 User Roles
                   14718: 
                   14719: =over 4
                   14720: 
                   14721: =item *
                   14722: 
1.1284    raeburn  14723: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14724: returns codes for allowed actions.
                   14725: 
                   14726: The first argument is required, all others are optional.
                   14727: 
                   14728: $priv is the privilege being checked.
                   14729: $uri contains additional information about what is being checked for access (e.g.,
                   14730: URL, course ID etc.). 
                   14731: $symb is the unique resource instance identifier in a course; if needed,
                   14732: but not provided, it will be retrieved via a call to &symbread(). 
                   14733: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14734: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14735: files).
                   14736: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14737: prevents recursive calls to &allowed.
                   14738: 
1.243     albertel 14739:  F: full access
                   14740:  U,I,K: authentication modes (cxx only)
                   14741:  '': forbidden
                   14742:  1: user needs to choose course
                   14743:  2: browse allowed
1.766     albertel 14744:  A: passphrase authentication needed
1.1284    raeburn  14745:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14746: 
                   14747: =item *
                   14748: 
1.1192    raeburn  14749: constructaccess($url,$setpriv) : check for access to construction space URL
                   14750: 
                   14751: See if the owner domain and name in the URL match those in the
                   14752: expected environment.  If so, return three element list
                   14753: ($ownername,$ownerdomain,$ownerhome).
                   14754: 
                   14755: Otherwise return the null string.
                   14756: 
                   14757: If second argument 'setpriv' is true, it assigns the privileges,
                   14758: and returns the same three element list, unless the owner has
                   14759: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14760: in which case the null string is returned.
                   14761: 
                   14762: =item *
                   14763: 
1.1326    raeburn  14764: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14765: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14766: for system, domain, and course level. $uname and $udom are optional (current
                   14767: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14768: 
                   14769: =item *
                   14770: 
1.988     raeburn  14771: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14772: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14773: $type is Course (default) or Community.
1.988     raeburn  14774: If $forcedefault evaluates to true, text returned will be default 
                   14775: text for $type. Otherwise, if this is a course, the text returned 
                   14776: will be a custom name for the role (if defined in the course's 
                   14777: environment).  If no custom name is defined the default is returned.
                   14778:    
1.832     raeburn  14779: =item *
                   14780: 
1.1219    raeburn  14781: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14782: All arguments are optional. Returns a hash of a roles, either for
                   14783: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14784: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14785: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14786: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14787: For each key, value is set to colon-separated start and end times for
                   14788: the role.  If no username and domain are specified, will default to
1.934     raeburn  14789: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14790: of role statuses (active, future or previous), roles 
                   14791: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14792: to restrict the list of roles reported. If no array ref is 
                   14793: provided for types, will default to return only active roles.
1.834     albertel 14794: 
1.1195    raeburn  14795: =item *
                   14796: 
                   14797: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14798: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14799: 
                   14800: Additional optional arguments are: $type (if role checking is to be restricted 
                   14801: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14802: available roles) or future (roles available in the future), and
                   14803: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14804: have active Domain Coordinator role in course's domain or in additional
                   14805: domains (specified in 'Domains to check for privileged users' in course
                   14806: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14807: 
                   14808: =item *
                   14809: 
                   14810: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14811: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14812: $possdomains and $possroles are optional array refs -- to domains to check and
                   14813: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14814: users' roles.db to check for a dc or su role in any domain. This can be
                   14815: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14816: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14817: this then allows &privileged_by_domain() to be used, which caches the identity
                   14818: of privileged users, eliminating the need for repeated calls to &dump().
                   14819: 
                   14820: =item *
                   14821: 
                   14822: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14823: where the outer hash keys are domains specified in the $possdomains array ref,
                   14824: next inner hash keys are privileged roles specified in the $roles array ref,
                   14825: and the innermost hash contains key = value pairs for username:domain = end:start
                   14826: for active or future "privileged" users with that role in that domain. To avoid
                   14827: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14828: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14829: 
1.243     albertel 14830: =back
                   14831: 
                   14832: =head2 User Modification
                   14833: 
                   14834: =over 4
                   14835: 
                   14836: =item *
                   14837: 
1.957     raeburn  14838: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14839: user for the level given by URL.  Optional start and end dates (leave empty
                   14840: string or zero for "no date")
1.191     harris41 14841: 
                   14842: =item *
                   14843: 
1.243     albertel 14844: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14845: change a users, password, possible return values are: ok,
                   14846: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14847: refused
1.191     harris41 14848: 
                   14849: =item *
                   14850: 
1.243     albertel 14851: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14852: 
                   14853: =item *
                   14854: 
1.1058    raeburn  14855: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14856:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14857: 
                   14858: will update user information (firstname,middlename,lastname,generation,
                   14859: permanentemail), and if forceid is true, student/employee ID also.
                   14860: A user's institutional affiliation(s) can also be updated.
                   14861: User information fields will not be overwritten with empty entries 
                   14862: unless the field is included in the $candelete array reference.
                   14863: This array is included when a single user is modified via "Manage Users",
                   14864: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14865: 
                   14866: =item *
                   14867: 
1.286     matthew  14868: modifystudent
                   14869: 
1.957     raeburn  14870: modify a student's enrollment and identification information.
1.1235    raeburn  14871: The course id is resolved based on the current user's environment.  
                   14872: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14873: associated with a course.
                   14874: 
1.297     matthew  14875: This call is essentially a wrapper for lonnet::modifyuser and
                   14876: lonnet::modify_student_enrollment
1.286     matthew  14877: 
                   14878: Inputs: 
                   14879: 
                   14880: =over 4
                   14881: 
1.957     raeburn  14882: =item B<$udom> Student's loncapa domain
1.286     matthew  14883: 
1.957     raeburn  14884: =item B<$uname> Student's loncapa login name
1.286     matthew  14885: 
1.964     bisitz   14886: =item B<$uid> Student/Employee ID
1.286     matthew  14887: 
1.957     raeburn  14888: =item B<$umode> Student's authentication mode
1.286     matthew  14889: 
1.957     raeburn  14890: =item B<$upass> Student's password
1.286     matthew  14891: 
1.957     raeburn  14892: =item B<$first> Student's first name
1.286     matthew  14893: 
1.957     raeburn  14894: =item B<$middle> Student's middle name
1.286     matthew  14895: 
1.957     raeburn  14896: =item B<$last> Student's last name
1.286     matthew  14897: 
1.957     raeburn  14898: =item B<$gene> Student's generation
1.286     matthew  14899: 
1.957     raeburn  14900: =item B<$usec> Student's section in course
1.286     matthew  14901: 
                   14902: =item B<$end> Unix time of the roles expiration
                   14903: 
                   14904: =item B<$start> Unix time of the roles start date
                   14905: 
                   14906: =item B<$forceid> If defined, allow $uid to be changed
                   14907: 
                   14908: =item B<$desiredhome> server to use as home server for student
                   14909: 
1.957     raeburn  14910: =item B<$email> Student's permanent e-mail address
                   14911: 
                   14912: =item B<$type> Type of enrollment (auto or manual)
                   14913: 
1.963     raeburn  14914: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14915: 
                   14916: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14917: 
1.963     raeburn  14918: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14919: 
1.963     raeburn  14920: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14921: 
1.1216    raeburn  14922: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14923: 
                   14924: =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  14925: 
1.286     matthew  14926: =back
1.297     matthew  14927: 
                   14928: =item *
                   14929: 
                   14930: modify_student_enrollment
                   14931: 
1.1235    raeburn  14932: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14933: 'role.request.course' must be defined for this function to proceed.
                   14934: 
                   14935: Inputs:
                   14936: 
                   14937: =over 4
                   14938: 
1.1235    raeburn  14939: =item $udom, student's domain
1.297     matthew  14940: 
1.1235    raeburn  14941: =item $uname, student's name
1.297     matthew  14942: 
1.1235    raeburn  14943: =item $uid, student's user id
1.297     matthew  14944: 
1.1235    raeburn  14945: =item $first, student's first name
1.297     matthew  14946: 
                   14947: =item $middle
                   14948: 
                   14949: =item $last
                   14950: 
                   14951: =item $gene
                   14952: 
                   14953: =item $usec
                   14954: 
                   14955: =item $end
                   14956: 
                   14957: =item $start
                   14958: 
1.957     raeburn  14959: =item $type
                   14960: 
                   14961: =item $locktype
                   14962: 
                   14963: =item $cid
                   14964: 
                   14965: =item $selfenroll
                   14966: 
                   14967: =item $context
                   14968: 
1.1216    raeburn  14969: =item $credits, number of credits student will earn from this class
                   14970: 
1.1314    raeburn  14971: =item $instsec, institutional course section code for student
                   14972: 
1.297     matthew  14973: =back
                   14974: 
1.191     harris41 14975: 
                   14976: =item *
                   14977: 
1.243     albertel 14978: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14979: custom role; give a custom role to a user for the level given by URL.  Specify
                   14980: name and domain of role author, and role name
1.191     harris41 14981: 
                   14982: =item *
                   14983: 
1.243     albertel 14984: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14985: 
                   14986: =item *
                   14987: 
1.243     albertel 14988: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14989: 
                   14990: =back
                   14991: 
                   14992: =head2 Course Infomation
                   14993: 
                   14994: =over 4
1.191     harris41 14995: 
                   14996: =item *
                   14997: 
1.1118    foxr     14998: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14999: specified course id, including all environment settings for the
                   15000: course, the description of the course will be in the hash under the
                   15001: key 'description'
1.191     harris41 15002: 
1.1118    foxr     15003: $options is an optional parameter that if supplied is a hash reference that controls
                   15004: what how this function works.  It has the following key/values:
                   15005: 
                   15006: =over 4
                   15007: 
                   15008: =item freshen_cache
                   15009: 
                   15010: If defined, and the environment cache for the course is valid, it is 
                   15011: returned in the returned hash.
                   15012: 
                   15013: =item one_time
                   15014: 
                   15015: If defined, the last cache time is set to _now_
                   15016: 
                   15017: =item user
                   15018: 
                   15019: If defined, the supplied username is used instead of the current user.
                   15020: 
                   15021: 
                   15022: =back
                   15023: 
1.191     harris41 15024: =item *
                   15025: 
1.624     albertel 15026: resdata($name,$domain,$type,@which) : request for current parameter
                   15027: setting for a specific $type, where $type is either 'course' or 'user',
                   15028: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15029: answers for 10 minutes.
1.243     albertel 15030: 
1.877     foxr     15031: =item *
                   15032: 
                   15033: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15034: data base, returning a hash that is keyed by the resource name and has
                   15035: values that are the resource value.  I believe that the timestamps and
                   15036: versions are also returned.
                   15037: 
1.1236    raeburn  15038: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15039: supplemental content area. This routine caches the number of files for 
                   15040: 10 minutes.
                   15041: 
1.243     albertel 15042: =back
                   15043: 
                   15044: =head2 Course Modification
                   15045: 
                   15046: =over 4
1.191     harris41 15047: 
                   15048: =item *
                   15049: 
1.243     albertel 15050: writecoursepref($courseid,%prefs) : write preferences (environment
                   15051: database) for a course
1.191     harris41 15052: 
                   15053: =item *
                   15054: 
1.1011    raeburn  15055: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15056: 
                   15057: =item *
                   15058: 
1.1038    raeburn  15059: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15060: 
1.1167    droeschl 15061: =item *
                   15062: 
                   15063: is_course($courseid), is_course($cdom, $cnum)
                   15064: 
                   15065: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15066: two component version $cdom, $cnum. It checks if the specified course exists.
                   15067: 
                   15068: Returns:
                   15069:     undef if the course doesn't exist, otherwise
                   15070:     in scalar context the combined courseid.
                   15071:     in list context the two components of the course identifier, domain and 
                   15072:     courseid.    
                   15073: 
1.243     albertel 15074: =back
                   15075: 
                   15076: =head2 Resource Subroutines
                   15077: 
                   15078: =over 4
1.191     harris41 15079: 
                   15080: =item *
                   15081: 
1.243     albertel 15082: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15083: 
                   15084: =item *
                   15085: 
1.243     albertel 15086: repcopy($filename) : subscribes to the requested file, and attempts to
                   15087: replicate from the owning library server, Might return
1.607     raeburn  15088: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15089: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15090: resource. Expects the local filesystem pathname
                   15091: (/home/httpd/html/res/....)
                   15092: 
                   15093: =back
                   15094: 
                   15095: =head2 Resource Information
                   15096: 
                   15097: =over 4
1.191     harris41 15098: 
                   15099: =item *
                   15100: 
1.1228    raeburn  15101: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15102: and returns the value of a variety of different possible values,
                   15103: $varname should be a request string, and the other parameters can be
                   15104: used to specify who and what one is asking about. Ordinarily, $cid 
                   15105: does not need to be specified, as it is retrived from 
                   15106: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15107: within lonuserstate::loadmap() when initializing a course, before
                   15108: $env{'request.course.id'} has been set, so it needs to be provided
                   15109: in that one case.
1.243     albertel 15110: 
                   15111: Possible values for $varname are environment.lastname (or other item
                   15112: from the envirnment hash), user.name (or someother aspect about the
                   15113: user), resource.0.maxtries (or some other part and parameter of a
                   15114: resource)
1.204     albertel 15115: 
                   15116: =item *
                   15117: 
1.243     albertel 15118: directcondval($number) : get current value of a condition; reads from a state
                   15119: string
1.204     albertel 15120: 
                   15121: =item *
                   15122: 
1.243     albertel 15123: condval($condidx) : value of condition index based on state
1.204     albertel 15124: 
                   15125: =item *
                   15126: 
1.1362    raeburn  15127: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15128: resource's metadata, $what should be either a specific key, or either
                   15129: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15130: packages that this resource currently uses, the last 3 arguments are 
                   15131: only used internally for recursive metadata.
                   15132: 
                   15133: the toolsymb is only used where the uri is for an external tool (for which
                   15134: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15135: 
1.1371    raeburn  15136: this function automatically caches all requests except any made recursively
                   15137: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15138: defined).
1.191     harris41 15139: 
                   15140: =item *
                   15141: 
1.243     albertel 15142: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15143: network of library servers; returns file handle of where SQL and regex results
                   15144: will be stored for query
1.191     harris41 15145: 
                   15146: =item *
                   15147: 
1.1282    raeburn  15148: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15149: return symbolic list entry (all arguments optional). 
                   15150: 
                   15151: Args: filename is the filename (including path) for the file for which a symb 
                   15152: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15153: to check access status if more than one resource was found in the bighash 
                   15154: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15155: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15156: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15157: cause possible symbs to be checked to determine if they are subject to content
                   15158: blocking, if so they will not be included as possible symbs; possibles is a
                   15159: ref to a hash, which, as a side effect, will be populated with all possible 
                   15160: symbs (content blocking not tested).
                   15161:  
1.243     albertel 15162: returns the data handle
1.191     harris41 15163: 
                   15164: =item *
                   15165: 
1.1190    raeburn  15166: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15167: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15168: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15169: on failure, user must be in a course, as it assumes the existence of
                   15170: the course initial hash, and uses $env('request.course.id'}.  The third
                   15171: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15172: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15173: encrypted; otherwise it will be null.  
1.191     harris41 15174: 
                   15175: =item *
                   15176: 
1.243     albertel 15177: symbclean($symb) : removes versions numbers from a symb, returns the
                   15178: cleaned symb
1.191     harris41 15179: 
                   15180: =item *
                   15181: 
1.243     albertel 15182: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15183: course map, user must be in a course for it to work.
1.191     harris41 15184: 
                   15185: =item *
                   15186: 
1.243     albertel 15187: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15188: 
                   15189: =item *
                   15190: 
1.243     albertel 15191: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15192: a random seed, all arguments are optional, if they aren't sent it uses the
                   15193: environment to derive them. Note: if symb isn't sent and it can't get one
                   15194: from &symbread it will use the current time as its return value
1.191     harris41 15195: 
                   15196: =item *
                   15197: 
1.243     albertel 15198: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15199: unfakeable, receipt
1.191     harris41 15200: 
                   15201: =item *
                   15202: 
1.620     albertel 15203: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15204: 
                   15205: =item *
                   15206: 
1.243     albertel 15207: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15208: 
                   15209: =item *
                   15210: 
1.243     albertel 15211: 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 15212: 
                   15213: =item *
                   15214: 
1.243     albertel 15215: 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 15216: 
                   15217: =item *
                   15218: 
1.243     albertel 15219: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15220: 
                   15221: =item *
                   15222: 
1.243     albertel 15223: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15224: forcing spreadsheet to reevaluate the resource scores next time.
                   15225: 
1.1195    raeburn  15226: =item * 
                   15227: 
1.1196    raeburn  15228: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15229: when viewing in course context.
1.1195    raeburn  15230: 
1.1196    raeburn  15231:  input: six args -- filename (decluttered), course number, course domain,
                   15232:                     url, symb (if registered) and group (if this is a 
                   15233:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15234: 
1.1196    raeburn  15235:  output: array of five scalars --
1.1195    raeburn  15236:          $cfile -- url for file editing if editable on current server
                   15237:          $home -- homeserver of resource (i.e., for author if published,
                   15238:                                           or course if uploaded.).
                   15239:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15240:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15241:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15242: 
                   15243: =item *
                   15244: 
                   15245: is_course_upload($file,$cnum,$cdom)
                   15246: 
                   15247: Used in course context to determine if current file was uploaded to 
                   15248: the course (i.e., would be found in /userfiles/docs on the course's 
                   15249: homeserver.
                   15250: 
                   15251:   input: 3 args -- filename (decluttered), course number and course domain.
                   15252:   output: boolean -- 1 if file was uploaded.
                   15253: 
1.243     albertel 15254: =back
                   15255: 
                   15256: =head2 Storing/Retreiving Data
                   15257: 
                   15258: =over 4
1.191     harris41 15259: 
                   15260: =item *
                   15261: 
1.1269    raeburn  15262: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15263: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15264: the remaining args aren't required and if they aren't passed or are '' they will
                   15265: be derived from the env (with the exception of $laststore, which is an 
                   15266: optional arg used when a user's submission is stored in grading).
                   15267: $laststore is $version=$timestamp, where $version is the most recent version
                   15268: number retrieved for the corresponding $symb in the $namespace db file, and
                   15269: $timestamp is the timestamp for that transaction (UNIX time).
                   15270: $laststore is currently only passed when cstore() is called by 
                   15271: structuretags::finalize_storage().
1.191     harris41 15272: 
                   15273: =item *
                   15274: 
1.1269    raeburn  15275: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15276: but uses critical subroutine
1.191     harris41 15277: 
                   15278: =item *
                   15279: 
1.243     albertel 15280: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15281: all args are optional
1.191     harris41 15282: 
                   15283: =item *
                   15284: 
1.717     albertel 15285: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15286: dumps the complete (or key matching regexp) namespace into a hash
                   15287: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15288: normally &store()ed into
                   15289: 
                   15290: $range should be either an integer '100' (give me the first 100
                   15291:                                            matching records)
                   15292:               or be  two integers sperated by a - with no spaces
                   15293:                  '30-50' (give me the 30th through the 50th matching
                   15294:                           records)
                   15295: 
                   15296: 
                   15297: =item *
                   15298: 
1.1269    raeburn  15299: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15300: replaces a &store() version of data with a replacement set of data
                   15301: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15302: reference. If $tolog is true, the transaction is logged in the courselog
                   15303: with an action=PUTSTORE.
1.717     albertel 15304: 
                   15305: =item *
                   15306: 
1.243     albertel 15307: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15308: works very similar to store/cstore, but all data is stored in a
                   15309: temporary location and can be reset using tmpreset, $storehash should
                   15310: be a hash reference, returns nothing on success
1.191     harris41 15311: 
                   15312: =item *
                   15313: 
1.243     albertel 15314: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15315: similar to restore, but all data is stored in a temporary location and
                   15316: can be reset using tmpreset. Returns a hash of values on success,
                   15317: error string otherwise.
1.191     harris41 15318: 
                   15319: =item *
                   15320: 
1.243     albertel 15321: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15322: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15323: 
                   15324: =item *
                   15325: 
1.243     albertel 15326: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15327: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15328: 
                   15329: =item *
                   15330: 
1.243     albertel 15331: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15332: namesp ($udom and $uname are optional)
1.191     harris41 15333: 
                   15334: =item *
                   15335: 
1.702     albertel 15336: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15337: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15338: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15339: 
1.702     albertel 15340: $range should be either an integer '100' (give me the first 100
                   15341:                                            matching records)
                   15342:               or be  two integers sperated by a - with no spaces
                   15343:                  '30-50' (give me the 30th through the 50th matching
                   15344:                           records)
1.449     matthew  15345: =item *
                   15346: 
                   15347: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15348: $store can be a scalar, an array reference, or if the amount to be 
                   15349: incremented is > 1, a hash reference.
                   15350: 
                   15351: ($udom and $uname are optional)
1.191     harris41 15352: 
                   15353: =item *
                   15354: 
1.243     albertel 15355: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15356: ($udom and $uname are optional)
1.191     harris41 15357: 
                   15358: =item *
                   15359: 
1.243     albertel 15360: cput($namespace,$storehash,$udom,$uname) : critical put
                   15361: ($udom and $uname are optional)
1.191     harris41 15362: 
                   15363: =item *
                   15364: 
1.748     albertel 15365: newput($namespace,$storehash,$udom,$uname) :
                   15366: 
                   15367: Attempts to store the items in the $storehash, but only if they don't
                   15368: currently exist, if this succeeds you can be certain that you have 
                   15369: successfully created a new key value pair in the $namespace db.
                   15370: 
                   15371: 
                   15372: Args:
                   15373:  $namespace: name of database to store values to
                   15374:  $storehash: hashref to store to the db
                   15375:  $udom: (optional) domain of user containing the db
                   15376:  $uname: (optional) name of user caontaining the db
                   15377: 
                   15378: Returns:
                   15379:  'ok' -> succeeded in storing all keys of $storehash
                   15380:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15381:                         least <key> already existed in the db (other
                   15382:                         requested keys may also already exist)
1.967     bisitz   15383:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15384:  'con_lost' -> unable to contact request server
                   15385:  'refused' -> action was not allowed by remote machine
                   15386: 
                   15387: 
                   15388: =item *
                   15389: 
1.243     albertel 15390: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15391: reference filled in from namesp (encrypts the return communication)
                   15392: ($udom and $uname are optional)
1.191     harris41 15393: 
                   15394: =item *
                   15395: 
1.243     albertel 15396: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15397: critical subroutine
                   15398: 
1.806     raeburn  15399: =item *
                   15400: 
1.860     raeburn  15401: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15402: array reference filled in from namespace found in domain level on either
                   15403: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15404: 
                   15405: =item *
                   15406: 
1.860     raeburn  15407: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15408: domain level either on specified domain server ($uhome) or primary domain 
                   15409: server ($udom and $uhome are optional)
1.806     raeburn  15410: 
1.943     raeburn  15411: =item * 
                   15412: 
1.1240    raeburn  15413: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15414: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15415: the target domain.
                   15416: 
                   15417: May also include additional key => value pairs for the following groups:
                   15418: 
                   15419: =over
                   15420: 
                   15421: =item
                   15422: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15423: 
                   15424: =over
                   15425: 
                   15426: =item defaultquota, authorquota
                   15427: 
                   15428: =back
                   15429: 
                   15430: =item
                   15431: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15432: portfolio for users).
                   15433: 
                   15434: =over
                   15435: 
                   15436: =item
                   15437: aboutme, blog, webdav, portfolio
                   15438: 
                   15439: =back
                   15440: 
                   15441: =item
                   15442: requestcourses: ability to request courses, and how requests are processed.
                   15443: 
                   15444: =over
                   15445: 
                   15446: =item
1.1305    raeburn  15447: official, unofficial, community, textbook, placement
1.1240    raeburn  15448: 
                   15449: =back
                   15450: 
                   15451: =item
                   15452: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15453: 
                   15454: =over
                   15455: 
                   15456: =item
1.1256    raeburn  15457: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15458: 
                   15459: =back
                   15460: 
                   15461: =item
                   15462: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15463: for course's uploaded content.
                   15464: 
                   15465: =over
                   15466: 
                   15467: =item
1.1246    raeburn  15468: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15469: communityquota, textbookquota, placementquota
1.1240    raeburn  15470: 
                   15471: =back
                   15472: 
                   15473: =item
                   15474: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15475: on your servers.
                   15476: 
                   15477: =over
                   15478: 
                   15479: =item 
                   15480: remotesessions, hostedsessions
                   15481: 
                   15482: =back
                   15483: 
                   15484: =back
                   15485: 
                   15486: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15487: utility to create a configuration.db file on a domain's primary library server 
                   15488: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15489: -- corresponding values are authentication type (internal, krb4, krb5,
                   15490: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15491: will be available. Values are retrieved from cache (if current), unless the
                   15492: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15493: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15494: 
                   15495: Typical usage:
1.943     raeburn  15496: 
1.1240    raeburn  15497: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15498: 
1.243     albertel 15499: =back
                   15500: 
                   15501: =head2 Network Status Functions
                   15502: 
                   15503: =over 4
1.191     harris41 15504: 
                   15505: =item *
                   15506: 
1.1137    raeburn  15507: dirlist() : return directory list based on URI (first arg).
                   15508: 
                   15509: Inputs: 1 required, 5 optional.
                   15510: 
                   15511: =over
                   15512: 
                   15513: =item 
                   15514: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15515: 
                   15516: =item
                   15517: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15518: 
                   15519: =item
                   15520: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15521: 
                   15522: =item
                   15523: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15524: 
                   15525: =item
                   15526: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15527: 
                   15528: =item 
                   15529: $alternateRoot - path to prepend in place of path from $uri.
                   15530: 
                   15531: =back
                   15532: 
                   15533: Returns: Array of up to two items.
                   15534: 
                   15535: =over
                   15536: 
                   15537: a reference to an array of files/subdirectories
                   15538: 
                   15539: =over
                   15540: 
                   15541: Each element in the array of files/subdirectories is a & separated list of
                   15542: item name and the result of running stat on the item.  If dirlist was requested
                   15543: for a file instead of a directory, the item name will be ''. For a directory 
                   15544: listing, if the item is a metadata file, the element will end &N&M 
                   15545: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15546: default copyright set (1).  
                   15547: 
                   15548: =back
                   15549: 
                   15550: a scalar containing error condition (if encountered).
                   15551: 
                   15552: =over
                   15553: 
                   15554: =item 
                   15555: no_host (no homeserver identified for $username:$domain).
                   15556: 
                   15557: =item 
                   15558: no_such_host (server contacted for listing not identified as valid host).
                   15559: 
                   15560: =item 
                   15561: con_lost (connection to remote server failed).
                   15562: 
                   15563: =item 
                   15564: refused (invalid $username:$domain received on lond side).
                   15565: 
                   15566: =item 
                   15567: no_such_dir (directory at specified path on lond side does not exist). 
                   15568: 
                   15569: =item 
                   15570: empty (directory at specified path on lond side is empty).
                   15571: 
                   15572: =over
                   15573: 
                   15574: This is currently not encountered because the &ls3, &ls2, 
                   15575: &ls (_handler) routines on the lond side do not filter out
                   15576: . and .. from a directory listing. 
                   15577: 
                   15578: =back
                   15579: 
                   15580: =back
                   15581: 
                   15582: =back
1.191     harris41 15583: 
                   15584: =item *
                   15585: 
1.243     albertel 15586: spareserver() : find server with least workload from spare.tab
                   15587: 
1.986     foxr     15588: 
                   15589: =item *
                   15590: 
                   15591: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15592: if there is no corresponding loncapa host.
                   15593: 
1.243     albertel 15594: =back
                   15595: 
1.986     foxr     15596: 
1.243     albertel 15597: =head2 Apache Request
                   15598: 
                   15599: =over 4
1.191     harris41 15600: 
                   15601: =item *
                   15602: 
1.243     albertel 15603: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15604: localhost, posts hash
                   15605: 
                   15606: =back
                   15607: 
                   15608: =head2 Data to String to Data
                   15609: 
                   15610: =over 4
1.191     harris41 15611: 
                   15612: =item *
                   15613: 
1.243     albertel 15614: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15615: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15616: 
                   15617: =item *
                   15618: 
1.243     albertel 15619: hashref2str($hashref) : convert a hashref into a string complete with
                   15620: escaping and '=' and '&' separators, supports elements that are
                   15621: arrayrefs and hashrefs
1.191     harris41 15622: 
                   15623: =item *
                   15624: 
1.243     albertel 15625: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15626: with escaping and '&' separators, supports elements that are arrayrefs
                   15627: and hashrefs
1.191     harris41 15628: 
                   15629: =item *
                   15630: 
1.243     albertel 15631: str2hash($string) : convert string to hash using unescaping and
                   15632: splitting on '=' and '&', supports elements that are arrayrefs and
                   15633: hashrefs
1.191     harris41 15634: 
                   15635: =item *
                   15636: 
1.243     albertel 15637: str2array($string) : convert string to hash using unescaping and
                   15638: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15639: 
                   15640: =back
                   15641: 
                   15642: =head2 Logging Routines
                   15643: 
                   15644: 
                   15645: These routines allow one to make log messages in the lonnet.log and
                   15646: lonnet.perm logfiles.
1.191     harris41 15647: 
1.1119    foxr     15648: =over 4
                   15649: 
1.191     harris41 15650: =item *
                   15651: 
1.243     albertel 15652: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15653: 
                   15654: =item *
                   15655: 
1.243     albertel 15656: logthis() : append message to the normal lonnet.log file, it gets
                   15657: preiodically rolled over and deleted.
1.191     harris41 15658: 
                   15659: =item *
                   15660: 
1.243     albertel 15661: logperm() : append a permanent message to lonnet.perm.log, this log
                   15662: file never gets deleted by any automated portion of the system, only
                   15663: messages of critical importance should go in here.
                   15664: 
1.1119    foxr     15665: 
1.243     albertel 15666: =back
                   15667: 
                   15668: =head2 General File Helper Routines
                   15669: 
                   15670: =over 4
1.191     harris41 15671: 
                   15672: =item *
                   15673: 
1.481     raeburn  15674: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15675: (a) files in /uploaded
                   15676:   (i) If a local copy of the file exists - 
                   15677:       compares modification date of local copy with last-modified date for 
                   15678:       definitive version stored on home server for course. If local copy is 
                   15679:       stale, requests a new version from the home server and stores it. 
                   15680:       If the original has been removed from the home server, then local copy 
                   15681:       is unlinked.
                   15682:   (ii) If local copy does not exist -
                   15683:       requests the file from the home server and stores it. 
                   15684:   
                   15685:   If $caller is 'uploadrep':  
                   15686:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15687:     for request for files originally uploaded via DOCS. 
                   15688:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15689:   
                   15690:   Otherwise:
                   15691:      This indicates a call from the content generation phase of the request.
                   15692:      -  returns the entire contents of the file or -1.
                   15693:      
                   15694: (b) files in /res
                   15695:    - returns the entire contents of a file or -1; 
                   15696:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15697: 
1.712     albertel 15698: 
                   15699: =item *
                   15700: 
                   15701: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15702:                   reference
                   15703: 
                   15704: returns either a stat() list of data about the file or an empty list
                   15705: if the file doesn't exist or couldn't find out about it (connection
                   15706: problems or user unknown)
                   15707: 
1.191     harris41 15708: =item *
                   15709: 
1.243     albertel 15710: filelocation($dir,$file) : returns file system location of a file
                   15711: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15712: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15713: and a file of ../bob will become /a/bob)
1.191     harris41 15714: 
                   15715: =item *
                   15716: 
                   15717: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15718: filelocation except for hrefs
                   15719: 
                   15720: =item *
                   15721: 
1.1261    raeburn  15722: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15723: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15724: 
1.243     albertel 15725: =back
                   15726: 
1.608     albertel 15727: =head2 Usererfile file routines (/uploaded*)
                   15728: 
                   15729: =over 4
                   15730: 
                   15731: =item *
                   15732: 
                   15733: userfileupload(): main rotine for putting a file in a user or course's
                   15734:                   filespace, arguments are,
                   15735: 
1.620     albertel 15736:  formname - required - this is the name of the element in $env where the
1.608     albertel 15737:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15738:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15739:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15740:  context - if coursedoc, store the file in the course of the active role
                   15741:              of the current user; 
                   15742:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15743:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15744:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15745:          if undefined, it will be placed in "unknown"
                   15746: 
                   15747:  (This routine calls clean_filename() to remove any dangerous
                   15748:  characters from the filename, and then calls finuserfileupload() to
                   15749:  complete the transaction)
                   15750: 
                   15751:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15752:  and /adm/notfound.html if unsuccessful
                   15753: 
                   15754: =item *
                   15755: 
                   15756: clean_filename(): routine for cleaing a filename up for storage in
                   15757:                  userfile space, argument is:
                   15758: 
                   15759:  filename - proposed filename
                   15760: 
                   15761: returns: the new clean filename
                   15762: 
                   15763: =item *
                   15764: 
1.1090    raeburn  15765: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15766: userspace, probably shouldn't be called directly
                   15767: 
                   15768:   docuname: username or courseid of destination for the file
                   15769:   docudom: domain of user/course of destination for the file
                   15770:   formname: same as for userfileupload()
1.1090    raeburn  15771:   fname: filename (including subdirectories) for the file
                   15772:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15773:   allfiles: reference to hash used to store objects found by parser
                   15774:   codebase: reference to hash used for codebases of java objects found by parser
                   15775:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15776:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15777:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15778:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15779:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15780:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15781:   mimetype: reference to scalar to accommodate mime type determined
                   15782:             from File::MMagic if $parser = parse.
1.608     albertel 15783: 
                   15784:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15785:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15786:  was 'overwrite').
                   15787:  
1.608     albertel 15788: 
                   15789: =item *
                   15790: 
                   15791: renameuserfile(): renames an existing userfile to a new name
                   15792: 
                   15793:   Args:
                   15794:    docuname: username or courseid of destination for the file
                   15795:    docudom: domain of user/course of destination for the file
                   15796:    old: current file name (including any subdirs under userfiles)
                   15797:    new: desired file name (including any subdirs under userfiles)
                   15798: 
                   15799: =item *
                   15800: 
                   15801: mkdiruserfile(): creates a directory is a userfiles dir
                   15802: 
                   15803:   Args:
                   15804:    docuname: username or courseid of destination for the file
                   15805:    docudom: domain of user/course of destination for the file
                   15806:    dir: dir to create (including any subdirs under userfiles)
                   15807: 
                   15808: =item *
                   15809: 
                   15810: removeuserfile(): removes a file that exists in userfiles
                   15811: 
                   15812:   Args:
                   15813:    docuname: username or courseid of destination for the file
                   15814:    docudom: domain of user/course of destination for the file
                   15815:    fname: filname to delete (including any subdirs under userfiles)
                   15816: 
                   15817: =item *
                   15818: 
                   15819: removeuploadedurl(): convience function for removeuserfile()
                   15820: 
                   15821:   Args:
                   15822:    url:  a full /uploaded/... url to delete
                   15823: 
1.747     albertel 15824: =item * 
                   15825: 
                   15826: get_portfile_permissions():
                   15827:   Args:
                   15828:     domain: domain of user or course contain the portfolio files
                   15829:     user: name of user or num of course contain the portfolio files
                   15830:   Returns:
                   15831:     hashref of a dump of the proper file_permissions.db
                   15832:    
                   15833: 
                   15834: =item * 
                   15835: 
                   15836: get_access_controls():
                   15837: 
                   15838: Args:
                   15839:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15840:   group: (optional) the group you want the files associated with
                   15841:   file: (optional) the file you want access info on
                   15842: 
                   15843: Returns:
1.749     raeburn  15844:     a hash (keys are file names) of hashes containing
                   15845:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15846:         values are XML containing access control settings (see below) 
1.747     albertel 15847: 
                   15848: Internal notes:
                   15849: 
1.749     raeburn  15850:  access controls are stored in file_permissions.db as key=value pairs.
                   15851:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15852:         where scope -> public,guest,course,group,domains or users.
                   15853:               end -> UNIX time for end of access (0 -> no end date)
                   15854:               start -> UNIX time for start of access
                   15855: 
                   15856:     value -> XML description of access control
                   15857:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15858:             <start></start>
                   15859:             <end></end>
                   15860: 
                   15861:             <password></password>  for scope type = guest
                   15862: 
                   15863:             <domain></domain>     for scope type = course or group
                   15864:             <number></number>
                   15865:             <roles id="">
                   15866:              <role></role>
                   15867:              <access></access>
                   15868:              <section></section>
                   15869:              <group></group>
                   15870:             </roles>
                   15871: 
                   15872:             <dom></dom>         for scope type = domains
                   15873: 
                   15874:             <users>             for scope type = users
                   15875:              <user>
                   15876:               <uname></uname>
                   15877:               <udom></udom>
                   15878:              </user>
                   15879:             </users>
                   15880:            </scope> 
                   15881:               
                   15882:  Access data is also aggregated for each file in an additional key=value pair:
                   15883:  key -> path to file/file_name\0accesscontrol 
                   15884:  value -> reference to hash
                   15885:           hash contains key = value pairs
                   15886:           where key = uniqueID:scope_end_start
                   15887:                 value = UNIX time record was last updated
                   15888: 
                   15889:           Used to improve speed of look-ups of access controls for each file.  
                   15890:  
                   15891:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15892: 
1.1198    raeburn  15893: =item *
                   15894: 
1.749     raeburn  15895: modify_access_controls():
                   15896: 
                   15897: Modifies access controls for a portfolio file
                   15898: Args
                   15899: 1. file name
                   15900: 2. reference to hash of required changes,
                   15901: 3. domain
                   15902: 4. username
                   15903:   where domain,username are the domain of the portfolio owner 
                   15904:   (either a user or a course) 
                   15905: 
                   15906: Returns:
                   15907: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15908: 2. result of deletions ('ok' or 'error', with error message).
                   15909: 3. reference to hash of any new or updated access controls.
                   15910: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15911:    key = integer (inbound ID)
1.1198    raeburn  15912:    value = uniqueID
                   15913: 
                   15914: =item *
                   15915: 
                   15916: get_timebased_id():
                   15917: 
                   15918: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15919: course via the Course Editor (e.g., folders, composite pages, 
                   15920: group bulletin boards).
                   15921: 
                   15922: Args: (first three required; six others optional)
                   15923: 
                   15924: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15925:    docssequence, or name of group
                   15926: 
                   15927: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15928:    e.g., num, boardids
                   15929: 
                   15930: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15931:    file will be named nohist_namespace.db
                   15932: 
                   15933: 4. cdom: domain of course; default is current course domain from %env
                   15934: 
                   15935: 5. cnum: course number; default is current course number from %env
                   15936: 
                   15937: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15938:    unix timestamp to form the suffix, if the plain timestamp is already
                   15939:    in use.  Default is to not do this, but simply increment the unix 
                   15940:    timestamp by 1 until a unique key is obtained.
                   15941: 
                   15942: 7. who: holder of locking key; defaults to user:domain for user.
                   15943: 
                   15944: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15945:    retrying); default is 3.
                   15946: 
                   15947: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15948: 
                   15949: Returns:
                   15950: 
                   15951: 1. suffix obtained (numeric)
                   15952: 
                   15953: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15954: 
                   15955: 3. error: contains (localized) error message if an error occurred.
                   15956: 
1.747     albertel 15957: 
1.608     albertel 15958: =back
                   15959: 
1.243     albertel 15960: =head2 HTTP Helper Routines
                   15961: 
                   15962: =over 4
                   15963: 
1.191     harris41 15964: =item *
                   15965: 
                   15966: escape() : unpack non-word characters into CGI-compatible hex codes
                   15967: 
                   15968: =item *
                   15969: 
                   15970: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15971: 
1.243     albertel 15972: =back
                   15973: 
                   15974: =head1 PRIVATE SUBROUTINES
                   15975: 
                   15976: =head2 Underlying communication routines (Shouldn't call)
                   15977: 
                   15978: =over 4
                   15979: 
                   15980: =item *
                   15981: 
                   15982: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15983: 
                   15984: =item *
                   15985: 
                   15986: reply() : uses subreply to send a message to remote machine, logs all failures
                   15987: 
                   15988: =item *
                   15989: 
                   15990: critical() : passes a critical message to another server; if cannot
                   15991: get through then place message in connection buffer directory and
                   15992: returns con_delayed, if incapable of saving message, returns
                   15993: con_failed
                   15994: 
                   15995: =item *
                   15996: 
                   15997: reconlonc() : tries to reconnect lonc client processes.
                   15998: 
                   15999: =back
                   16000: 
                   16001: =head2 Resource Access Logging
                   16002: 
                   16003: =over 4
                   16004: 
                   16005: =item *
                   16006: 
                   16007: flushcourselogs() : flush (save) buffer logs and access logs
                   16008: 
                   16009: =item *
                   16010: 
                   16011: courselog($what) : save message for course in hash
                   16012: 
                   16013: =item *
                   16014: 
                   16015: courseacclog($what) : save message for course using &courselog().  Perform
                   16016: special processing for specific resource types (problems, exams, quizzes, etc).
                   16017: 
1.191     harris41 16018: =item *
                   16019: 
                   16020: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16021: as a PerlChildExitHandler
1.243     albertel 16022: 
                   16023: =back
                   16024: 
                   16025: =head2 Other
                   16026: 
                   16027: =over 4
                   16028: 
                   16029: =item *
                   16030: 
                   16031: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16032: 
                   16033: =back
                   16034: 
                   16035: =cut
1.877     foxr     16036: 

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