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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1393  ! raeburn     4: # $Id: lonnet.pm,v 1.1392 2018/12/05 03:29:11 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'};
                   1646:             }
1.1391    raeburn  1647:             $dom_balancers = $currbalancer;
1.1191    raeburn  1648:         } else {
1.1391    raeburn  1649:             if (keys(%{$result})) {
                   1650:                 foreach my $key (keys(%{$result})) {
                   1651:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1652:                         (ref($result->{$key}) eq 'HASH')) {
                   1653:                         $is_balancer = 1;
                   1654:                         $currrules = $result->{$key}{'rules'};
                   1655:                         $currtargets = $result->{$key}{'targets'};
                   1656:                         $setcookie = $result->{$key}{'cookie'};
                   1657:                         last;
                   1658:                     }
1.1191    raeburn  1659:                 }
1.1391    raeburn  1660:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1661:             }
                   1662:         }
                   1663:     }
1.1391    raeburn  1664:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1665: }
                   1666: 
1.1129    raeburn  1667: sub get_loadbalancer_targets {
                   1668:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1669:     my $offloadto;
1.1175    raeburn  1670:     if ($rule_in_effect eq 'none') {
                   1671:         return [$perlvar{'lonHostID'}];
                   1672:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1673:         $offloadto = $currtargets;
                   1674:     } else {
                   1675:         if ($rule_in_effect eq 'homeserver') {
                   1676:             my $homeserver = &homeserver($uname,$udom);
                   1677:             if ($homeserver ne 'no_host') {
                   1678:                 $offloadto = [$homeserver];
                   1679:             }
                   1680:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1681:             my %domconfig =
                   1682:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1683:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1684:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1685:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1686:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1687:                     }
                   1688:                 }
                   1689:             } else {
1.1178    raeburn  1690:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1691:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1692:                 if (&hostname($remotebalancer) ne '') {
                   1693:                     $offloadto = [$remotebalancer];
                   1694:                 }
                   1695:             }
                   1696:         } elsif (&hostname($rule_in_effect) ne '') {
                   1697:             $offloadto = [$rule_in_effect];
                   1698:         }
                   1699:     }
                   1700:     return $offloadto;
                   1701: }
                   1702: 
1.1127    raeburn  1703: sub internet_dom_servers {
                   1704:     my ($dom) = @_;
                   1705:     my (%uniqservers,%servers);
                   1706:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1707:     my @machinedoms = &machine_domains($primaryserver);
                   1708:     foreach my $mdom (@machinedoms) {
                   1709:         my %currservers = %servers;
                   1710:         my %server = &get_servers($mdom);
                   1711:         %servers = (%currservers,%server);
                   1712:     }
                   1713:     my %by_hostname;
                   1714:     foreach my $id (keys(%servers)) {
                   1715:         push(@{$by_hostname{$servers{$id}}},$id);
                   1716:     }
                   1717:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1718:         if (@{$by_hostname{$hostname}} > 1) {
                   1719:             my $match = 0;
                   1720:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1721:                 if (&host_domain($id) eq $dom) {
                   1722:                     $uniqservers{$id} = $hostname;
                   1723:                     $match = 1;
                   1724:                 }
                   1725:             }
                   1726:             unless ($match) {
                   1727:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1728:             }
                   1729:         } else {
                   1730:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1731:         }
                   1732:     }
                   1733:     return %uniqservers;
                   1734: }
                   1735: 
1.1347    raeburn  1736: sub trusted_domains {
                   1737:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1738:     my ($trusted,$untrusted);
1.1347    raeburn  1739:     if (&domain($calldom) eq '') {
1.1349    raeburn  1740:         return ($trusted,$untrusted);
1.1347    raeburn  1741:     }
                   1742:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1743:         return ($trusted,$untrusted);
1.1347    raeburn  1744:     }
                   1745:     my $callprimary = &domain($calldom,'primary');
                   1746:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1747:     if ($intcalldom eq '') {
1.1349    raeburn  1748:         return ($trusted,$untrusted);
1.1347    raeburn  1749:     }
                   1750: 
                   1751:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1752:     unless (defined($cached)) {
                   1753:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1754:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1755:         $trustconfig = $domconfig{'trust'};
                   1756:     }
                   1757:     if (ref($trustconfig)) {
                   1758:         my (%possexc,%possinc,@allexc,@allinc); 
                   1759:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1760:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1761:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1762:             }
                   1763:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1764:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1765:             }
                   1766:         }
                   1767:         if (keys(%possexc)) {
                   1768:             if (keys(%possinc)) {
                   1769:                 foreach my $key (sort(keys(%possexc))) {
                   1770:                     next if ($key eq $intcalldom);
                   1771:                     unless ($possinc{$key}) {
                   1772:                         push(@allexc,$key);
                   1773:                     }
                   1774:                 }
                   1775:             } else {
                   1776:                 @allexc = sort(keys(%possexc));
                   1777:             }
                   1778:         }
                   1779:         if (keys(%possinc)) {
                   1780:             $possinc{$intcalldom} = 1;
                   1781:             @allinc = sort(keys(%possinc));
                   1782:         }
                   1783:         if ((@allexc > 0) || (@allinc > 0)) {
                   1784:             my %doms_by_intdom;
                   1785:             my %allintdoms = &all_host_intdom();
                   1786:             my %alldoms = &all_host_domain();
                   1787:             foreach my $key (%allintdoms) {
                   1788:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1789:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1790:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1791:                     }
                   1792:                 } else {
                   1793:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1794:                 }
                   1795:             }
                   1796:             foreach my $exc (@allexc) {
                   1797:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349    raeburn  1798:                     $untrusted = $doms_by_intdom{$exc};
1.1347    raeburn  1799:                 }
                   1800:             }
                   1801:             foreach my $inc (@allinc) {
                   1802:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349    raeburn  1803:                     $trusted = $doms_by_intdom{$inc};
1.1347    raeburn  1804:                 }
                   1805:             }
                   1806:         }
                   1807:     }
1.1349    raeburn  1808:     return ($trusted,$untrusted);
1.1347    raeburn  1809: }
                   1810: 
                   1811: sub will_trust {
                   1812:     my ($cmdtype,$domain,$possdom) = @_;
                   1813:     return 1 if ($domain eq $possdom);
                   1814:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1815:     my $willtrust; 
                   1816:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1817:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1818:             $willtrust = 1;
                   1819:         }
                   1820:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1821:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1822:             $willtrust = 1;
                   1823:         }
                   1824:     } else {
                   1825:         $willtrust = 1;
                   1826:     }
                   1827:     return $willtrust;
                   1828: }
                   1829: 
1.1       albertel 1830: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1831: 
1.599     albertel 1832: my %homecache;
1.1       albertel 1833: sub homeserver {
1.230     stredwic 1834:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1835:     my $index="$uname:$udom";
1.426     albertel 1836: 
1.599     albertel 1837:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1838: 
                   1839:     my %servers = &get_servers($udom,'library');
                   1840:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1841:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1842: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1843: 
                   1844: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1845: 	if ($answer eq 'found') {
                   1846: 	    delete($badServerCache{$tryserver}); 
                   1847: 	    return $homecache{$index}=$tryserver;
                   1848: 	} elsif ($answer eq 'no_host') {
                   1849: 	    $badServerCache{$tryserver}=1;
                   1850: 	}
1.1       albertel 1851:     }    
                   1852:     return 'no_host';
1.70      www      1853: }
                   1854: 
1.1300    raeburn  1855: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1856: 
                   1857: sub idget {
1.1300    raeburn  1858:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1859:     my %returnhash=();
1.1300    raeburn  1860:     my @ids=(); 
                   1861:     if (ref($idsref) eq 'ARRAY') {
                   1862:         @ids = @{$idsref};
                   1863:     } else {
                   1864:         return %returnhash; 
                   1865:     }
                   1866:     if ($namespace eq '') {
                   1867:         $namespace = 'ids';
                   1868:     }
1.70      www      1869:     
1.841     albertel 1870:     my %servers = &get_servers($udom,'library');
                   1871:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1872: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1873: 	if ($namespace eq 'ids') {
                   1874: 	    $idlist=~tr/A-Z/a-z/;
                   1875: 	}
                   1876: 	my $reply;
                   1877: 	if ($namespace eq 'ids') {
                   1878: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1879: 	} else {
                   1880: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1881: 	}
1.841     albertel 1882: 	my @answer=();
                   1883: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1884: 	    @answer=split(/\&/,$reply);
                   1885: 	}                    ;
                   1886: 	my $i;
                   1887: 	for ($i=0;$i<=$#ids;$i++) {
                   1888: 	    if ($answer[$i]) {
1.1299    raeburn  1889: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1890: 	    }
1.841     albertel 1891: 	}
1.1300    raeburn  1892:     }
1.70      www      1893:     return %returnhash;
                   1894: }
                   1895: 
                   1896: # ------------------------------------- Find the IDs behind a list of usernames
                   1897: 
                   1898: sub idrget {
                   1899:     my ($udom,@unames)=@_;
                   1900:     my %returnhash=();
1.800     albertel 1901:     foreach my $uname (@unames) {
                   1902:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1903:     }
1.70      www      1904:     return %returnhash;
                   1905: }
                   1906: 
1.1300    raeburn  1907: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1908: 
                   1909: sub idput {
1.1300    raeburn  1910:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1911:     my %servers=();
1.1300    raeburn  1912:     my %ids=();
                   1913:     my %byid = ();
                   1914:     if (ref($idsref) eq 'HASH') {
                   1915:         %ids=%{$idsref};
                   1916:     }
                   1917:     if ($namespace eq '') {
                   1918:         $namespace = 'ids'; 
                   1919:     }
1.800     albertel 1920:     foreach my $uname (keys(%ids)) {
                   1921: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1922:         if ($uhom eq '') {
                   1923:             $uhom=&homeserver($uname,$udom);
                   1924:         }
1.70      www      1925:         if ($uhom ne 'no_host') {
1.800     albertel 1926:             my $esc_unam=&escape($uname);
1.1300    raeburn  1927:             if ($namespace eq 'ids') {
                   1928:                 my $id=&escape($ids{$uname});
                   1929:                 $id=~tr/A-Z/a-z/;
                   1930:                 my $esc_unam=&escape($uname);
                   1931:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1932:             } else {
1.1300    raeburn  1933:                 my @currids = split(/,/,$ids{$uname});
                   1934:                 foreach my $id (@currids) {
                   1935:                     $byid{$uhom}{$id} .= $uname.',';
                   1936:                 }
                   1937:             }
                   1938:         }
                   1939:     }
                   1940:     if ($namespace eq 'clickers') {
                   1941:         foreach my $server (keys(%byid)) {
                   1942:             if (ref($byid{$server}) eq 'HASH') {
                   1943:                 foreach my $id (keys(%{$byid{$server}})) {
                   1944:                     $byid{$server} =~ s/,$//;
                   1945:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1946:                 }
1.70      www      1947:             }
                   1948:         }
1.191     harris41 1949:     }
1.800     albertel 1950:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1951:         $servers{$server} =~ s/\&$//;
                   1952:         if ($namespace eq 'ids') {     
                   1953:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1954:         } else {
                   1955:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1956:         }
1.191     harris41 1957:     }
1.344     www      1958: }
                   1959: 
1.1300    raeburn  1960: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1961: 
                   1962: sub iddel {
1.1300    raeburn  1963:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1964:     my %result=();
1.1300    raeburn  1965:     my %ids=();
                   1966:     my %byid = ();
                   1967:     if (ref($idshashref) eq 'HASH') {
                   1968:         %ids=%{$idshashref};
                   1969:     } else {
1.1231    raeburn  1970:         return %result;
                   1971:     }
1.1300    raeburn  1972:     if ($namespace eq '') {
                   1973:         $namespace = 'ids';
                   1974:     }
1.1231    raeburn  1975:     my %servers=();
1.1300    raeburn  1976:     while (my ($id,$unamestr) = each(%ids)) {
                   1977:         if ($namespace eq 'ids') {
                   1978:             my $uhom = $uhome;
                   1979:             if ($uhom eq '') { 
                   1980:                 $uhom=&homeserver($unamestr,$udom);
                   1981:             }
                   1982:             if ($uhom ne 'no_host') {
                   1983:                 $servers{$uhom}.='&'.&escape($id);
                   1984:             }
                   1985:          } else {
                   1986:             my @curritems = split(/,/,$ids{$id});
                   1987:             foreach my $uname (@curritems) {
                   1988:                 my $uhom = $uhome;
                   1989:                 if ($uhom eq '') {
                   1990:                     $uhom=&homeserver($uname,$udom);
                   1991:                 }
                   1992:                 if ($uhom ne 'no_host') { 
                   1993:                     $byid{$uhom}{$id} .= $uname.',';
                   1994:                 }
                   1995:             }
1.1231    raeburn  1996:         }
1.1300    raeburn  1997:     }
                   1998:     if ($namespace eq 'clickers') {
                   1999:         foreach my $server (keys(%byid)) {
                   2000:             if (ref($byid{$server}) eq 'HASH') {
                   2001:                 foreach my $id (keys(%{$byid{$server}})) {
                   2002:                     $byid{$server}{$id} =~ s/,$//;
                   2003:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2004:                 }
1.1231    raeburn  2005:             }
                   2006:         }
                   2007:     }
                   2008:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2009:         $servers{$server} =~ s/\&$//;
                   2010:         if ($namespace eq 'ids') {
                   2011:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2012:         } elsif ($namespace eq 'clickers') {
                   2013:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2014:         }
1.1231    raeburn  2015:     }
                   2016:     return %result;
                   2017: }
                   2018: 
1.1300    raeburn  2019: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2020: 
                   2021: sub updateclickers {
                   2022:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2023:     my %clickers;
                   2024:     if (ref($idshashref) eq 'HASH') {
                   2025:         %clickers=%{$idshashref};
                   2026:     } else {
                   2027:         return;
                   2028:     }
                   2029:     my $items='';
                   2030:     foreach my $item (keys(%clickers)) {
                   2031:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2032:     }
                   2033:     $items=~s/\&$//;
                   2034:     my $request = "updateclickers:$udom:$action:$items";
                   2035:     if ($critical) {
                   2036:         return &critical($request,$uhome);
                   2037:     } else {
                   2038:         return &reply($request,$uhome);
                   2039:     }
                   2040: }
                   2041: 
1.1023    raeburn  2042: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2043: sub dump_dom {
1.1165    droeschl 2044:     my ($namespace, $udom, $regexp) = @_;
                   2045: 
                   2046:     $udom ||= $env{'user.domain'};
                   2047: 
                   2048:     return () unless $udom;
                   2049: 
                   2050:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2051: }
                   2052: 
1.1023    raeburn  2053: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2054: 
                   2055: sub get_dom {
1.860     raeburn  2056:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2057:     return if ($udom eq 'public');
1.806     raeburn  2058:     my $items='';
                   2059:     foreach my $item (@$storearr) {
                   2060:         $items.=&escape($item).'&';
                   2061:     }
                   2062:     $items=~s/\&$//;
1.860     raeburn  2063:     if (!$udom) {
                   2064:         $udom=$env{'user.domain'};
1.1267    raeburn  2065:         return if ($udom eq 'public');
1.860     raeburn  2066:         if (defined(&domain($udom,'primary'))) {
                   2067:             $uhome=&domain($udom,'primary');
                   2068:         } else {
1.874     albertel 2069:             undef($uhome);
1.860     raeburn  2070:         }
                   2071:     } else {
                   2072:         if (!$uhome) {
                   2073:             if (defined(&domain($udom,'primary'))) {
                   2074:                 $uhome=&domain($udom,'primary');
                   2075:             }
                   2076:         }
                   2077:     }
                   2078:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2079:         my $rep;
                   2080:         if ($namespace =~ /^enc/) {
                   2081:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2082:         } else {
                   2083:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2084:         }
1.866     raeburn  2085:         my %returnhash;
1.875     albertel 2086:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2087:             return %returnhash;
                   2088:         }
1.806     raeburn  2089:         my @pairs=split(/\&/,$rep);
                   2090:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2091:             return @pairs;
                   2092:         }
                   2093:         my $i=0;
                   2094:         foreach my $item (@$storearr) {
                   2095:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2096:             $i++;
                   2097:         }
                   2098:         return %returnhash;
                   2099:     } else {
1.880     banghart 2100:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2101:     }
                   2102: }
                   2103: 
                   2104: # -------------------------------------------- put items in domain db files 
                   2105: 
                   2106: sub put_dom {
1.860     raeburn  2107:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2108:     if (!$udom) {
                   2109:         $udom=$env{'user.domain'};
                   2110:         if (defined(&domain($udom,'primary'))) {
                   2111:             $uhome=&domain($udom,'primary');
                   2112:         } else {
1.874     albertel 2113:             undef($uhome);
1.860     raeburn  2114:         }
                   2115:     } else {
                   2116:         if (!$uhome) {
                   2117:             if (defined(&domain($udom,'primary'))) {
                   2118:                 $uhome=&domain($udom,'primary');
                   2119:             }
                   2120:         }
                   2121:     } 
                   2122:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2123:         my $items='';
                   2124:         foreach my $item (keys(%$storehash)) {
                   2125:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2126:         }
                   2127:         $items=~s/\&$//;
1.1344    raeburn  2128:         if ($namespace =~ /^enc/) {
                   2129:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2130:         } else {
                   2131:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2132:         }
1.806     raeburn  2133:     } else {
1.860     raeburn  2134:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2135:     }
                   2136: }
                   2137: 
1.1023    raeburn  2138: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2139: sub newput_dom {
1.1023    raeburn  2140:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2141:     my $result;
                   2142:     if (!$udom) {
                   2143:         $udom=$env{'user.domain'};
                   2144:     }
1.1023    raeburn  2145:     if ($udom) {
                   2146:         my $uname = &get_domainconfiguser($udom);
                   2147:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2148:     }
                   2149:     return $result;
                   2150: }
                   2151: 
1.1023    raeburn  2152: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2153: sub del_dom {
1.1023    raeburn  2154:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2155:     if (ref($storearr) eq 'ARRAY') {
                   2156:         if (!$udom) {
                   2157:             $udom=$env{'user.domain'};
                   2158:         }
1.1023    raeburn  2159:         if ($udom) {
                   2160:             my $uname = &get_domainconfiguser($udom); 
                   2161:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2162:         }
                   2163:     }
                   2164: }
                   2165: 
1.1023    raeburn  2166: # ----------------------------------construct domainconfig user for a domain 
                   2167: sub get_domainconfiguser {
                   2168:     my ($udom) = @_;
                   2169:     return $udom.'-domainconfig';
                   2170: }
                   2171: 
1.837     raeburn  2172: sub retrieve_inst_usertypes {
                   2173:     my ($udom) = @_;
                   2174:     my (%returnhash,@order);
1.989     raeburn  2175:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2176:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2177:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2178:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2179:     } else {
                   2180:         if (defined(&domain($udom,'primary'))) {
                   2181:             my $uhome=&domain($udom,'primary');
                   2182:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2183:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2184:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2185:                 return (\%returnhash,\@order);
                   2186:             }
                   2187:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2188:             my @pairs=split(/\&/,$hashitems);
                   2189:             foreach my $item (@pairs) {
                   2190:                 my ($key,$value)=split(/=/,$item,2);
                   2191:                 $key = &unescape($key);
                   2192:                 next if ($key =~ /^error: 2 /);
                   2193:                 $returnhash{$key}=&thaw_unescape($value);
                   2194:             }
                   2195:             my @esc_order = split(/\&/,$orderitems);
                   2196:             foreach my $item (@esc_order) {
                   2197:                 push(@order,&unescape($item));
                   2198:             }
                   2199:         } else {
1.1256    raeburn  2200:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2201:         }
1.1256    raeburn  2202:         return (\%returnhash,\@order);
1.837     raeburn  2203:     }
                   2204: }
                   2205: 
1.868     raeburn  2206: sub is_domainimage {
                   2207:     my ($url) = @_;
1.1306    raeburn  2208:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2209:         if (&domain($1) ne '') {
                   2210:             return '1';
                   2211:         }
                   2212:     }
                   2213:     return;
                   2214: }
                   2215: 
1.899     raeburn  2216: sub inst_directory_query {
                   2217:     my ($srch) = @_;
                   2218:     my $udom = $srch->{'srchdomain'};
                   2219:     my %results;
                   2220:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2221:     my $outcome;
1.899     raeburn  2222:     if ($homeserver ne '') {
1.1357    raeburn  2223:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2224:             if ($srch->{'srchby'} eq 'email') {
                   2225:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2226:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2227:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2228:                     (($major == 2) && ($minor < 12))) {
                   2229:                     return;
                   2230:                 }
                   2231:             }
                   2232:         }
1.904     albertel 2233: 	my $queryid=&reply("querysend:instdirsearch:".
                   2234: 			   &escape($srch->{'srchby'}).':'.
                   2235: 			   &escape($srch->{'srchterm'}).':'.
                   2236: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2237: 	my $host=&hostname($homeserver);
                   2238: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2239: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2240: 	    return;
                   2241: 	}
                   2242: 	my $response = &get_query_reply($queryid);
                   2243: 	my $maxtries = 5;
                   2244: 	my $tries = 1;
                   2245: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2246: 	    $response = &get_query_reply($queryid);
                   2247: 	    $tries ++;
                   2248: 	}
                   2249: 
                   2250:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2251:             if ($response eq 'unavailable') {
                   2252:                 $outcome = $response;
                   2253:             } else {
                   2254:                 $outcome = 'ok';
                   2255:                 my @matches = split(/\n/,$response);
                   2256:                 foreach my $match (@matches) {
                   2257:                     my ($key,$value) = split(/=/,$match);
                   2258:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2259:                 }
1.899     raeburn  2260:             }
                   2261:         }
                   2262:     }
1.909     raeburn  2263:     return ($outcome,%results);
1.899     raeburn  2264: }
                   2265: 
                   2266: sub usersearch {
                   2267:     my ($srch) = @_;
                   2268:     my $dom = $srch->{'srchdomain'};
                   2269:     my %results;
                   2270:     my %libserv = &all_library();
                   2271:     my $query = 'usersearch';
                   2272:     foreach my $tryserver (keys(%libserv)) {
                   2273:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2274:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2275:                 if ($srch->{'srchby'} eq 'email') {
                   2276:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2277:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2278:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2279:                              (($major == 2) && ($minor < 12)));
                   2280:                 }
                   2281:             }
1.899     raeburn  2282:             my $host=&hostname($tryserver);
                   2283:             my $queryid=
1.911     raeburn  2284:                 &reply("querysend:".&escape($query).':'.
                   2285:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2286:                        &escape($srch->{'srchtype'}).':'.
                   2287:                        &escape($srch->{'srchterm'}),$tryserver);
                   2288:             if ($queryid !~/^\Q$host\E\_/) {
                   2289:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2290:                 next;
1.899     raeburn  2291:             }
                   2292:             my $reply = &get_query_reply($queryid);
                   2293:             my $maxtries = 1;
                   2294:             my $tries = 1;
                   2295:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2296:                 $reply = &get_query_reply($queryid);
                   2297:                 $tries ++;
                   2298:             }
                   2299:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2300:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2301:             } else {
1.911     raeburn  2302:                 my @matches;
                   2303:                 if ($reply =~ /\n/) {
                   2304:                     @matches = split(/\n/,$reply);
                   2305:                 } else {
                   2306:                     @matches = split(/\&/,$reply);
                   2307:                 }
1.899     raeburn  2308:                 foreach my $match (@matches) {
                   2309:                     my ($uname,$udom,%userhash);
1.911     raeburn  2310:                     foreach my $entry (split(/:/,$match)) {
                   2311:                         my ($key,$value) =
                   2312:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2313:                         $userhash{$key} = $value;
                   2314:                         if ($key eq 'username') {
                   2315:                             $uname = $value;
                   2316:                         } elsif ($key eq 'domain') {
                   2317:                             $udom = $value;
1.911     raeburn  2318:                         }
1.899     raeburn  2319:                     }
                   2320:                     $results{$uname.':'.$udom} = \%userhash;
                   2321:                 }
                   2322:             }
                   2323:         }
                   2324:     }
                   2325:     return %results;
                   2326: }
                   2327: 
1.912     raeburn  2328: sub get_instuser {
                   2329:     my ($udom,$uname,$id) = @_;
                   2330:     my $homeserver = &domain($udom,'primary');
                   2331:     my ($outcome,%results);
                   2332:     if ($homeserver ne '') {
                   2333:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2334:                            &escape($id).':'.&escape($udom),$homeserver);
                   2335:         my $host=&hostname($homeserver);
                   2336:         if ($queryid !~/^\Q$host\E\_/) {
                   2337:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2338:             return;
                   2339:         }
                   2340:         my $response = &get_query_reply($queryid);
                   2341:         my $maxtries = 5;
                   2342:         my $tries = 1;
                   2343:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2344:             $response = &get_query_reply($queryid);
                   2345:             $tries ++;
                   2346:         }
                   2347:         if (!&error($response) && $response ne 'refused') {
                   2348:             if ($response eq 'unavailable') {
                   2349:                 $outcome = $response;
                   2350:             } else {
                   2351:                 $outcome = 'ok';
                   2352:                 my @matches = split(/\n/,$response);
                   2353:                 foreach my $match (@matches) {
                   2354:                     my ($key,$value) = split(/=/,$match);
                   2355:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2356:                 }
                   2357:             }
                   2358:         }
                   2359:     }
                   2360:     my %userinfo;
                   2361:     if (ref($results{$uname}) eq 'HASH') {
                   2362:         %userinfo = %{$results{$uname}};
                   2363:     } 
                   2364:     return ($outcome,%userinfo);
                   2365: }
                   2366: 
1.1290    raeburn  2367: sub get_multiple_instusers {
                   2368:     my ($udom,$users,$caller) = @_;
                   2369:     my ($outcome,$results);
                   2370:     if (ref($users) eq 'HASH') {
                   2371:         my $count = keys(%{$users}); 
                   2372:         my $requested = &freeze_escape($users);
                   2373:         my $homeserver = &domain($udom,'primary');
                   2374:         if ($homeserver ne '') {
                   2375:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2376:             my $host=&hostname($homeserver);
                   2377:             if ($queryid !~/^\Q$host\E\_/) {
                   2378:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2379:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2380:                 return ($outcome,$results);
                   2381:             }
                   2382:             my $response = &get_query_reply($queryid);
                   2383:             my $maxtries = 5;
                   2384:             if ($count > 100) {
                   2385:                 $maxtries = 1+int($count/20);
                   2386:             }
                   2387:             my $tries = 1;
                   2388:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2389:                 $response = &get_query_reply($queryid);
                   2390:                 $tries ++;
                   2391:             }
                   2392:             if ($response eq '') {
                   2393:                 $results = {};
                   2394:                 foreach my $key (keys(%{$users})) {
                   2395:                     my ($uname,$id);
                   2396:                     if ($caller eq 'id') {
                   2397:                         $id = $key;
                   2398:                     } else {
                   2399:                         $uname = $key;
                   2400:                     }
                   2401:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2402:                     $outcome = $resp;
1.1290    raeburn  2403:                     if ($resp eq 'ok') {
                   2404:                         %{$results} = (%{$results}, %info);
                   2405:                     } else {
                   2406:                         last;
                   2407:                     }
                   2408:                 }
                   2409:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2410:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2411:                     $outcome = $response;
                   2412:                 } else {
1.1291    raeburn  2413:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2414:                     if ($outcome eq 'ok') {
                   2415:                         $results = &thaw_unescape($userdata); 
                   2416:                     }
                   2417:                 }
                   2418:             }
                   2419:         }
                   2420:     }
                   2421:     return ($outcome,$results);
                   2422: }
                   2423: 
1.912     raeburn  2424: sub inst_rulecheck {
1.923     raeburn  2425:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2426:     my %returnhash;
                   2427:     if ($udom ne '') {
                   2428:         if (ref($rules) eq 'ARRAY') {
                   2429:             @{$rules} = map {&escape($_);} (@{$rules});
                   2430:             my $rulestr = join(':',@{$rules});
                   2431:             my $homeserver=&domain($udom,'primary');
                   2432:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2433:                 my $response;
                   2434:                 if ($item eq 'username') {                
                   2435:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2436:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2437:                                               $homeserver));
1.923     raeburn  2438:                 } elsif ($item eq 'id') {
                   2439:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2440:                                               ':'.&escape($id).':'.$rulestr,
                   2441:                                               $homeserver));
1.945     raeburn  2442:                 } elsif ($item eq 'selfcreate') {
                   2443:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2444:                                                &escape($udom).':'.&escape($uname).
                   2445:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2446:                 }
1.912     raeburn  2447:                 if ($response ne 'refused') {
                   2448:                     my @pairs=split(/\&/,$response);
                   2449:                     foreach my $item (@pairs) {
                   2450:                         my ($key,$value)=split(/=/,$item,2);
                   2451:                         $key = &unescape($key);
                   2452:                         next if ($key =~ /^error: 2 /);
                   2453:                         $returnhash{$key}=&thaw_unescape($value);
                   2454:                     }
                   2455:                 }
                   2456:             }
                   2457:         }
                   2458:     }
                   2459:     return %returnhash;
                   2460: }
                   2461: 
                   2462: sub inst_userrules {
1.923     raeburn  2463:     my ($udom,$check) = @_;
1.912     raeburn  2464:     my (%ruleshash,@ruleorder);
                   2465:     if ($udom ne '') {
                   2466:         my $homeserver=&domain($udom,'primary');
                   2467:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2468:             my $response;
                   2469:             if ($check eq 'id') {
                   2470:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2471:                                  $homeserver);
1.943     raeburn  2472:             } elsif ($check eq 'email') {
                   2473:                 $response=&reply('instemailrules:'.&escape($udom),
                   2474:                                  $homeserver);
1.923     raeburn  2475:             } else {
                   2476:                 $response=&reply('instuserrules:'.&escape($udom),
                   2477:                                  $homeserver);
                   2478:             }
1.912     raeburn  2479:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2480:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2481:                 ($response ne 'no_such_host')) {
                   2482:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2483:                 my @pairs=split(/\&/,$hashitems);
                   2484:                 foreach my $item (@pairs) {
                   2485:                     my ($key,$value)=split(/=/,$item,2);
                   2486:                     $key = &unescape($key);
                   2487:                     next if ($key =~ /^error: 2 /);
                   2488:                     $ruleshash{$key}=&thaw_unescape($value);
                   2489:                 }
                   2490:                 my @esc_order = split(/\&/,$orderitems);
                   2491:                 foreach my $item (@esc_order) {
                   2492:                     push(@ruleorder,&unescape($item));
                   2493:                 }
                   2494:             }
                   2495:         }
                   2496:     }
                   2497:     return (\%ruleshash,\@ruleorder);
                   2498: }
                   2499: 
1.976     raeburn  2500: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2501: 
                   2502: sub get_domain_defaults {
1.1240    raeburn  2503:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2504:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2505:     my $cachetime = 60*60*24;
1.1240    raeburn  2506:     unless ($ignore_cache) {
                   2507:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2508:         if (defined($cached)) {
                   2509:             if (ref($result) eq 'HASH') {
                   2510:                 return %{$result};
                   2511:             }
1.943     raeburn  2512:         }
                   2513:     }
                   2514:     my %domdefaults;
                   2515:     my %domconfig =
1.989     raeburn  2516:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2517:                                   'requestcourses','inststatus',
1.1183    raeburn  2518:                                   'coursedefaults','usersessions',
1.1258    raeburn  2519:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2520:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2521:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2522:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2523:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2524:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2525:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2526:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2527:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2528:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2529:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2530:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2531:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2532:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2533:     } else {
                   2534:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2535:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2536:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2537:     }
1.976     raeburn  2538:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2539:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2540:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2541:         } else {
                   2542:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2543:         }
1.1177    raeburn  2544:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2545:         foreach my $item (@usertools) {
                   2546:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2547:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2548:             }
                   2549:         }
1.1229    raeburn  2550:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2551:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2552:         }
1.976     raeburn  2553:     }
1.985     raeburn  2554:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2555:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2556:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2557:         }
                   2558:     }
1.1183    raeburn  2559:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2560:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2561:     }
1.989     raeburn  2562:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2563:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2564:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2565:         }
                   2566:     }
1.1047    raeburn  2567:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2568:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2569:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2570:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2571:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2572:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2573:         }
1.1254    raeburn  2574:         foreach my $type (@coursetypes) {
                   2575:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2576:                 unless ($type eq 'community') {
                   2577:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2578:                 }
                   2579:             }
                   2580:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2581:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2582:             }
1.1277    raeburn  2583:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2584:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2585:                     $domdefaults{$type.'postsubtimeout'} = 
                   2586:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2587:                 }
                   2588:             }
1.1230    raeburn  2589:         }
1.1286    raeburn  2590:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2591:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2592:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2593:                 if (@clonecodes) {
                   2594:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2595:                 }
                   2596:             }
                   2597:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2598:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2599:         }
1.1356    raeburn  2600:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2601:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2602:         } 
1.1047    raeburn  2603:     }
1.1073    raeburn  2604:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2605:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2606:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2607:         }
                   2608:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2609:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2610:         }
1.1279    raeburn  2611:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2612:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2613:         }
1.1073    raeburn  2614:     }
1.1254    raeburn  2615:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2616:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2617:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2618:                             'approval','limit');
                   2619:             foreach my $type (@coursetypes) {
                   2620:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2621:                     my @mgrdc = ();
                   2622:                     foreach my $item (@settings) {
                   2623:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2624:                             push(@mgrdc,$item);
                   2625:                         }
                   2626:                     }
                   2627:                     if (@mgrdc) {
                   2628:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2629:                     }
                   2630:                 }
                   2631:             }
                   2632:         }
                   2633:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2634:             foreach my $type (@coursetypes) {
                   2635:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2636:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2637:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2638:                     }
                   2639:                 }
                   2640:             }
                   2641:         }
                   2642:     }
1.1258    raeburn  2643:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2644:         $domdefaults{'catauth'} = 'std';
                   2645:         $domdefaults{'catunauth'} = 'std';
                   2646:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2647:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2648:         }
                   2649:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2650:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2651:         }
                   2652:     }
1.1315    raeburn  2653:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2654:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2655:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2656:         }
1.1338    raeburn  2657:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2658:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2659:         }
                   2660:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2661:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2662:         }
                   2663:     }
1.1320    raeburn  2664:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2665:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2666:         foreach my $prefix (@prefixes) {
                   2667:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2668:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2669:             }
                   2670:         }
                   2671:     }
1.1314    raeburn  2672:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2673:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2674:     }
1.1332    raeburn  2675:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2676:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2677:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2678:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2679:         }
                   2680:     }
1.1219    raeburn  2681:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2682:     return %domdefaults;
                   2683: }
                   2684: 
1.1311    raeburn  2685: sub course_portal_url {
                   2686:     my ($cnum,$cdom) = @_;
                   2687:     my $chome = &homeserver($cnum,$cdom);
                   2688:     my $hostname = &hostname($chome);
                   2689:     my $protocol = $protocol{$chome};
                   2690:     $protocol = 'http' if ($protocol ne 'https');
                   2691:     my %domdefaults = &get_domain_defaults($cdom);
                   2692:     my $firsturl;
                   2693:     if ($domdefaults{'portal_def'}) {
                   2694:         $firsturl = $domdefaults{'portal_def'};
                   2695:     } else {
                   2696:         $firsturl = $protocol.'://'.$hostname;
                   2697:     }
                   2698:     return $firsturl;
                   2699: }
                   2700: 
1.344     www      2701: # --------------------------------------------------- Assign a key to a student
                   2702: 
                   2703: sub assign_access_key {
1.364     www      2704: #
                   2705: # a valid key looks like uname:udom#comments
                   2706: # comments are being appended
                   2707: #
1.498     www      2708:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2709:     $kdom=
1.620     albertel 2710:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2711:     $knum=
1.620     albertel 2712:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2713:     $cdom=
1.620     albertel 2714:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2715:     $cnum=
1.620     albertel 2716:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2717:     $udom=$env{'user.name'} unless (defined($udom));
                   2718:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2719:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2720:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2721:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2722:                                                   # assigned to this person
                   2723:                                                   # - this should not happen,
1.345     www      2724:                                                   # unless something went wrong
                   2725:                                                   # the first time around
                   2726: # ready to assign
1.364     www      2727:         $logentry=$1.'; '.$logentry;
1.496     www      2728:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2729:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2730: # key now belongs to user
1.346     www      2731: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2732:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2733:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2734:                 return 'ok';
                   2735:             } else {
                   2736:                 return 
                   2737:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2738: 	    }
                   2739:         } else {
                   2740:             return 'error: Could not assign key, try again later.';
                   2741:         }
1.364     www      2742:     } elsif (!$existing{$ckey}) {
1.345     www      2743: # the key does not exist
                   2744: 	return 'error: The key does not exist';
                   2745:     } else {
                   2746: # the key is somebody else's
                   2747: 	return 'error: The key is already in use';
                   2748:     }
1.344     www      2749: }
                   2750: 
1.364     www      2751: # ------------------------------------------ put an additional comment on a key
                   2752: 
                   2753: sub comment_access_key {
                   2754: #
                   2755: # a valid key looks like uname:udom#comments
                   2756: # comments are being appended
                   2757: #
                   2758:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2759:     $cdom=
1.620     albertel 2760:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2761:     $cnum=
1.620     albertel 2762:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2763:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2764:     if ($existing{$ckey}) {
                   2765:         $existing{$ckey}.='; '.$logentry;
                   2766: # ready to assign
1.367     www      2767:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2768:                                                  $cdom,$cnum) eq 'ok') {
                   2769: 	    return 'ok';
                   2770:         } else {
                   2771: 	    return 'error: Count not store comment.';
                   2772:         }
                   2773:     } else {
                   2774: # the key does not exist
                   2775: 	return 'error: The key does not exist';
                   2776:     }
                   2777: }
                   2778: 
1.344     www      2779: # ------------------------------------------------------ Generate a set of keys
                   2780: 
                   2781: sub generate_access_keys {
1.364     www      2782:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2783:     $cdom=
1.620     albertel 2784:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2785:     $cnum=
1.620     albertel 2786:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2787:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2788:     unless (($cdom) && ($cnum)) { return 0; }
                   2789:     if ($number>10000) { return 0; }
                   2790:     sleep(2); # make sure don't get same seed twice
                   2791:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2792:     my $total=0;
                   2793:     for (my $i=1;$i<=$number;$i++) {
                   2794:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2795:                   sprintf("%lx",int(100000*rand)).'-'.
                   2796:                   sprintf("%lx",int(100000*rand));
                   2797:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2798:        $newkey=~s/0/h/g; # and also 0 and O
                   2799:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2800:        if ($existing{$newkey}) {
                   2801:            $i--;
                   2802:        } else {
1.364     www      2803: 	  if (&put('accesskeys',
                   2804:               { $newkey => '# generated '.localtime().
1.620     albertel 2805:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2806:                            '; '.$logentry },
                   2807: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2808:               $total++;
                   2809: 	  }
                   2810:        }
                   2811:     }
1.620     albertel 2812:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2813:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2814:     return $total;
                   2815: }
                   2816: 
                   2817: # ------------------------------------------------------- Validate an accesskey
                   2818: 
                   2819: sub validate_access_key {
                   2820:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2821:     $cdom=
1.620     albertel 2822:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2823:     $cnum=
1.620     albertel 2824:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2825:     $udom=$env{'user.domain'} unless (defined($udom));
                   2826:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2827:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2828:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2829: }
                   2830: 
                   2831: # ------------------------------------- Find the section of student in a course
1.652     albertel 2832: sub devalidate_getsection_cache {
                   2833:     my ($udom,$unam,$courseid)=@_;
                   2834:     my $hashid="$udom:$unam:$courseid";
                   2835:     &devalidate_cache_new('getsection',$hashid);
                   2836: }
1.298     matthew  2837: 
1.815     albertel 2838: sub courseid_to_courseurl {
                   2839:     my ($courseid) = @_;
                   2840:     #already url style courseid
                   2841:     return $courseid if ($courseid =~ m{^/});
                   2842: 
                   2843:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2844: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2845: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2846: 	return "/$cdom/$cnum";
                   2847:     }
                   2848: 
                   2849:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2850:     if (exists($courseinfo{'num'})) {
                   2851: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2852:     }
                   2853: 
                   2854:     return undef;
                   2855: }
                   2856: 
1.298     matthew  2857: sub getsection {
                   2858:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2859:     my $cachetime=1800;
1.551     albertel 2860: 
                   2861:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2862:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2863:     if (defined($cached)) { return $result; }
                   2864: 
1.298     matthew  2865:     my %Pending; 
                   2866:     my %Expired;
                   2867:     #
                   2868:     # Each role can either have not started yet (pending), be active, 
                   2869:     #    or have expired.
                   2870:     #
                   2871:     # If there is an active role, we are done.
                   2872:     #
                   2873:     # If there is more than one role which has not started yet, 
                   2874:     #     choose the one which will start sooner
                   2875:     # If there is one role which has not started yet, return it.
                   2876:     #
                   2877:     # If there is more than one expired role, choose the one which ended last.
                   2878:     # If there is a role which has expired, return it.
                   2879:     #
1.815     albertel 2880:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2881:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2882:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2883:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2884:         my $section=$1;
                   2885:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2886:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2887:         my $now=time;
1.548     albertel 2888:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2889:             $Expired{$end}=$section;
                   2890:             next;
                   2891:         }
1.548     albertel 2892:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2893:             $Pending{$start}=$section;
                   2894:             next;
                   2895:         }
1.599     albertel 2896:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2897:     }
                   2898:     #
                   2899:     # Presumedly there will be few matching roles from the above
                   2900:     # loop and the sorting time will be negligible.
                   2901:     if (scalar(keys(%Pending))) {
                   2902:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2903:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2904:     } 
                   2905:     if (scalar(keys(%Expired))) {
                   2906:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2907:         my $time = pop(@sorted);
1.599     albertel 2908:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2909:     }
1.599     albertel 2910:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2911: }
1.70      www      2912: 
1.599     albertel 2913: sub save_cache {
                   2914:     &purge_remembered();
1.722     albertel 2915:     #&Apache::loncommon::validate_page();
1.620     albertel 2916:     undef(%env);
1.780     albertel 2917:     undef($env_loaded);
1.599     albertel 2918: }
1.452     albertel 2919: 
1.599     albertel 2920: my $to_remember=-1;
                   2921: my %remembered;
                   2922: my %accessed;
                   2923: my $kicks=0;
                   2924: my $hits=0;
1.849     albertel 2925: sub make_key {
                   2926:     my ($name,$id) = @_;
1.872     albertel 2927:     if (length($id) > 65 
                   2928: 	&& length(&escape($id)) > 200) {
                   2929: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2930:     }
1.849     albertel 2931:     return &escape($name.':'.$id);
                   2932: }
                   2933: 
1.599     albertel 2934: sub devalidate_cache_new {
                   2935:     my ($name,$id,$debug) = @_;
                   2936:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2937:     my $remembered_id=$name.':'.$id;
1.849     albertel 2938:     $id=&make_key($name,$id);
1.599     albertel 2939:     $memcache->delete($id);
1.1319    damieng  2940:     delete($remembered{$remembered_id});
                   2941:     delete($accessed{$remembered_id});
1.599     albertel 2942: }
                   2943: 
                   2944: sub is_cached_new {
                   2945:     my ($name,$id,$debug) = @_;
1.1319    damieng  2946:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2947:     if (exists($remembered{$remembered_id})) {
                   2948: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2949: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2950: 	$hits++;
1.1319    damieng  2951: 	return ($remembered{$remembered_id},1);
1.599     albertel 2952:     }
1.1319    damieng  2953:     $id=&make_key($name,$id);
1.599     albertel 2954:     my $value = $memcache->get($id);
                   2955:     if (!(defined($value))) {
                   2956: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2957: 	return (undef,undef);
1.416     albertel 2958:     }
1.599     albertel 2959:     if ($value eq '__undef__') {
                   2960: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2961: 	$value=undef;
                   2962:     }
1.1319    damieng  2963:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2964:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2965:     return ($value,1);
                   2966: }
                   2967: 
                   2968: sub do_cache_new {
                   2969:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2970:     my $remembered_id=$name.':'.$id;
1.849     albertel 2971:     $id=&make_key($name,$id);
1.599     albertel 2972:     my $setvalue=$value;
                   2973:     if (!defined($setvalue)) {
                   2974: 	$setvalue='__undef__';
                   2975:     }
1.623     albertel 2976:     if (!defined($time) ) {
                   2977: 	$time=600;
                   2978:     }
1.599     albertel 2979:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2980:     my $result = $memcache->set($id,$setvalue,$time);
                   2981:     if (! $result) {
1.872     albertel 2982: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2983: 	$memcache->disconnect_all();
1.872     albertel 2984:     }
1.600     albertel 2985:     # need to make a copy of $value
1.1319    damieng  2986:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2987:     return $value;
                   2988: }
                   2989: 
                   2990: sub make_room {
1.1319    damieng  2991:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2992: 
1.1319    damieng  2993:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2994:                                     : $value;
1.599     albertel 2995:     if ($to_remember<0) { return; }
1.1319    damieng  2996:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2997:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2998:     my $to_kick;
                   2999:     my $max_time=0;
                   3000:     foreach my $other (keys(%accessed)) {
                   3001: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3002: 	    $to_kick=$other;
                   3003: 	    $max_time=&tv_interval($accessed{$other});
                   3004: 	}
                   3005:     }
                   3006:     delete($remembered{$to_kick});
                   3007:     delete($accessed{$to_kick});
                   3008:     $kicks++;
                   3009:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3010:     return;
                   3011: }
                   3012: 
1.599     albertel 3013: sub purge_remembered {
1.604     albertel 3014:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3015:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3016:     undef(%remembered);
                   3017:     undef(%accessed);
1.428     albertel 3018: }
1.70      www      3019: # ------------------------------------- Read an entry from a user's environment
                   3020: 
                   3021: sub userenvironment {
                   3022:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3023:     my $items;
                   3024:     foreach my $item (@what) {
                   3025:         $items.=&escape($item).'&';
                   3026:     }
                   3027:     $items=~s/\&$//;
1.70      www      3028:     my %returnhash=();
1.1009    raeburn  3029:     my $uhome = &homeserver($unam,$udom);
                   3030:     unless ($uhome eq 'no_host') {
                   3031:         my @answer=split(/\&/, 
                   3032:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3033:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3034:             return %returnhash;
                   3035:         }
1.1009    raeburn  3036:         my $i;
                   3037:         for ($i=0;$i<=$#what;$i++) {
                   3038: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3039:         }
1.70      www      3040:     }
                   3041:     return %returnhash;
1.1       albertel 3042: }
                   3043: 
1.617     albertel 3044: # ---------------------------------------------------------- Get a studentphoto
                   3045: sub studentphoto {
                   3046:     my ($udom,$unam,$ext) = @_;
                   3047:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3048:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3049:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3050:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3051:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3052:             } else {
                   3053:                 my ($result,$perm_reqd)=
1.707     albertel 3054: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3055:                 if ($result eq 'ok') {
                   3056:                     if (!($perm_reqd eq 'yes')) {
                   3057:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3058:                     }
                   3059:                 }
                   3060:             }
                   3061:         }
                   3062:     } else {
                   3063:         my ($result,$perm_reqd) = 
1.707     albertel 3064: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3065:         if ($result eq 'ok') {
                   3066:             if (!($perm_reqd eq 'yes')) {
                   3067:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3068:             }
                   3069:         }
                   3070:     }
                   3071:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3072: }
                   3073: 
                   3074: sub retrievestudentphoto {
                   3075:     my ($udom,$unam,$ext,$type) = @_;
                   3076:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3077:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3078:     if ($ret eq 'ok') {
                   3079:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3080:         if ($type eq 'thumbnail') {
                   3081:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3082:         }
                   3083:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3084:         return $tokenurl;
                   3085:     } else {
                   3086:         if ($type eq 'thumbnail') {
                   3087:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3088:         } else { 
                   3089:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3090:         }
1.617     albertel 3091:     }
                   3092: }
                   3093: 
1.263     www      3094: # -------------------------------------------------------------------- New chat
                   3095: 
                   3096: sub chatsend {
1.724     raeburn  3097:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3098:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3099:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3100:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3101:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3102: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3103: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3104: }
                   3105: 
                   3106: # ------------------------------------------ Find current version of a resource
                   3107: 
                   3108: sub getversion {
                   3109:     my $fname=&clutter(shift);
1.1189    raeburn  3110:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3111:     return &currentversion(&filelocation('',$fname));
                   3112: }
                   3113: 
                   3114: sub currentversion {
                   3115:     my $fname=shift;
                   3116:     my $author=$fname;
                   3117:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3118:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3119:     my $home=&homeserver($uname,$udom);
1.292     www      3120:     if ($home eq 'no_host') { 
                   3121:         return -1; 
                   3122:     }
1.1112    www      3123:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3124:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3125: 	return -1;
                   3126:     }
1.1112    www      3127:     return $answer;
1.263     www      3128: }
                   3129: 
1.1111    www      3130: #
                   3131: # Return special version number of resource if set by override, empty otherwise
                   3132: #
                   3133: sub usedversion {
                   3134:     my $fname=shift;
                   3135:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3136:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3137:     if ($urlversion) { return $urlversion; }
                   3138:     return '';
                   3139: }
                   3140: 
1.1       albertel 3141: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3142: 
1.1       albertel 3143: sub subscribe {
                   3144:     my $fname=shift;
1.761     raeburn  3145:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3146:     $fname=~s/[\n\r]//g;
1.1       albertel 3147:     my $author=$fname;
                   3148:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3149:     my ($udom,$uname)=split(/\//,$author);
                   3150:     my $home=homeserver($uname,$udom);
1.335     albertel 3151:     if ($home eq 'no_host') {
                   3152:         return 'not_found';
1.1       albertel 3153:     }
                   3154:     my $answer=reply("sub:$fname",$home);
1.64      www      3155:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3156: 	$answer.=' by '.$home;
                   3157:     }
1.1       albertel 3158:     return $answer;
                   3159: }
                   3160:     
1.8       www      3161: # -------------------------------------------------------------- Replicate file
                   3162: 
                   3163: sub repcopy {
                   3164:     my $filename=shift;
1.23      www      3165:     $filename=~s/\/+/\//g;
1.1142    raeburn  3166:     my $londocroot = $perlvar{'lonDocRoot'};
                   3167:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3168:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3169:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3170: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3171: 	return &repcopy_userfile($filename);
                   3172:     }
1.532     albertel 3173:     $filename=~s/[\n\r]//g;
1.8       www      3174:     my $transname="$filename.in.transfer";
1.828     www      3175: # FIXME: this should flock
1.607     raeburn  3176:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3177:     my $remoteurl=subscribe($filename);
1.64      www      3178:     if ($remoteurl =~ /^con_lost by/) {
                   3179: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3180:            return 'unavailable';
1.8       www      3181:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3182: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3183: 	   return 'not_found';
1.64      www      3184:     } elsif ($remoteurl =~ /^rejected by/) {
                   3185: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3186:            return 'forbidden';
1.20      www      3187:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3188:            return 'ok';
1.8       www      3189:     } else {
1.290     www      3190:         my $author=$filename;
                   3191:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3192:         my ($udom,$uname)=split(/\//,$author);
                   3193:         my $home=homeserver($uname,$udom);
                   3194:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3195:            my @parts=split(/\//,$filename);
                   3196:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3197:            if ($path ne "$londocroot/res") {
1.8       www      3198:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3199: 	       return 'bad_request';
1.8       www      3200:            }
                   3201:            my $count;
                   3202:            for ($count=5;$count<$#parts;$count++) {
                   3203:                $path.="/$parts[$count]";
                   3204:                if ((-e $path)!=1) {
                   3205: 		   mkdir($path,0777);
                   3206:                }
                   3207:            }
                   3208:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3209:            my $response;
                   3210:            if ($remoteurl =~ m{/raw/}) {
                   3211:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3212:            } else {
                   3213:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3214:            }
1.8       www      3215:            if ($response->is_error()) {
                   3216: 	       unlink($transname);
                   3217:                my $message=$response->status_line;
1.672     albertel 3218:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3219:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3220:                return 'unavailable';
1.8       www      3221:            } else {
1.16      www      3222: 	       if ($remoteurl!~/\.meta$/) {
                   3223:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3224:                   my $mresponse;
                   3225:                   if ($remoteurl =~ m{/raw/}) {
                   3226:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3227:                   } else {
                   3228:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3229:                   }
1.16      www      3230:                   if ($mresponse->is_error()) {
                   3231: 		      unlink($filename.'.meta');
                   3232:                       &logthis(
1.672     albertel 3233:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3234:                   }
                   3235: 	       }
1.8       www      3236:                rename($transname,$filename);
1.607     raeburn  3237:                return 'ok';
1.8       www      3238:            }
1.290     www      3239:        }
1.8       www      3240:     }
1.330     www      3241: }
                   3242: 
                   3243: # ------------------------------------------------ Get server side include body
                   3244: sub ssi_body {
1.381     albertel 3245:     my ($filelink,%form)=@_;
1.606     matthew  3246:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3247:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3248:     }
1.953     www      3249:     my $output='';
                   3250:     my $response;
1.980     raeburn  3251:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3252:        ($output,$response)=&externalssi($filelink);
1.953     www      3253:     } else {
1.1004    droeschl 3254:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3255:        $filelink .= 'inhibitmenu=yes';
1.953     www      3256:        ($output,$response)=&ssi($filelink,%form);
                   3257:     }
1.778     albertel 3258:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3259:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3260:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3261:     if (wantarray) {
                   3262:         return ($output, $response);
                   3263:     } else {
                   3264:         return $output;
                   3265:     }
1.8       www      3266: }
                   3267: 
1.15      www      3268: # --------------------------------------------------------- Server Side Include
                   3269: 
1.782     albertel 3270: sub absolute_url {
                   3271:     my ($host_name) = @_;
                   3272:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3273:     if ($host_name eq '') {
                   3274: 	$host_name = $ENV{'SERVER_NAME'};
                   3275:     }
                   3276:     return $protocol.$host_name;
                   3277: }
                   3278: 
1.942     foxr     3279: #
                   3280: #   Server side include.
                   3281: # Parameters:
                   3282: #  fn     Possibly encrypted resource name/id.
                   3283: #  form   Hash that describes how the rendering should be done
                   3284: #         and other things.
1.944     foxr     3285: # Returns:
1.950     raeburn  3286: #   Scalar context: The content of the response.
                   3287: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3288: #     
1.15      www      3289: sub ssi {
                   3290: 
1.944     foxr     3291:     my ($fn,%form)=@_;
1.23      www      3292:     my $request;
1.711     albertel 3293: 
                   3294:     $form{'no_update_last_known'}=1;
1.895     albertel 3295:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3296:     if (%form) {
1.782     albertel 3297:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3298:       $request->content(join('&',map { 
                   3299:             my $name = escape($_);
                   3300:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3301:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3302:             : &escape($form{$_}) );    
                   3303:         } keys(%form)));
1.23      www      3304:     } else {
1.782     albertel 3305:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3306:     }
                   3307: 
1.15      www      3308:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3309:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3310:     my $islocal;
                   3311:     if (($env{'request.course.id'}) &&
                   3312:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3313:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3314:         ($form{'grade_symb'} ne '') &&
                   3315:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3316:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3317:         $islocal = 1;
                   3318:     }
1.1384    raeburn  3319:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3320:                                                 '','','',$islocal);
1.1182    foxr     3321: 
1.944     foxr     3322:     if (wantarray) {
1.1345    raeburn  3323: 	return ($response->content, $response);
1.944     foxr     3324:     } else {
1.1345    raeburn  3325: 	return $response->content;
1.942     foxr     3326:     }
1.324     www      3327: }
                   3328: 
                   3329: sub externalssi {
                   3330:     my ($url)=@_;
                   3331:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3332:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3333:     if (wantarray) {
                   3334:         return ($response->content, $response);
                   3335:     } else {
                   3336:         return $response->content;
                   3337:     }
1.15      www      3338: }
1.254     www      3339: 
1.1354    raeburn  3340: 
                   3341: # If the local copy of a replicated resource is outdated, trigger a  
                   3342: # connection from the homeserver to flush the delayed queue. If no update 
                   3343: # happens, remove local copies of outdated resource (and corresponding
                   3344: # metadata file).
                   3345: 
1.1352    raeburn  3346: sub remove_stale_resfile {
                   3347:     my ($url) = @_;
1.1354    raeburn  3348:     my $removed;
1.1352    raeburn  3349:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3350:         my $audom = $1;
                   3351:         my $auname = $2;
1.1353    raeburn  3352:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3353:             my $homeserver = &homeserver($auname,$audom);
                   3354:             unless (($homeserver eq 'no_host') ||
                   3355:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3356:                 my $fname = &filelocation('',$url);
                   3357:                 if (-e $fname) {
                   3358:                     my $protocol = $protocol{$homeserver};
                   3359:                     $protocol = 'http' if ($protocol ne 'https');
                   3360:                     my $hostname = &hostname($homeserver);
                   3361:                     if ($hostname) {
                   3362:                         my $uri = &declutter($url);
                   3363:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3364:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3365:                         if ($response->is_success()) {
                   3366:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3367:                             my $locmodtime = (stat($fname))[9];
                   3368:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3369:                                 my $stale;
                   3370:                                 my $answer = &reply('pong',$homeserver);
                   3371:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3372:                                     sleep(0.2);
                   3373:                                     $locmodtime = (stat($fname))[9];
                   3374:                                     if ($locmodtime < $remmodtime) {
                   3375:                                         my $posstransfer = $fname.'.in.transfer';
                   3376:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3377:                                             $removed = 1;
                   3378:                                         } else {
                   3379:                                             $stale = 1;
                   3380:                                         }
                   3381:                                     } else {
                   3382:                                         $removed = 1;
                   3383:                                     }
                   3384:                                 } else {
                   3385:                                     $stale = 1;
                   3386:                                 }
                   3387:                                 if ($stale) {
                   3388:                                     unlink($fname);
                   3389:                                     if ($uri!~/\.meta$/) {
                   3390:                                         unlink($fname.'.meta');
                   3391:                                     }
                   3392:                                     &reply("unsub:$fname",$homeserver);
                   3393:                                     $removed = 1;
1.1352    raeburn  3394:                                 }
                   3395:                             }
                   3396:                         }
                   3397:                     }
                   3398:                 }
                   3399:             }
                   3400:         }
                   3401:     }
1.1354    raeburn  3402:     return $removed;
1.1352    raeburn  3403: }
                   3404: 
1.492     albertel 3405: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3406: 
                   3407: sub allowuploaded {
                   3408:     my ($srcurl,$url)=@_;
                   3409:     $url=&clutter(&declutter($url));
                   3410:     my $dir=$url;
                   3411:     $dir=~s/\/[^\/]+$//;
                   3412:     my %httpref=();
                   3413:     my $httpurl=&hreflocation('',$url);
                   3414:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3415:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3416: }
1.477     raeburn  3417: 
1.1193    raeburn  3418: #
                   3419: # Determine if the current user should be able to edit a particular resource,
                   3420: # when viewing in course context.
                   3421: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3422: #     Functions.
                   3423: # (b) When displaying folder contents in course editor, used to determine if
                   3424: #     "Edit" link will be displayed alongside resource.
                   3425: #
1.1196    raeburn  3426: #  input: six args -- filename (decluttered), course number, course domain,
                   3427: #                   url, symb (if registered) and group (if this is a group
                   3428: #                   item -- e.g., bulletin board, group page etc.).
                   3429: #  output: array of five scalars -- 
1.1193    raeburn  3430: #          $cfile -- url for file editing if editable on current server
                   3431: #          $home -- homeserver of resource (i.e., for author if published,
                   3432: #                                           or course if uploaded.).
                   3433: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3434: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3435: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3436: #
                   3437: 
                   3438: sub can_edit_resource {
1.1194    raeburn  3439:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3440:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3441: #
                   3442: # For aboutme pages user can only edit his/her own.
                   3443: #
1.1199    raeburn  3444:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3445:         my ($sdom,$sname) = ($1,$2);
                   3446:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3447:             $home = $env{'user.home'};
                   3448:             $cfile = $resurl;
                   3449:             if ($env{'form.forceedit'}) {
                   3450:                 $forceview = 1;
                   3451:             } else {
                   3452:                 $forceedit = 1;
                   3453:             }
                   3454:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3455:         } else {
                   3456:             return;
                   3457:         }
                   3458:     }
                   3459: 
                   3460:     if ($env{'request.course.id'}) {
                   3461:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3462:         if ($group ne '') {
                   3463: # if this is a group homepage or group bulletin board, check group privs
                   3464:             my $allowed = 0;
1.1197    raeburn  3465:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3466:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3467:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3468:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3469:                     $allowed = 1;
                   3470:                 }
1.1197    raeburn  3471:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3472:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3473:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3474:                     $allowed = 1;
                   3475:                 }
                   3476:             }
                   3477:             if ($allowed) {
                   3478:                 $home=&homeserver($cnum,$cdom);
                   3479:                 if ($env{'form.forceedit'}) {
                   3480:                     $forceview = 1;
                   3481:                 } else {
                   3482:                     $forceedit = 1;
                   3483:                 }
                   3484:                 $cfile = $resurl;
                   3485:             } else {
                   3486:                 return;
                   3487:             }
                   3488:         } else {
1.1208    raeburn  3489:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3490:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3491:                     return;
                   3492:                 }
                   3493:             } elsif (!$crsedit) {
1.1194    raeburn  3494: #
                   3495: # No edit allowed where CC has switched to student role.
                   3496: #
                   3497:                 return;
                   3498:             }
                   3499:         }
                   3500:     }
                   3501: 
1.1193    raeburn  3502:     if ($file ne '') {
                   3503:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3504:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3505:                 $uploaded = 1;
                   3506:                 $incourse = 1;
1.1193    raeburn  3507:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3508:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3509:                     if ($env{'form.forceedit'}) {
                   3510:                         $forceview = 1;
                   3511:                     } else {
                   3512:                         $forceedit = 1;
                   3513:                     }
1.1194    raeburn  3514:                 }
                   3515:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3516:                 $incourse = 1;
                   3517:                 if ($env{'form.forceedit'}) {
                   3518:                     $forceview = 1;
                   3519:                 } else {
                   3520:                     $forceedit = 1;
                   3521:                 }
                   3522:                 $cfile = $resurl;
                   3523:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3524:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3525:                     $incourse = 1;
                   3526:                     if ($env{'form.forceedit'}) {
                   3527:                         $forceview = 1;
                   3528:                     } else {
                   3529:                         $forceedit = 1;
                   3530:                     }
                   3531:                     $cfile = $resurl;
1.1199    raeburn  3532:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3533:                     $incourse = 1;
                   3534:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3535:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3536:                     $incourse = 1;
1.1199    raeburn  3537:                     if ($env{'form.forceedit'}) {
                   3538:                         $forceview = 1;
                   3539:                     } else {
                   3540:                         $forceedit = 1;
                   3541:                     }
                   3542:                     $cfile = $resurl;
1.1343    raeburn  3543:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3544:                     $incourse = 1;
                   3545:                     if ($env{'form.forceedit'}) {
                   3546:                         $forceview = 1;
                   3547:                     } else {
                   3548:                         $forceedit = 1;
                   3549:                     }
                   3550:                     $cfile = $resurl;
1.1208    raeburn  3551:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3552:                     $incourse = 1;
                   3553:                     if ($env{'form.forceedit'}) {
                   3554:                         $forceview = 1;
                   3555:                     } else {
                   3556:                         $forceedit = 1;
                   3557:                     }
                   3558:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3559:                 }
                   3560:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3561:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3562:                 if (&is_on_map($template)) { 
                   3563:                     $incourse = 1;
                   3564:                     $forceview = 1;
                   3565:                     $cfile = $template;
1.1193    raeburn  3566:                 }
1.1199    raeburn  3567:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3568:                     $incourse = 1;
                   3569:                     if ($env{'form.forceedit'}) {
                   3570:                         $forceview = 1;
                   3571:                     } else {
                   3572:                         $forceedit = 1;
                   3573:                     }
                   3574:                     $cfile = $resurl;
1.1343    raeburn  3575:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3576:                 $incourse = 1;
                   3577:                 if ($env{'form.forceedit'}) {
                   3578:                     $forceview = 1;
                   3579:                 } else {
                   3580:                     $forceedit = 1;
                   3581:                 }
                   3582:                 $cfile = $resurl;
1.1199    raeburn  3583:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3584:                 $incourse = 1;
                   3585:                 $forceview = 1;
                   3586:                 if ($symb) {
                   3587:                     my ($map,$id,$res)=&decode_symb($symb);
                   3588:                     $env{'request.symb'} = $symb;
                   3589:                     $cfile = &clutter($res);
                   3590:                 } else {
                   3591:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3592:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3593:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3594:                         $cfile = '/adm/wrapper'.$escfile;
                   3595:                     } else {
                   3596:                         $escfile =~ s{^http://}{};
                   3597:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3598:                     }
1.1199    raeburn  3599:                 }
1.1234    raeburn  3600:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3601:                 if ($env{'form.forceedit'}) {
                   3602:                     $forceview = 1;
                   3603:                 } else {
                   3604:                     $forceedit = 1;
                   3605:                 }
                   3606:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3607:             }
                   3608:         }
1.1194    raeburn  3609:         if ($uploaded || $incourse) {
                   3610:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3611:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3612:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3613:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3614:             # Check that the user has permission to edit this resource
                   3615:             my $setpriv = 1;
                   3616:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3617:             if (defined($cfudom)) {
                   3618:                 $home=&homeserver($cfuname,$cfudom);
                   3619:                 $cfile=$file;
                   3620:             }
                   3621:         }
1.1194    raeburn  3622:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3623:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3624:             my @ids=&current_machine_ids();
                   3625:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3626:                 $switchserver=1;
                   3627:             }
                   3628:         }
                   3629:     }
1.1194    raeburn  3630:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3631: }
                   3632: 
                   3633: sub is_course_upload {
                   3634:     my ($file,$cnum,$cdom) = @_;
                   3635:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3636:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3637:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3638:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3639:         return 1;
                   3640:     }
                   3641:     return;
                   3642: }
                   3643: 
1.1194    raeburn  3644: sub in_course {
1.1195    raeburn  3645:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3646:     if ($hideprivileged) {
                   3647:         my $skipuser;
1.1219    raeburn  3648:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3649:         my @possdoms = ($cdom);  
                   3650:         if ($coursehash{'checkforpriv'}) { 
                   3651:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3652:         }
                   3653:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3654:             $skipuser = 1;
                   3655:             if ($coursehash{'nothideprivileged'}) {
                   3656:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3657:                     my $user;
                   3658:                     if ($item =~ /:/) {
                   3659:                         $user = $item;
                   3660:                     } else {
                   3661:                         $user = join(':',split(/[\@]/,$item));
                   3662:                     }
                   3663:                     if ($user eq $uname.':'.$udom) {
                   3664:                         undef($skipuser);
                   3665:                         last;
                   3666:                     }
                   3667:                 }
                   3668:             }
                   3669:             if ($skipuser) {
                   3670:                 return 0;
                   3671:             }
                   3672:         }
                   3673:     }
1.1194    raeburn  3674:     $type ||= 'any';
                   3675:     if (!defined($cdom) || !defined($cnum)) {
                   3676:         my $cid  = $env{'request.course.id'};
                   3677:         $cdom = $env{'course.'.$cid.'.domain'};
                   3678:         $cnum = $env{'course.'.$cid.'.num'};
                   3679:     }
                   3680:     my $typesref;
1.1195    raeburn  3681:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3682:         $typesref = ['active','previous','future'];
                   3683:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3684:         $typesref = [$type];
                   3685:     }
                   3686:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3687:                               $typesref,undef,[$cdom]);
                   3688:     my ($tmp) = keys(%roles);
                   3689:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3690:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3691:     if (@course_roles > 0) {
                   3692:         return 1;
                   3693:     }
                   3694:     return 0;
                   3695: }
                   3696: 
1.478     albertel 3697: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3698: # input: action, courseID, current domain, intended
1.637     raeburn  3699: #        path to file, source of file, instruction to parse file for objects,
                   3700: #        ref to hash for embedded objects,
                   3701: #        ref to hash for codebase of java objects.
1.1095    raeburn  3702: #        reference to scalar to accommodate mime type determined
                   3703: #          from File::MMagic if $parser = parse.
1.637     raeburn  3704: #
1.485     raeburn  3705: # output: url to file (if action was uploaddoc), 
                   3706: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3707: #
1.478     albertel 3708: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3709: # course.
1.477     raeburn  3710: #
1.478     albertel 3711: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3712: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3713: #          course's home server.
1.477     raeburn  3714: #
1.478     albertel 3715: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3716: #          be copied from $source (current location) to 
                   3717: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3718: #         and will then be copied to
                   3719: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3720: #         course's home server.
1.485     raeburn  3721: #
1.481     raeburn  3722: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3723: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3724: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3725: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3726: #         in course's home server.
1.637     raeburn  3727: #
1.477     raeburn  3728: 
                   3729: sub process_coursefile {
1.1095    raeburn  3730:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3731:         $mimetype)=@_;
1.477     raeburn  3732:     my $fetchresult;
1.638     albertel 3733:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3734:     if ($action eq 'propagate') {
1.638     albertel 3735:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3736: 			     $home);
1.481     raeburn  3737:     } else {
1.477     raeburn  3738:         my $fpath = '';
                   3739:         my $fname = $file;
1.478     albertel 3740:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3741:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3742:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3743:         if ($action eq 'copy') {
                   3744:             if ($source eq '') {
                   3745:                 $fetchresult = 'no source file';
                   3746:                 return $fetchresult;
                   3747:             } else {
                   3748:                 my $destination = $filepath.'/'.$fname;
                   3749:                 rename($source,$destination);
                   3750:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3751:                                  $home);
1.481     raeburn  3752:             }
                   3753:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3754:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3755:             print $fh $env{'form.'.$source};
1.481     raeburn  3756:             close($fh);
1.637     raeburn  3757:             if ($parser eq 'parse') {
1.1024    raeburn  3758:                 my $mm = new File::MMagic;
1.1095    raeburn  3759:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3760:                 if ($type eq 'text/html') {
1.1024    raeburn  3761:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3762:                     unless ($parse_result eq 'ok') {
                   3763:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3764:                     }
1.637     raeburn  3765:                 }
1.1095    raeburn  3766:                 if (ref($mimetype)) {
                   3767:                     $$mimetype = $type;
                   3768:                 } 
1.637     raeburn  3769:             }
1.477     raeburn  3770:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3771:                                  $home);
1.481     raeburn  3772:             if ($fetchresult eq 'ok') {
                   3773:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3774:             } else {
                   3775:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3776:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3777:                 return '/adm/notfound.html';
                   3778:             }
1.477     raeburn  3779:         }
                   3780:     }
1.485     raeburn  3781:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3782:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3783:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3784:     }
                   3785:     return $fetchresult;
                   3786: }
                   3787: 
1.637     raeburn  3788: sub build_filepath {
                   3789:     my ($fpath) = @_;
                   3790:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3791:     unless ($fpath eq '') {
                   3792:         my @parts=split('/',$fpath);
                   3793:         foreach my $part (@parts) {
                   3794:             $filepath.= '/'.$part;
                   3795:             if ((-e $filepath)!=1) {
                   3796:                 mkdir($filepath,0777);
                   3797:             }
                   3798:         }
                   3799:     }
                   3800:     return $filepath;
                   3801: }
                   3802: 
                   3803: sub store_edited_file {
1.638     albertel 3804:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3805:     my $file = $primary_url;
                   3806:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3807:     my $fpath = '';
                   3808:     my $fname = $file;
                   3809:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3810:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3811:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3812:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3813:     print $fh $content;
                   3814:     close($fh);
1.638     albertel 3815:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3816:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3817: 			  $home);
1.637     raeburn  3818:     if ($$fetchresult eq 'ok') {
                   3819:         return '/uploaded/'.$fpath.'/'.$fname;
                   3820:     } else {
1.638     albertel 3821:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3822: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3823:         return '/adm/notfound.html';
                   3824:     }
                   3825: }
                   3826: 
1.531     albertel 3827: sub clean_filename {
1.831     albertel 3828:     my ($fname,$args)=@_;
1.315     www      3829: # Replace Windows backslashes by forward slashes
1.257     www      3830:     $fname=~s/\\/\//g;
1.831     albertel 3831:     if (!$args->{'keep_path'}) {
                   3832:         # Get rid of everything but the actual filename
                   3833: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3834:     }
1.315     www      3835: # Replace spaces by underscores
                   3836:     $fname=~s/\s+/\_/g;
                   3837: # Replace all other weird characters by nothing
1.831     albertel 3838:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3839: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3840: # numbers
                   3841:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3842:     return $fname;
                   3843: }
1.1051    raeburn  3844: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3845: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3846: # image with the same aspect ratio as the original, but with dimensions which do 
                   3847: # not exceed $resizewidth and $resizeheight.
                   3848:  
1.984     neumanie 3849: sub resizeImage {
1.1051    raeburn  3850:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3851:     my $ima = Image::Magick->new;
                   3852:     my $resized;
                   3853:     if (-e $img_path) {
                   3854:         $ima->Read($img_path);
                   3855:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3856:             my $width = $ima->Get('width');
                   3857:             my $height = $ima->Get('height');
                   3858:             if ($width > $resizewidth) {
                   3859: 	        my $factor = $width/$resizewidth;
                   3860:                 my $newheight = $height/$factor;
                   3861:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3862:                 $resized = 1;
                   3863:             }
                   3864:         }
                   3865:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3866:             my $width = $ima->Get('width');
                   3867:             my $height = $ima->Get('height');
                   3868:             if ($height > $resizeheight) {
                   3869:                 my $factor = $height/$resizeheight;
                   3870:                 my $newwidth = $width/$factor;
                   3871:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3872:                 $resized = 1;
                   3873:             }
                   3874:         }
                   3875:         if ($resized) {
                   3876:             $ima->Write($img_path);
                   3877:         }
                   3878:     }
                   3879:     return;
1.977     amueller 3880: }
                   3881: 
1.608     albertel 3882: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3883: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3884: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3885: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3886: #                                    canceloverwrite, or ''. 
                   3887: #                   if 'coursedoc': upload to the current course
                   3888: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3889: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3890: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3891: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3892: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3893: #        $allfiles - reference to hash for embedded objects
                   3894: #        $codebase - reference to hash for codebase of java objects
                   3895: #        $desuname - username for permanent storage of uploaded file
                   3896: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3897: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3898: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3899: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3900: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3901: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3902: #                    from File::MMagic.
1.858     raeburn  3903: # 
1.686     albertel 3904: # output: url of file in userspace, or error: <message> 
                   3905: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3906: 
1.531     albertel 3907: sub userfileupload {
1.1090    raeburn  3908:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3909:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3910:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3911:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3912:     $fname=&clean_filename($fname);
1.1090    raeburn  3913:     # See if there is anything left
1.257     www      3914:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3915:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3916:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3917:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3918:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3919:         my $now = time;
1.1090    raeburn  3920:         my $filepath;
1.1095    raeburn  3921:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3922:              $filepath = 'tmp/helprequests/'.$now;
                   3923:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3924:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3925:                          '_'.$env{'user.domain'}.'/pending';
                   3926:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3927:             my ($docuname,$docudom);
1.1350    raeburn  3928:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3929:                 $docudom = $destudom;
                   3930:             } else {
                   3931:                 $docudom = $env{'user.domain'};
                   3932:             }
1.1350    raeburn  3933:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3934:                 $docuname = $destuname;
                   3935:             } else {
                   3936:                 $docuname = $env{'user.name'};
                   3937:             }
                   3938:             if (exists($env{'form.group'})) {
                   3939:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3940:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3941:             }
                   3942:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3943:             if ($context eq 'canceloverwrite') {
                   3944:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3945:                 if (-e  $tempfile) {
                   3946:                     my @info = stat($tempfile);
                   3947:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3948:                         unlink($tempfile);
                   3949:                     }
                   3950:                 }
                   3951:                 return;
1.523     raeburn  3952:             }
                   3953:         }
1.1090    raeburn  3954:         # Create the directory if not present
1.741     raeburn  3955:         my @parts=split(/\//,$filepath);
                   3956:         my $fullpath = $perlvar{'lonDaemons'};
                   3957:         for (my $i=0;$i<@parts;$i++) {
                   3958:             $fullpath .= '/'.$parts[$i];
                   3959:             if ((-e $fullpath)!=1) {
                   3960:                 mkdir($fullpath,0777);
                   3961:             }
                   3962:         }
1.1359    raeburn  3963:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3964:         print $fh $env{'form.'.$formname};
                   3965:         close($fh);
1.1090    raeburn  3966:         if ($context eq 'existingfile') {
                   3967:             my @info = stat($fullpath.'/'.$fname);
                   3968:             return ($fullpath.'/'.$fname,$info[9]);
                   3969:         } else {
                   3970:             return $fullpath.'/'.$fname;
                   3971:         }
1.523     raeburn  3972:     }
1.995     raeburn  3973:     if ($subdir eq 'scantron') {
                   3974:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3975:     } else {
1.995     raeburn  3976:         $fname="$subdir/$fname";
                   3977:     }
1.1090    raeburn  3978:     if ($context eq 'coursedoc') {
1.638     albertel 3979: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3980: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3981:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3982:             return &finishuserfileupload($docuname,$docudom,
                   3983: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3984: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3985:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3986:         } else {
1.1218    raeburn  3987:             if ($env{'form.folder'}) {
                   3988:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3989:             }
1.638     albertel 3990:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3991: 				       $fname,$formname,$parser,
1.1095    raeburn  3992: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3993:         }
1.719     banghart 3994:     } elsif (defined($destuname)) {
                   3995:         my $docuname=$destuname;
                   3996:         my $docudom=$destudom;
1.860     raeburn  3997: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3998: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3999:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4000:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4001:     } else {
1.638     albertel 4002:         my $docuname=$env{'user.name'};
                   4003:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4004:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4005:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4006:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4007:         }
1.860     raeburn  4008: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4009: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4010:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4011:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4012:     }
1.271     www      4013: }
                   4014: 
                   4015: sub finishuserfileupload {
1.860     raeburn  4016:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4017:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4018:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4019:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4020:   
1.860     raeburn  4021:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4022:     $file=$fname;
                   4023:     if ($fname=~m|/|) {
                   4024:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4025: 	$path.=$fnamepath.'/';
                   4026:     }
1.259     www      4027:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4028:     my $count;
                   4029:     for ($count=4;$count<=$#parts;$count++) {
                   4030:         $filepath.="/$parts[$count]";
                   4031:         if ((-e $filepath)!=1) {
                   4032: 	    mkdir($filepath,0777);
                   4033:         }
                   4034:     }
1.984     neumanie 4035: 
1.258     www      4036: # Save the file
                   4037:     {
1.1359    raeburn  4038: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4039: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4040: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4041: 	    return '/adm/notfound.html';
                   4042: 	}
1.1090    raeburn  4043:         if ($context eq 'overwrite') {
1.1117    foxr     4044:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4045:             my $target = $filepath.'/'.$file;
                   4046:             if (-e $source) {
                   4047:                 my @info = stat($source);
                   4048:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4049:                     unless (&File::Copy::move($source,$target)) {
                   4050:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4051:                         return "Moving from $source failed";
                   4052:                     }
                   4053:                 } else {
                   4054:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4055:                 }
                   4056:             } else {
                   4057:                 return "Temporary file: $source missing";
                   4058:             }
                   4059:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4060: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4061: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4062: 	    return '/adm/notfound.html';
                   4063: 	}
1.570     albertel 4064: 	close(FH);
1.1051    raeburn  4065:         if ($resizewidth && $resizeheight) {
                   4066:             my $mm = new File::MMagic;
                   4067:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4068:             if ($mime_type =~ m{^image/}) {
                   4069: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4070:             }  
1.977     amueller 4071: 	}
1.258     www      4072:     }
1.1152    raeburn  4073:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4074:         if (ref($mimetype)) {
                   4075:             if ($$mimetype eq '') {
                   4076:                 my $mm = new File::MMagic;
                   4077:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4078:                 $$mimetype = $type;
                   4079:             }
                   4080:         }
                   4081:     }
1.637     raeburn  4082:     if ($parser eq 'parse') {
1.1152    raeburn  4083:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4084:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4085:                                                        $allfiles,$codebase);
                   4086:             unless ($parse_result eq 'ok') {
                   4087:                 &logthis('Failed to parse '.$filepath.$file.
                   4088: 	   	         ' for embedded media: '.$parse_result); 
                   4089:             }
1.637     raeburn  4090:         }
                   4091:     }
1.860     raeburn  4092:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4093:         my $input = $filepath.'/'.$file;
                   4094:         my $output = $filepath.'/'.'tn-'.$file;
                   4095:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4096:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4097:         system({$args[0]} @args);
1.860     raeburn  4098:         if (-e $filepath.'/'.'tn-'.$file) {
                   4099:             $fetchthumb  = 1; 
                   4100:         }
                   4101:     }
1.858     raeburn  4102:  
1.259     www      4103: # Notify homeserver to grep it
                   4104: #
1.984     neumanie 4105:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4106:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4107:     if ($fetchresult eq 'ok') {
1.860     raeburn  4108:         if ($fetchthumb) {
                   4109:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4110:             if ($thumbresult ne 'ok') {
                   4111:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4112:                          $docuhome.': '.$thumbresult);
                   4113:             }
                   4114:         }
1.259     www      4115: #
1.258     www      4116: # Return the URL to it
1.494     albertel 4117:         return '/uploaded/'.$path.$file;
1.263     www      4118:     } else {
1.494     albertel 4119:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4120: 		 ': '.$fetchresult);
1.263     www      4121:         return '/adm/notfound.html';
1.858     raeburn  4122:     }
1.493     albertel 4123: }
                   4124: 
1.637     raeburn  4125: sub extract_embedded_items {
1.961     raeburn  4126:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4127:     my @state = ();
1.1164    raeburn  4128:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4129:     my %javafiles = (
                   4130:                       codebase => '',
                   4131:                       code => '',
                   4132:                       archive => ''
                   4133:                     );
                   4134:     my %mediafiles = (
                   4135:                       src => '',
                   4136:                       movie => '',
                   4137:                      );
1.648     raeburn  4138:     my $p;
                   4139:     if ($content) {
                   4140:         $p = HTML::LCParser->new($content);
                   4141:     } else {
1.961     raeburn  4142:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4143:     }
1.641     albertel 4144:     while (my $t=$p->get_token()) {
1.640     albertel 4145: 	if ($t->[0] eq 'S') {
                   4146: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4147: 	    push(@state, $tagname);
1.648     raeburn  4148:             if (lc($tagname) eq 'allow') {
                   4149:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4150:             }
1.640     albertel 4151: 	    if (lc($tagname) eq 'img') {
                   4152: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4153: 	    }
1.886     albertel 4154: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4155:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4156:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4157:                 }
1.886     albertel 4158: 	    }
1.645     raeburn  4159:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4160:                 my $src;
1.645     raeburn  4161:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4162:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4163:                 } else {
1.1164    raeburn  4164:                     if ($attr->{'src'} ne '') {
                   4165:                         $src = $attr->{'src'};
                   4166:                         &add_filetype($allfiles,$src,'src');
                   4167:                     }
                   4168:                 }
                   4169:                 my $text = $p->get_trimmed_text();
                   4170:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4171:                     my @swfargs = split(/,/,$1);
                   4172:                     foreach my $item (@swfargs) {
                   4173:                         $item =~ s/["']//g;
                   4174:                         $item =~ s/^\s+//;
                   4175:                         $item =~ s/\s+$//;
                   4176:                     }
                   4177:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4178:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4179:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4180:                         } else {
                   4181:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4182:                         }
                   4183:                     }
1.645     raeburn  4184:                 }
                   4185:             }
                   4186:             if (lc($tagname) eq 'link') {
                   4187:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4188:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4189:                 }
                   4190:             }
1.640     albertel 4191: 	    if (lc($tagname) eq 'object' ||
                   4192: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4193: 		foreach my $item (keys(%javafiles)) {
                   4194: 		    $javafiles{$item} = '';
                   4195: 		}
1.1164    raeburn  4196:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4197:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4198:                 }
1.640     albertel 4199: 	    }
                   4200: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4201: 		my $name = lc($attr->{'name'});
                   4202: 		foreach my $item (keys(%javafiles)) {
                   4203: 		    if ($name eq $item) {
                   4204: 			$javafiles{$item} = $attr->{'value'};
                   4205: 			last;
                   4206: 		    }
                   4207: 		}
1.1164    raeburn  4208:                 my $pathfrom;
1.640     albertel 4209: 		foreach my $item (keys(%mediafiles)) {
                   4210: 		    if ($name eq $item) {
1.1164    raeburn  4211:                         $pathfrom = $attr->{'value'};
                   4212:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4213: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4214: 			last;
                   4215: 		    }
                   4216: 		}
1.1164    raeburn  4217:                 if ($name eq 'flashvars') {
                   4218:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4219:                 }
                   4220:                 if ($pathfrom ne '') {
                   4221:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4222:                                          $pathfrom);
                   4223:                 }
1.640     albertel 4224: 	    }
                   4225: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4226: 		foreach my $item (keys(%javafiles)) {
                   4227: 		    if ($attr->{$item}) {
                   4228: 			$javafiles{$item} = $attr->{$item};
                   4229: 			last;
                   4230: 		    }
                   4231: 		}
                   4232: 		foreach my $item (keys(%mediafiles)) {
                   4233: 		    if ($attr->{$item}) {
                   4234: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4235: 			last;
                   4236: 		    }
                   4237: 		}
1.1164    raeburn  4238:                 if (lc($tagname) eq 'embed') {
                   4239:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4240:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4241:                                              $attr->{'src'});
                   4242:                     }
                   4243:                 }
1.640     albertel 4244: 	    }
1.1243    raeburn  4245:             if (lc($tagname) eq 'iframe') {
                   4246:                 my $src = $attr->{'src'} ;
                   4247:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4248:                     &add_filetype($allfiles,$src,'src');
                   4249:                 } elsif ($src =~ m{^/}) {
                   4250:                     if ($env{'request.course.id'}) {
                   4251:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4252:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4253:                         my $url = &hreflocation('',$fullpath);
                   4254:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4255:                             my $relpath = $1;
                   4256:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4257:                                 &add_filetype($allfiles,$1,'src');
                   4258:                             }
                   4259:                         }
                   4260:                     }
                   4261:                 }
                   4262:             }
1.1164    raeburn  4263:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4264:                 pop(@state);
1.1164    raeburn  4265:             }
1.640     albertel 4266: 	} elsif ($t->[0] eq 'E') {
                   4267: 	    my ($tagname) = ($t->[1]);
                   4268: 	    if ($javafiles{'codebase'} ne '') {
                   4269: 		$javafiles{'codebase'} .= '/';
                   4270: 	    }  
                   4271: 	    if (lc($tagname) eq 'applet' ||
                   4272: 		lc($tagname) eq 'object' ||
                   4273: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4274: 		) {
                   4275: 		foreach my $item (keys(%javafiles)) {
                   4276: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4277: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4278: 			&add_filetype($allfiles,$file,$item);
                   4279: 		    }
                   4280: 		}
                   4281: 	    } 
                   4282: 	    pop @state;
                   4283: 	}
                   4284:     }
1.1164    raeburn  4285:     foreach my $id (sort(keys(%flashvars))) {
                   4286:         if ($shockwave{$id} ne '') {
                   4287:             my @pairs = split(/\&/,$flashvars{$id});
                   4288:             foreach my $pair (@pairs) {
                   4289:                 my ($key,$value) = split(/\=/,$pair);
                   4290:                 if ($key eq 'thumb') {
                   4291:                     &add_filetype($allfiles,$value,$key);
                   4292:                 } elsif ($key eq 'content') {
                   4293:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4294:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4295:                     if ($ext ne '') {
                   4296:                         &add_filetype($allfiles,$path.$value,$ext);
                   4297:                     }
                   4298:                 }
                   4299:             }
                   4300:         }
                   4301:     }
1.637     raeburn  4302:     return 'ok';
                   4303: }
                   4304: 
1.639     albertel 4305: sub add_filetype {
                   4306:     my ($allfiles,$file,$type)=@_;
                   4307:     if (exists($allfiles->{$file})) {
                   4308: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4309: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4310: 	}
                   4311:     } else {
                   4312: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4313:     }
                   4314: }
                   4315: 
1.1164    raeburn  4316: sub embedded_dependency {
                   4317:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4318:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4319:         if (($identifier ne '') &&
                   4320:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4321:             ($pathfrom ne '')) {
                   4322:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4323:             foreach my $dep (@{$related->{$identifier}}) {
                   4324:                 &add_filetype($allfiles,$path.$dep,'object');
                   4325:             }
                   4326:         }
                   4327:     }
                   4328:     return;
                   4329: }
                   4330: 
1.493     albertel 4331: sub removeuploadedurl {
1.984     neumanie 4332:     my ($url)=@_;	
                   4333:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4334:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4335: }
                   4336: 
                   4337: sub removeuserfile {
                   4338:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4339:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4340:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4341:     if ($result eq 'ok') {	
1.798     raeburn  4342:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4343:             my $metafile = $fname.'.meta';
                   4344:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4345: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4346:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4347:             my $sqlresult = 
1.823     albertel 4348:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4349:                                         'portfolio_metadata',$group,
                   4350:                                         'delete');
1.798     raeburn  4351:         }
                   4352:     }
                   4353:     return $result;
1.257     www      4354: }
1.15      www      4355: 
1.530     albertel 4356: sub mkdiruserfile {
                   4357:     my ($docuname,$docudom,$dir)=@_;
                   4358:     my $home=&homeserver($docuname,$docudom);
                   4359:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4360: }
                   4361: 
1.531     albertel 4362: sub renameuserfile {
                   4363:     my ($docuname,$docudom,$old,$new)=@_;
                   4364:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4365:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4366:                         &escape("$old").':'.&escape("$new"),$home);
                   4367:     if ($result eq 'ok') {
                   4368:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4369:             my $oldmeta = $old.'.meta';
                   4370:             my $newmeta = $new.'.meta';
                   4371:             my $metaresult = 
                   4372:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4373: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4374:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4375:             my $sqlresult = 
1.823     albertel 4376:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4377:                                         'portfolio_metadata',$group,
                   4378:                                         'delete');
1.798     raeburn  4379:         }
                   4380:     }
                   4381:     return $result;
1.531     albertel 4382: }
                   4383: 
1.14      www      4384: # ------------------------------------------------------------------------- Log
                   4385: 
                   4386: sub log {
                   4387:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4388:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4389: }
                   4390: 
                   4391: # ------------------------------------------------------------------ Course Log
1.352     www      4392: #
                   4393: # This routine flushes several buffers of non-mission-critical nature
                   4394: #
1.157     www      4395: 
                   4396: sub flushcourselogs {
1.352     www      4397:     &logthis('Flushing log buffers');
                   4398: #
                   4399: # course logs
                   4400: # This is a log of all transactions in a course, which can be used
                   4401: # for data mining purposes
                   4402: #
                   4403: # It also collects the courseid database, which lists last transaction
                   4404: # times and course titles for all courseids
                   4405: #
                   4406:     my %courseidbuffer=();
1.921     raeburn  4407:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4408:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4409: 		          &escape($courselogs{$crsid}),
                   4410: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4411: 	    delete $courselogs{$crsid};
                   4412:         } else {
                   4413:             &logthis('Failed to flush log buffer for '.$crsid);
                   4414:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4415:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4416:                         " exceeded maximum size, deleting.</font>");
                   4417:                delete $courselogs{$crsid};
                   4418:             }
1.352     www      4419:         }
1.920     raeburn  4420:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4421:             'description' => $coursedescrbuf{$crsid},
                   4422:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4423:             'type'        => $coursetypebuf{$crsid},
                   4424:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4425:         };
1.191     harris41 4426:     }
1.352     www      4427: #
                   4428: # Write course id database (reverse lookup) to homeserver of courses 
                   4429: # Is used in pickcourse
                   4430: #
1.840     albertel 4431:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4432:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4433:                                     $courseidbuffer{$crs_home},
                   4434:                                     $crs_home,'timeonly');
1.352     www      4435:     }
                   4436: #
                   4437: # File accesses
                   4438: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4439: #
1.449     matthew  4440:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4441:         if ($entry =~ /___count$/) {
                   4442:             my ($dom,$name);
1.807     albertel 4443:             ($dom,$name,undef)=
1.811     albertel 4444: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4445:             if (! defined($dom) || $dom eq '' || 
                   4446:                 ! defined($name) || $name eq '') {
1.620     albertel 4447:                 my $cid = $env{'request.course.id'};
                   4448:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4449:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4450:             }
1.450     matthew  4451:             my $value = $accesshash{$entry};
                   4452:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4453:             my %temphash=($url => $value);
1.449     matthew  4454:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4455:             if ($result eq 'ok') {
                   4456:                 delete $accesshash{$entry};
                   4457:             }
                   4458:         } else {
1.811     albertel 4459:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4460:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4461:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4462:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4463:                 delete $accesshash{$entry};
                   4464:             }
1.185     www      4465:         }
1.191     harris41 4466:     }
1.352     www      4467: #
                   4468: # Roles
                   4469: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4470: #
1.800     albertel 4471:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4472:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4473: 	    split(/\:/,$entry);
                   4474:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4475:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4476:                 $rudom,$runame) eq 'ok') {
                   4477: 	    delete $userrolehash{$entry};
                   4478:         }
                   4479:     }
1.662     raeburn  4480: #
1.1334    raeburn  4481: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4482: #
                   4483:     my %domrolebuffer = ();
1.1000    raeburn  4484:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4485:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4486:         if ($domrolebuffer{$rudom}) {
                   4487:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4488:                       '='.&escape($domainrolehash{$entry});
                   4489:         } else {
                   4490:             $domrolebuffer{$rudom}.=&escape($entry).
                   4491:                       '='.&escape($domainrolehash{$entry});
                   4492:         }
                   4493:         delete $domainrolehash{$entry};
                   4494:     }
                   4495:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4496: 	my %servers;
                   4497: 	if (defined(&domain($dom,'primary'))) {
                   4498: 	    my $primary=&domain($dom,'primary');
                   4499: 	    my $hostname=&hostname($primary);
                   4500: 	    $servers{$primary} = $hostname;
                   4501: 	} else { 
                   4502: 	    %servers = &get_servers($dom,'library');
                   4503: 	}
1.841     albertel 4504: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4505: 	    if (&reply('domroleput:'.$dom.':'.
                   4506: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4507: 		last;
                   4508: 	    } else {  
1.841     albertel 4509: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4510: 	    }
1.662     raeburn  4511:         }
                   4512:     }
1.186     www      4513:     $dumpcount++;
1.157     www      4514: }
                   4515: 
                   4516: sub courselog {
                   4517:     my $what=shift;
1.158     www      4518:     $what=time.':'.$what;
1.620     albertel 4519:     unless ($env{'request.course.id'}) { return ''; }
                   4520:     $coursedombuf{$env{'request.course.id'}}=
                   4521:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4522:     $coursenumbuf{$env{'request.course.id'}}=
                   4523:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4524:     $coursehombuf{$env{'request.course.id'}}=
                   4525:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4526:     $coursedescrbuf{$env{'request.course.id'}}=
                   4527:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4528:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4529:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4530:     $courseownerbuf{$env{'request.course.id'}}=
                   4531:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4532:     $coursetypebuf{$env{'request.course.id'}}=
                   4533:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4534:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4535: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4536:     } else {
1.620     albertel 4537: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4538:     }
1.620     albertel 4539:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4540: 	&flushcourselogs();
                   4541:     }
1.158     www      4542: }
                   4543: 
                   4544: sub courseacclog {
                   4545:     my $fnsymb=shift;
1.620     albertel 4546:     unless ($env{'request.course.id'}) { return ''; }
                   4547:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4548:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4549:         $what.=':POST';
1.583     matthew  4550:         # FIXME: Probably ought to escape things....
1.800     albertel 4551: 	foreach my $key (keys(%env)) {
                   4552:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4553:                 my $formitem = $1;
                   4554:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4555:                     $what.=':'.$formitem.'='.$env{$key};
                   4556:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4557:                     $what.=':'.$formitem.'='.$env{$key};
                   4558:                 }
1.158     www      4559:             }
1.191     harris41 4560:         }
1.583     matthew  4561:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4562:         # FIXME: We should not be depending on a form parameter that someone
                   4563:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4564:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4565:             $what.= ':POST';
                   4566:             # FIXME: Probably ought to escape things....
                   4567:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4568:                                  'crsdiscuss') {
1.620     albertel 4569:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4570:             }
                   4571:         }
1.158     www      4572:     }
                   4573:     &courselog($what);
1.149     www      4574: }
                   4575: 
1.185     www      4576: sub countacc {
                   4577:     my $url=&declutter(shift);
1.458     matthew  4578:     return if (! defined($url) || $url eq '');
1.620     albertel 4579:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4580: #
                   4581: # Mark that this url was used in this course
                   4582: #
1.620     albertel 4583:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4584: #
                   4585: # Increase the access count for this resource in this child process
                   4586: #
1.281     www      4587:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4588:     $accesshash{$key}++;
1.185     www      4589: }
1.349     www      4590: 
1.361     www      4591: sub linklog {
                   4592:     my ($from,$to)=@_;
                   4593:     $from=&declutter($from);
                   4594:     $to=&declutter($to);
                   4595:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4596:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4597: }
1.1160    www      4598: 
                   4599: sub statslog {
                   4600:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4601:     if ($users<2) { return; }
                   4602:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4603:             'course'       => $env{'request.course.id'},
                   4604:             'sections'     => '"all"',
                   4605:             'num_students' => $users,
                   4606:             'part'         => $part,
                   4607:             'symb'         => $symb,
                   4608:             'mean_tries'   => $av_attempts,
                   4609:             'deg_of_diff'  => $degdiff});
                   4610:     foreach my $key (keys(%dynstore)) {
                   4611:         $accesshash{$key}=$dynstore{$key};
                   4612:     }
                   4613: }
1.361     www      4614:   
1.349     www      4615: sub userrolelog {
                   4616:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4617:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4618:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4619:        $userrolehash
                   4620:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4621:                     =$tend.':'.$tstart;
1.662     raeburn  4622:     }
1.1169    droeschl 4623:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4624:        $userrolehash
                   4625:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4626:                     =$tend.':'.$tstart;
                   4627:     }
1.1334    raeburn  4628:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4629:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4630:        $domainrolehash
                   4631:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4632:                     = $tend.':'.$tstart;
                   4633:     }
1.351     www      4634: }
                   4635: 
1.957     raeburn  4636: sub courserolelog {
                   4637:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4638:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4639:         my $cdom = $1;
                   4640:         my $cnum = $2;
                   4641:         my $sec = $3;
                   4642:         my $namespace = 'rolelog';
                   4643:         my %storehash = (
                   4644:                            role    => $trole,
                   4645:                            start   => $tstart,
                   4646:                            end     => $tend,
                   4647:                            selfenroll => $selfenroll,
                   4648:                            context    => $context,
                   4649:                         );
                   4650:         if ($trole eq 'gr') {
                   4651:             $namespace = 'groupslog';
                   4652:             $storehash{'group'} = $sec;
                   4653:         } else {
                   4654:             $storehash{'section'} = $sec;
                   4655:         }
1.1188    raeburn  4656:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4657:                    $domain,$cnum,$cdom);
1.1184    raeburn  4658:         if (($trole ne 'st') || ($sec ne '')) {
                   4659:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4660:         }
                   4661:     }
                   4662:     return;
                   4663: }
                   4664: 
1.1184    raeburn  4665: sub domainrolelog {
                   4666:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4667:     if ($area =~ m{^/($match_domain)/$}) {
                   4668:         my $cdom = $1;
                   4669:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4670:         my $namespace = 'rolelog';
                   4671:         my %storehash = (
                   4672:                            role    => $trole,
                   4673:                            start   => $tstart,
                   4674:                            end     => $tend,
                   4675:                            context => $context,
                   4676:                         );
1.1188    raeburn  4677:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4678:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4679:     }
                   4680:     return;
                   4681: 
                   4682: }
                   4683: 
                   4684: sub coauthorrolelog {
                   4685:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4686:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4687:         my $audom = $1;
                   4688:         my $auname = $2;
                   4689:         my $namespace = 'rolelog';
                   4690:         my %storehash = (
                   4691:                            role    => $trole,
                   4692:                            start   => $tstart,
                   4693:                            end     => $tend,
                   4694:                            context => $context,
                   4695:                         );
1.1188    raeburn  4696:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4697:                    $domain,$auname,$audom);
1.1184    raeburn  4698:     }
                   4699:     return;
                   4700: }
                   4701: 
1.351     www      4702: sub get_course_adv_roles {
1.948     raeburn  4703:     my ($cid,$codes) = @_;
1.620     albertel 4704:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4705:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4706:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4707:     my %nothide=();
1.800     albertel 4708:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4709:         if ($user !~ /:/) {
                   4710: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4711:         } else {
                   4712:             $nothide{$user}=1;
                   4713:         }
1.470     www      4714:     }
1.1219    raeburn  4715:     my @possdoms = ($coursehash{'domain'});
                   4716:     if ($coursehash{'checkforpriv'}) {
                   4717:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4718:     }
1.351     www      4719:     my %returnhash=();
                   4720:     my %dumphash=
                   4721:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4722:     my $now=time;
1.997     raeburn  4723:     my %privileged;
1.1000    raeburn  4724:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4725: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4726:         if (($tstart) && ($tstart<0)) { next; }
                   4727:         if (($tend) && ($tend<$now)) { next; }
                   4728:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4729:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4730: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4731:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4732:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4733: 	if ($role eq 'cr') { next; }
1.948     raeburn  4734:         if ($codes) {
                   4735:             if ($section) { $role .= ':'.$section; }
                   4736:             if ($returnhash{$role}) {
                   4737:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4738:             } else {
                   4739:                 $returnhash{$role}=$username.':'.$domain;
                   4740:             }
1.351     www      4741:         } else {
1.988     raeburn  4742:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4743:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4744:             if ($returnhash{$key}) {
                   4745: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4746:             } else {
                   4747:                 $returnhash{$key}=$username.':'.$domain;
                   4748:             }
1.351     www      4749:         }
1.948     raeburn  4750:     }
1.400     www      4751:     return %returnhash;
                   4752: }
                   4753: 
                   4754: sub get_my_roles {
1.937     raeburn  4755:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4756:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4757:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4758:     my (%dumphash,%nothide);
1.1086    raeburn  4759:     if ($context eq 'userroles') {
1.1166    raeburn  4760:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4761:     } else {
1.1219    raeburn  4762:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4763:         if ($hidepriv) {
                   4764:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4765:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4766:                 if ($user !~ /:/) {
                   4767:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4768:                 } else {
                   4769:                     $nothide{$user} = 1;
                   4770:                 }
                   4771:             }
                   4772:         }
1.858     raeburn  4773:     }
1.400     www      4774:     my %returnhash=();
                   4775:     my $now=time;
1.999     raeburn  4776:     my %privileged;
1.800     albertel 4777:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4778:         my ($role,$tend,$tstart);
                   4779:         if ($context eq 'userroles') {
1.1149    raeburn  4780:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4781: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4782:         } else {
                   4783:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4784:         }
1.400     www      4785:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4786:         my $status = 'active';
1.939     raeburn  4787:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4788:             $status = 'previous';
                   4789:         } 
                   4790:         if (($tstart) && ($now<$tstart)) {
                   4791:             $status = 'future';
                   4792:         }
                   4793:         if (ref($types) eq 'ARRAY') {
                   4794:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4795:                 next;
                   4796:             } 
                   4797:         } else {
                   4798:             if ($status ne 'active') {
                   4799:                 next;
                   4800:             }
                   4801:         }
1.867     raeburn  4802:         my ($rolecode,$username,$domain,$section,$area);
                   4803:         if ($context eq 'userroles') {
1.1186    raeburn  4804:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4805:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4806:         } else {
                   4807:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4808:         }
1.832     raeburn  4809:         if (ref($roledoms) eq 'ARRAY') {
                   4810:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4811:                 next;
                   4812:             }
                   4813:         }
                   4814:         if (ref($roles) eq 'ARRAY') {
                   4815:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4816:                 if ($role =~ /^cr\//) {
                   4817:                     if (!grep(/^cr$/,@{$roles})) {
                   4818:                         next;
                   4819:                     }
1.1104    raeburn  4820:                 } elsif ($role =~ /^gr\//) {
                   4821:                     if (!grep(/^gr$/,@{$roles})) {
                   4822:                         next;
                   4823:                     }
1.922     raeburn  4824:                 } else {
                   4825:                     next;
                   4826:                 }
1.832     raeburn  4827:             }
1.867     raeburn  4828:         }
1.937     raeburn  4829:         if ($hidepriv) {
1.1219    raeburn  4830:             my @privroles = ('dc','su');
1.999     raeburn  4831:             if ($context eq 'userroles') {
1.1219    raeburn  4832:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4833:             } else {
1.1219    raeburn  4834:                 my $possdoms = [$domain];
                   4835:                 if (ref($roledoms) eq 'ARRAY') {
                   4836:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4837:                 }
1.1219    raeburn  4838:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4839:                     if (!$nothide{$username.':'.$domain}) {
                   4840:                         next;
                   4841:                     }
                   4842:                 }
1.937     raeburn  4843:             }
                   4844:         }
1.933     raeburn  4845:         if ($withsec) {
                   4846:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4847:                 $tstart.':'.$tend;
                   4848:         } else {
                   4849:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4850:         }
1.832     raeburn  4851:     }
1.373     www      4852:     return %returnhash;
1.399     www      4853: }
                   4854: 
1.1333    raeburn  4855: sub get_all_adhocroles {
                   4856:     my ($dom) = @_;
                   4857:     my @roles_by_num = ();
                   4858:     my %domdefaults = &get_domain_defaults($dom);
                   4859:     my (%description,%access_in_dom,%access_info);
                   4860:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4861:         my $count = 0;
                   4862:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4863:         my %ordered;
                   4864:         foreach my $role (sort(keys(%domcurrent))) {
                   4865:             my ($order,$desc,$access_in_dom);
                   4866:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4867:                 $order = $domcurrent{$role}{'order'};
                   4868:                 $desc = $domcurrent{$role}{'desc'};
                   4869:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4870:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4871:             }
                   4872:             if ($order eq '') {
                   4873:                 $order = $count;
                   4874:             }
                   4875:             $ordered{$order} = $role;
                   4876:             if ($desc ne '') {
                   4877:                 $description{$role} = $desc;
                   4878:             } else {
                   4879:                 $description{$role}= $role;
                   4880:             }
                   4881:             $count++;
                   4882:         }
                   4883:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4884:             push(@roles_by_num,$ordered{$item});
                   4885:         }
                   4886:     }
                   4887:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4888: }
                   4889: 
1.1332    raeburn  4890: sub get_my_adhocroles {
1.1333    raeburn  4891:     my ($cid,$checkreg) = @_;
                   4892:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4893:     if ($env{'request.course.id'} eq $cid) {
                   4894:         $cdom = $env{'course.'.$cid.'.domain'};
                   4895:         $cnum = $env{'course.'.$cid.'.num'};
                   4896:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4897:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4898:         $cdom = $1;
                   4899:         $cnum = $2;
                   4900:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4901:                                      $cdom,$cnum);
                   4902:     }
                   4903:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4904:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4905:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4906:         if ($rosterhash{$user} ne '') {
                   4907:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4908:             return ([],{}) if ($type eq 'auto');
                   4909:         }
                   4910:     }
                   4911:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4912:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4913:             my $then=$env{'user.login.time'};
                   4914:             my $update=$env{'user.update.time'};
1.1335    raeburn  4915:             if (!$update) {
                   4916:                 $update = $then;
                   4917:             }
                   4918:             my @liveroles;
1.1334    raeburn  4919:             foreach my $role ('dh','da') {
                   4920:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4921:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4922:                     my $limit = $update;
                   4923:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4924:                         $limit = $then;
                   4925:                     }
1.1335    raeburn  4926:                     my $activerole = 1;
                   4927:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4928:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4929:                     if ($activerole) {
                   4930:                         push(@liveroles,$role);
                   4931:                     }
1.1334    raeburn  4932:                 }
1.1332    raeburn  4933:             }
1.1335    raeburn  4934:             if (@liveroles) {
1.1332    raeburn  4935:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4936:                     my ($accessref,$accessinfo,%access_in_dom);
                   4937:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4938:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4939:                         if (@{$roles_by_num}) {
1.1332    raeburn  4940:                             my %settings;
                   4941:                             if ($env{'request.course.id'} eq $cid) {
                   4942:                                 foreach my $envkey (keys(%env)) {
                   4943:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4944:                                         $settings{$1} = $env{$envkey};
                   4945:                                     }
                   4946:                                 }
                   4947:                             } else {
                   4948:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4949:                             }
                   4950:                             my %setincrs;
                   4951:                             if ($settings{'internal.adhocaccess'}) {
                   4952:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4953:                             }
                   4954:                             my @statuses;
                   4955:                             if ($env{'environment.inststatus'}) {
                   4956:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4957:                             }
                   4958:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4959:                             if (ref($accessref) eq 'HASH') {
                   4960:                                 %access_in_dom = %{$accessref};
                   4961:                             }
                   4962:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4963:                                 my ($curraccess,@okstatus,@personnel);
                   4964:                                 if ($setincrs{$role}) {
                   4965:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4966:                                     if ($curraccess eq 'status') {
                   4967:                                         @okstatus = split(/\&/,$rest);
                   4968:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4969:                                         @personnel = split(/\&/,$rest);
                   4970:                                     }
                   4971:                                 } else {
                   4972:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4973:                                     if (ref($accessinfo) eq 'HASH') {
                   4974:                                         if ($curraccess eq 'status') {
                   4975:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4976:                                                 @okstatus = @{$accessinfo->{$role}};
                   4977:                                             }
                   4978:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4979:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4980:                                                 @personnel = @{$accessinfo->{$role}};
                   4981:                                             }
1.1332    raeburn  4982:                                         }
                   4983:                                     }
                   4984:                                 }
                   4985:                                 if ($curraccess eq 'none') {
                   4986:                                     next;
                   4987:                                 } elsif ($curraccess eq 'all') {
                   4988:                                     push(@possroles,$role);
1.1336    raeburn  4989:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4990:                                     if (grep(/^dh$/,@liveroles)) {
                   4991:                                         push(@possroles,$role);
                   4992:                                     } else {
                   4993:                                         next;
                   4994:                                     }
1.1336    raeburn  4995:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4996:                                     if (grep(/^da$/,@liveroles)) {
                   4997:                                         push(@possroles,$role);
                   4998:                                     } else {
                   4999:                                         next;
                   5000:                                     }
1.1332    raeburn  5001:                                 } elsif ($curraccess eq 'status') {
                   5002:                                     if (@okstatus) {
                   5003:                                         if (!@statuses) {
                   5004:                                             if (grep(/^default$/,@okstatus)) {
                   5005:                                                 push(@possroles,$role);
                   5006:                                             }
                   5007:                                         } else {
                   5008:                                             foreach my $status (@okstatus) {
                   5009:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5010:                                                     push(@possroles,$role);
                   5011:                                                     last;
                   5012:                                                 }
                   5013:                                             }
                   5014:                                         }
                   5015:                                     }
                   5016:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5017:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5018:                                         if ($curraccess eq 'exc') {
                   5019:                                             push(@possroles,$role);
                   5020:                                         }
                   5021:                                     } elsif ($curraccess eq 'inc') {
                   5022:                                         push(@possroles,$role);
                   5023:                                     }
                   5024:                                 }
                   5025:                             }
                   5026:                         }
                   5027:                     }
                   5028:                 }
                   5029:             }
                   5030:         }
                   5031:     }
1.1333    raeburn  5032:     unless (ref($description) eq 'HASH') {
                   5033:         if (ref($roles_by_num) eq 'ARRAY') {
                   5034:             my %desc;
                   5035:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5036:             $description = \%desc;
                   5037:         } else {
                   5038:             $description = {};
                   5039:         }
                   5040:     }
                   5041:     return (\@possroles,$description);
1.1332    raeburn  5042: }
                   5043: 
1.399     www      5044: # ----------------------------------------------------- Frontpage Announcements
                   5045: #
                   5046: #
                   5047: 
                   5048: sub postannounce {
                   5049:     my ($server,$text)=@_;
1.844     albertel 5050:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5051:     unless ($text=~/\w/) { $text=''; }
                   5052:     return &reply('setannounce:'.&escape($text),$server);
                   5053: }
                   5054: 
                   5055: sub getannounce {
1.448     albertel 5056: 
1.1359    raeburn  5057:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5058: 	my $announcement='';
1.800     albertel 5059: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5060: 	close($fh);
1.399     www      5061: 	if ($announcement=~/\w/) { 
                   5062: 	    return 
                   5063:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5064:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5065: 	} else {
                   5066: 	    return '';
                   5067: 	}
                   5068:     } else {
                   5069: 	return '';
                   5070:     }
1.351     www      5071: }
1.353     www      5072: 
                   5073: # ---------------------------------------------------------- Course ID routines
                   5074: # Deal with domain's nohist_courseid.db files
                   5075: #
                   5076: 
                   5077: sub courseidput {
1.921     raeburn  5078:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5079:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5080:     my $outcome;
                   5081:     if ($caller eq 'timeonly') {
                   5082:         my $cids = '';
                   5083:         foreach my $item (keys(%$storehash)) {
                   5084:             $cids.=&escape($item).'&';
                   5085:         }
                   5086:         $cids=~s/\&$//;
                   5087:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5088:                           $coursehome);       
                   5089:     } else {
                   5090:         my $items = '';
                   5091:         foreach my $item (keys(%$storehash)) {
                   5092:             $items.= &escape($item).'='.
                   5093:                      &freeze_escape($$storehash{$item}).'&';
                   5094:         }
                   5095:         $items=~s/\&$//;
                   5096:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5097:                           $coursehome);
1.918     raeburn  5098:     }
                   5099:     if ($outcome eq 'unknown_cmd') {
                   5100:         my $what;
                   5101:         foreach my $cid (keys(%$storehash)) {
                   5102:             $what .= &escape($cid).'=';
1.921     raeburn  5103:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5104:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5105:             }
                   5106:             $what =~ s/\:$/&/;
                   5107:         }
                   5108:         $what =~ s/\&$//;  
                   5109:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5110:     } else {
                   5111:         return $outcome;
                   5112:     }
1.353     www      5113: }
                   5114: 
                   5115: sub courseiddump {
1.921     raeburn  5116:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5117:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5118:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5119:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5120:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5121:     my $as_hash = 1;
                   5122:     my %returnhash;
                   5123:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5124:     my %libserv = &all_library();
                   5125:     foreach my $tryserver (keys(%libserv)) {
                   5126:         if ( (  $hostidflag == 1 
                   5127: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5128: 	     || (!defined($hostidflag)) ) {
                   5129: 
1.918     raeburn  5130: 	    if (($domfilter eq '') ||
                   5131: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5132:                 my $rep;
                   5133:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5134:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5135:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5136:                                 &escape($descfilter), &escape($instcodefilter), 
                   5137:                                 &escape($ownerfilter), &escape($coursefilter),
                   5138:                                 &escape($typefilter), &escape($regexp_ok), 
                   5139:                                 $as_hash, &escape($selfenrollonly), 
                   5140:                                 &escape($catfilter), $showhidden, $caller, 
                   5141:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5142:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5143:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5144:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5145:                 } else {
                   5146:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5147:                              $sincefilter.':'.&escape($descfilter).':'.
                   5148:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5149:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5150:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5151:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5152:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5153:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5154:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5155:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5156:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5157:                 }
                   5158:                      
1.918     raeburn  5159:                 my @pairs=split(/\&/,$rep);
                   5160:                 foreach my $item (@pairs) {
                   5161:                     my ($key,$value)=split(/\=/,$item,2);
                   5162:                     $key = &unescape($key);
                   5163:                     next if ($key =~ /^error: 2 /);
                   5164:                     my $result = &thaw_unescape($value);
                   5165:                     if (ref($result) eq 'HASH') {
                   5166:                         $returnhash{$key}=$result;
                   5167:                     } else {
1.921     raeburn  5168:                         my @responses = split(/:/,$value);
                   5169:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5170:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5171:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5172:                         }
1.1008    raeburn  5173:                     }
1.353     www      5174:                 }
                   5175:             }
                   5176:         }
                   5177:     }
                   5178:     return %returnhash;
                   5179: }
                   5180: 
1.1055    raeburn  5181: sub courselastaccess {
                   5182:     my ($cdom,$cnum,$hostidref) = @_;
                   5183:     my %returnhash;
                   5184:     if ($cdom && $cnum) {
                   5185:         my $chome = &homeserver($cnum,$cdom);
                   5186:         if ($chome ne 'no_host') {
                   5187:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5188:             &extract_lastaccess(\%returnhash,$rep);
                   5189:         }
                   5190:     } else {
                   5191:         if (!$cdom) { $cdom=''; }
                   5192:         my %libserv = &all_library();
                   5193:         foreach my $tryserver (keys(%libserv)) {
                   5194:             if (ref($hostidref) eq 'ARRAY') {
                   5195:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5196:             } 
                   5197:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5198:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5199:                 &extract_lastaccess(\%returnhash,$rep);
                   5200:             }
                   5201:         }
                   5202:     }
                   5203:     return %returnhash;
                   5204: }
                   5205: 
                   5206: sub extract_lastaccess {
                   5207:     my ($returnhash,$rep) = @_;
                   5208:     if (ref($returnhash) eq 'HASH') {
                   5209:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5210:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5211:                  $rep eq '') {
                   5212:             my @pairs=split(/\&/,$rep);
                   5213:             foreach my $item (@pairs) {
                   5214:                 my ($key,$value)=split(/\=/,$item,2);
                   5215:                 $key = &unescape($key);
                   5216:                 next if ($key =~ /^error: 2 /);
                   5217:                 $returnhash->{$key} = &thaw_unescape($value);
                   5218:             }
                   5219:         }
                   5220:     }
                   5221:     return;
                   5222: }
                   5223: 
1.658     raeburn  5224: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5225: 
                   5226: sub dcmailput {
1.685     raeburn  5227:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5228:     my $status = &Apache::lonnet::critical(
1.740     www      5229:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5230:        &escape($message),$server);
1.662     raeburn  5231:     return $status;
                   5232: }
                   5233: 
1.658     raeburn  5234: sub dcmaildump {
                   5235:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5236:     my %returnhash=();
1.846     albertel 5237: 
                   5238:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5239:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5240:                                                          &escape($enddate).':';
                   5241: 	my @esc_senders=map { &escape($_)} @$senders;
                   5242: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5243: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5244:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5245:             if (($key) && ($value)) {
                   5246:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5247:             }
                   5248:         }
                   5249:     }
                   5250:     return %returnhash;
                   5251: }
1.662     raeburn  5252: # ---------------------------------------------------------- Domain roles
                   5253: 
                   5254: sub get_domain_roles {
                   5255:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5256:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5257:         $startdate = '.';
                   5258:     }
1.1018    raeburn  5259:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5260:         $enddate = '.';
                   5261:     }
1.922     raeburn  5262:     my $rolelist;
                   5263:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5264:         $rolelist = join('&',@{$roles});
1.922     raeburn  5265:     }
1.662     raeburn  5266:     my %personnel = ();
1.841     albertel 5267: 
                   5268:     my %servers = &get_servers($dom,'library');
                   5269:     foreach my $tryserver (keys(%servers)) {
                   5270: 	%{$personnel{$tryserver}}=();
                   5271: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5272: 					    &escape($startdate).':'.
                   5273: 					    &escape($enddate).':'.
                   5274: 					    &escape($rolelist), $tryserver))) {
                   5275: 	    my ($key,$value) = split(/\=/,$line,2);
                   5276: 	    if (($key) && ($value)) {
                   5277: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5278: 	    }
                   5279: 	}
1.662     raeburn  5280:     }
                   5281:     return %personnel;
                   5282: }
1.658     raeburn  5283: 
1.1332    raeburn  5284: sub get_active_domroles {
                   5285:     my ($dom,$roles) = @_;
                   5286:     return () unless (ref($roles) eq 'ARRAY');
                   5287:     my $now = time;
                   5288:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5289:     my %domroles;
                   5290:     foreach my $server (keys(%dompersonnel)) {
                   5291:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5292:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5293:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5294:         }
                   5295:     }
                   5296:     return %domroles;
                   5297: }
                   5298: 
1.1057    www      5299: # ----------------------------------------------------------- Interval timing 
1.149     www      5300: 
1.1153    www      5301: {
                   5302: # Caches needed for speedup of navmaps
                   5303: # We don't want to cache this for very long at all (5 seconds at most)
                   5304: # 
                   5305: # The user for whom we cache
                   5306: my $cachedkey='';
                   5307: # The cached times for this user
                   5308: my %cachedtimes=();
                   5309: # When this was last done
1.1282    raeburn  5310: my $cachedtime='';
1.1153    www      5311: 
                   5312: sub load_all_first_access {
1.1308    raeburn  5313:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5314:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5315:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5316:         (!$ignorecache)) {
1.1154    raeburn  5317:         return;
                   5318:     }
                   5319:     $cachedtime=time;
                   5320:     $cachedkey=$uname.':'.$udom;
                   5321:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5322: }
                   5323: 
1.504     albertel 5324: sub get_first_access {
1.1308    raeburn  5325:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5326:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5327:     if ($argsymb) { $symb=$argsymb; }
                   5328:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5329:     if ($argmap) { $map = $argmap; }
1.926     albertel 5330:     if ($type eq 'course') {
                   5331: 	$res='course';
                   5332:     } elsif ($type eq 'map') {
1.588     albertel 5333: 	$res=&symbread($map);
                   5334:     } else {
                   5335: 	$res=$symb;
                   5336:     }
1.1308    raeburn  5337:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5338:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5339: }
                   5340: 
                   5341: sub set_first_access {
1.1162    raeburn  5342:     my ($type,$interval)=@_;
1.790     albertel 5343:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5344:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5345:     if ($type eq 'course') {
                   5346: 	$res='course';
                   5347:     } elsif ($type eq 'map') {
1.588     albertel 5348: 	$res=&symbread($map);
                   5349:     } else {
                   5350: 	$res=$symb;
                   5351:     }
1.1153    www      5352:     $cachedkey='';
1.1162    raeburn  5353:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5354:     if ($firstaccess) {
                   5355:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393  ! raeburn  5356:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
        !          5357:                  "in $courseid");
1.1386    raeburn  5358:         return 'already_set';
                   5359:     } else {
1.1162    raeburn  5360:         my $start = time;
                   5361: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5362:                           $udom,$uname);
                   5363:         if ($putres eq 'ok') {
                   5364:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5365:                  $udom,$uname); 
                   5366:             &appenv(
                   5367:                      {
                   5368:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5369:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5370:                      }
                   5371:                   );
1.1365    raeburn  5372:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5373:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5374:             }
1.1386    raeburn  5375:         } elsif ($putres ne 'refused') {
                   5376:             &logthis("Result: $putres when attempting to set first access time ".
                   5377:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5378:         }
                   5379:         return $putres;
1.505     albertel 5380:     }
                   5381:     return 'already_set';
1.504     albertel 5382: }
1.1153    www      5383: }
1.1282    raeburn  5384: 
1.110     www      5385: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5386: 
                   5387: sub expirespread {
                   5388:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5389:     my $cid=$env{'request.course.id'}; 
1.110     www      5390:     if ($cid) {
                   5391:        my $now=time;
                   5392:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5393:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5394:                             $env{'course.'.$cid.'.num'}.
1.110     www      5395: 	        	    ':nohist_expirationdates:'.
                   5396:                             &escape($key).'='.$now,
1.620     albertel 5397:                             $env{'course.'.$cid.'.home'})
1.110     www      5398:     }
                   5399:     return 'ok';
1.14      www      5400: }
                   5401: 
1.109     www      5402: # ----------------------------------------------------- Devalidate Spreadsheets
                   5403: 
                   5404: sub devalidate {
1.325     www      5405:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5406:     my $cid=$env{'request.course.id'}; 
1.109     www      5407:     if ($cid) {
1.391     matthew  5408:         # delete the stored spreadsheets for
                   5409:         # - the student level sheet of this user in course's homespace
                   5410:         # - the assessment level sheet for this resource 
                   5411:         #   for this user in user's homespace
1.553     albertel 5412: 	# - current conditional state info
1.325     www      5413: 	my $key=$uname.':'.$udom.':';
1.109     www      5414:         my $status=
1.299     matthew  5415: 	    &del('nohist_calculatedsheets',
1.391     matthew  5416: 		 [$key.'studentcalc:'],
1.620     albertel 5417: 		 $env{'course.'.$cid.'.domain'},
                   5418: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5419: 		.' '.
                   5420: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5421: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5422:         unless ($status eq 'ok ok') {
                   5423:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5424:                     $uname.' at '.$udom.' for '.
1.109     www      5425: 		    $symb.': '.$status);
1.133     albertel 5426:         }
1.553     albertel 5427: 	&delenv('user.state.'.$cid);
1.109     www      5428:     }
                   5429: }
                   5430: 
1.265     albertel 5431: sub get_scalar {
                   5432:     my ($string,$end) = @_;
                   5433:     my $value;
                   5434:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5435: 	$value = $1;
                   5436:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5437: 	$value = $1;
                   5438:     }
                   5439:     return &unescape($value);
                   5440: }
                   5441: 
                   5442: sub array2str {
                   5443:   my (@array) = @_;
                   5444:   my $result=&arrayref2str(\@array);
                   5445:   $result=~s/^__ARRAY_REF__//;
                   5446:   $result=~s/__END_ARRAY_REF__$//;
                   5447:   return $result;
                   5448: }
                   5449: 
1.204     albertel 5450: sub arrayref2str {
                   5451:   my ($arrayref) = @_;
1.265     albertel 5452:   my $result='__ARRAY_REF__';
1.204     albertel 5453:   foreach my $elem (@$arrayref) {
1.265     albertel 5454:     if(ref($elem) eq 'ARRAY') {
                   5455:       $result.=&arrayref2str($elem).'&';
                   5456:     } elsif(ref($elem) eq 'HASH') {
                   5457:       $result.=&hashref2str($elem).'&';
                   5458:     } elsif(ref($elem)) {
                   5459:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5460:     } else {
                   5461:       $result.=&escape($elem).'&';
                   5462:     }
                   5463:   }
                   5464:   $result=~s/\&$//;
1.265     albertel 5465:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5466:   return $result;
                   5467: }
                   5468: 
1.168     albertel 5469: sub hash2str {
1.204     albertel 5470:   my (%hash) = @_;
                   5471:   my $result=&hashref2str(\%hash);
1.265     albertel 5472:   $result=~s/^__HASH_REF__//;
                   5473:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5474:   return $result;
                   5475: }
                   5476: 
                   5477: sub hashref2str {
                   5478:   my ($hashref)=@_;
1.265     albertel 5479:   my $result='__HASH_REF__';
1.800     albertel 5480:   foreach my $key (sort(keys(%$hashref))) {
                   5481:     if (ref($key) eq 'ARRAY') {
                   5482:       $result.=&arrayref2str($key).'=';
                   5483:     } elsif (ref($key) eq 'HASH') {
                   5484:       $result.=&hashref2str($key).'=';
                   5485:     } elsif (ref($key)) {
1.265     albertel 5486:       $result.='=';
1.800     albertel 5487:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5488:     } else {
1.1132    raeburn  5489: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5490:     }
                   5491: 
1.800     albertel 5492:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5493:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5494:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5495:       $result.=&hashref2str($hashref->{$key}).'&';
                   5496:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5497:        $result.='&';
1.800     albertel 5498:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5499:     } else {
1.800     albertel 5500:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5501:     }
                   5502:   }
1.168     albertel 5503:   $result=~s/\&$//;
1.265     albertel 5504:   $result .= '__END_HASH_REF__';
1.168     albertel 5505:   return $result;
                   5506: }
                   5507: 
                   5508: sub str2hash {
1.265     albertel 5509:     my ($string)=@_;
                   5510:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5511:     return %$hash;
                   5512: }
                   5513: 
                   5514: sub str2hashref {
1.168     albertel 5515:   my ($string) = @_;
1.265     albertel 5516: 
                   5517:   my %hash;
                   5518: 
                   5519:   if($string !~ /^__HASH_REF__/) {
                   5520:       if (! ($string eq '' || !defined($string))) {
                   5521: 	  $hash{'error'}='Not hash reference';
                   5522:       }
                   5523:       return (\%hash, $string);
                   5524:   }
                   5525: 
                   5526:   $string =~ s/^__HASH_REF__//;
                   5527: 
                   5528:   while($string !~ /^__END_HASH_REF__/) {
                   5529:       #key
                   5530:       my $key='';
                   5531:       if($string =~ /^__HASH_REF__/) {
                   5532:           ($key, $string)=&str2hashref($string);
                   5533:           if(defined($key->{'error'})) {
                   5534:               $hash{'error'}='Bad data';
                   5535:               return (\%hash, $string);
                   5536:           }
                   5537:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5538:           ($key, $string)=&str2arrayref($string);
                   5539:           if($key->[0] eq 'Array reference error') {
                   5540:               $hash{'error'}='Bad data';
                   5541:               return (\%hash, $string);
                   5542:           }
                   5543:       } else {
                   5544:           $string =~ s/^(.*?)=//;
1.267     albertel 5545: 	  $key=&unescape($1);
1.265     albertel 5546:       }
                   5547:       $string =~ s/^=//;
                   5548: 
                   5549:       #value
                   5550:       my $value='';
                   5551:       if($string =~ /^__HASH_REF__/) {
                   5552:           ($value, $string)=&str2hashref($string);
                   5553:           if(defined($value->{'error'})) {
                   5554:               $hash{'error'}='Bad data';
                   5555:               return (\%hash, $string);
                   5556:           }
                   5557:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5558:           ($value, $string)=&str2arrayref($string);
                   5559:           if($value->[0] eq 'Array reference error') {
                   5560:               $hash{'error'}='Bad data';
                   5561:               return (\%hash, $string);
                   5562:           }
                   5563:       } else {
                   5564: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5565:       }
                   5566:       $string =~ s/^&//;
                   5567: 
                   5568:       $hash{$key}=$value;
1.204     albertel 5569:   }
1.265     albertel 5570: 
                   5571:   $string =~ s/^__END_HASH_REF__//;
                   5572: 
                   5573:   return (\%hash, $string);
1.204     albertel 5574: }
                   5575: 
                   5576: sub str2array {
1.265     albertel 5577:     my ($string)=@_;
                   5578:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5579:     return @$array;
                   5580: }
                   5581: 
                   5582: sub str2arrayref {
1.204     albertel 5583:   my ($string) = @_;
1.265     albertel 5584:   my @array;
                   5585: 
                   5586:   if($string !~ /^__ARRAY_REF__/) {
                   5587:       if (! ($string eq '' || !defined($string))) {
                   5588: 	  $array[0]='Array reference error';
                   5589:       }
                   5590:       return (\@array, $string);
                   5591:   }
                   5592: 
                   5593:   $string =~ s/^__ARRAY_REF__//;
                   5594: 
                   5595:   while($string !~ /^__END_ARRAY_REF__/) {
                   5596:       my $value='';
                   5597:       if($string =~ /^__HASH_REF__/) {
                   5598:           ($value, $string)=&str2hashref($string);
                   5599:           if(defined($value->{'error'})) {
                   5600:               $array[0] ='Array reference error';
                   5601:               return (\@array, $string);
                   5602:           }
                   5603:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5604:           ($value, $string)=&str2arrayref($string);
                   5605:           if($value->[0] eq 'Array reference error') {
                   5606:               $array[0] ='Array reference error';
                   5607:               return (\@array, $string);
                   5608:           }
                   5609:       } else {
                   5610: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5611:       }
                   5612:       $string =~ s/^&//;
                   5613: 
                   5614:       push(@array, $value);
1.191     harris41 5615:   }
1.265     albertel 5616: 
                   5617:   $string =~ s/^__END_ARRAY_REF__//;
                   5618: 
                   5619:   return (\@array, $string);
1.168     albertel 5620: }
                   5621: 
1.167     albertel 5622: # -------------------------------------------------------------------Temp Store
                   5623: 
1.168     albertel 5624: sub tmpreset {
                   5625:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5626:   if (!$symb) {
                   5627:     $symb=&symbread();
1.620     albertel 5628:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5629:   }
                   5630:   $symb=escape($symb);
                   5631: 
1.620     albertel 5632:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5633:   $namespace=~s/\//\_/g;
                   5634:   $namespace=~s/\W//g;
                   5635: 
1.620     albertel 5636:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5637:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5638:   if ($domain eq 'public' && $stuname eq 'public') {
                   5639:       $stuname=$ENV{'REMOTE_ADDR'};
                   5640:   }
1.1117    foxr     5641:   my $path=LONCAPA::tempdir();
1.168     albertel 5642:   my %hash;
                   5643:   if (tie(%hash,'GDBM_File',
                   5644: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5645: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5646:     foreach my $key (keys(%hash)) {
1.180     albertel 5647:       if ($key=~ /:$symb/) {
1.168     albertel 5648: 	delete($hash{$key});
                   5649:       }
                   5650:     }
                   5651:   }
                   5652: }
                   5653: 
1.167     albertel 5654: sub tmpstore {
1.168     albertel 5655:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5656: 
                   5657:   if (!$symb) {
                   5658:     $symb=&symbread();
1.620     albertel 5659:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5660:   }
                   5661:   $symb=escape($symb);
                   5662: 
                   5663:   if (!$namespace) {
                   5664:     # I don't think we would ever want to store this for a course.
                   5665:     # it seems this will only be used if we don't have a course.
1.620     albertel 5666:     #$namespace=$env{'request.course.id'};
1.168     albertel 5667:     #if (!$namespace) {
1.620     albertel 5668:       $namespace=$env{'request.state'};
1.168     albertel 5669:     #}
                   5670:   }
                   5671:   $namespace=~s/\//\_/g;
                   5672:   $namespace=~s/\W//g;
1.620     albertel 5673:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5674:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5675:   if ($domain eq 'public' && $stuname eq 'public') {
                   5676:       $stuname=$ENV{'REMOTE_ADDR'};
                   5677:   }
1.168     albertel 5678:   my $now=time;
                   5679:   my %hash;
1.1117    foxr     5680:   my $path=LONCAPA::tempdir();
1.168     albertel 5681:   if (tie(%hash,'GDBM_File',
                   5682: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5683: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5684:     $hash{"version:$symb"}++;
                   5685:     my $version=$hash{"version:$symb"};
                   5686:     my $allkeys=''; 
                   5687:     foreach my $key (keys(%$storehash)) {
                   5688:       $allkeys.=$key.':';
1.591     albertel 5689:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5690:     }
                   5691:     $hash{"$version:$symb:timestamp"}=$now;
                   5692:     $allkeys.='timestamp';
                   5693:     $hash{"$version:keys:$symb"}=$allkeys;
                   5694:     if (untie(%hash)) {
                   5695:       return 'ok';
                   5696:     } else {
                   5697:       return "error:$!";
                   5698:     }
                   5699:   } else {
                   5700:     return "error:$!";
                   5701:   }
                   5702: }
1.167     albertel 5703: 
1.168     albertel 5704: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5705: 
1.168     albertel 5706: sub tmprestore {
                   5707:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5708: 
1.168     albertel 5709:   if (!$symb) {
                   5710:     $symb=&symbread();
1.620     albertel 5711:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5712:   }
                   5713:   $symb=escape($symb);
                   5714: 
1.620     albertel 5715:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5716: 
1.620     albertel 5717:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5718:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5719:   if ($domain eq 'public' && $stuname eq 'public') {
                   5720:       $stuname=$ENV{'REMOTE_ADDR'};
                   5721:   }
1.168     albertel 5722:   my %returnhash;
                   5723:   $namespace=~s/\//\_/g;
                   5724:   $namespace=~s/\W//g;
                   5725:   my %hash;
1.1117    foxr     5726:   my $path=LONCAPA::tempdir();
1.168     albertel 5727:   if (tie(%hash,'GDBM_File',
                   5728: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5729: 	  &GDBM_READER(),0640)) {
1.168     albertel 5730:     my $version=$hash{"version:$symb"};
                   5731:     $returnhash{'version'}=$version;
                   5732:     my $scope;
                   5733:     for ($scope=1;$scope<=$version;$scope++) {
                   5734:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5735:       my @keys=split(/:/,$vkeys);
                   5736:       my $key;
                   5737:       $returnhash{"$scope:keys"}=$vkeys;
                   5738:       foreach $key (@keys) {
1.591     albertel 5739: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5740: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5741:       }
                   5742:     }
1.168     albertel 5743:     if (!(untie(%hash))) {
                   5744:       return "error:$!";
                   5745:     }
                   5746:   } else {
                   5747:     return "error:$!";
                   5748:   }
                   5749:   return %returnhash;
1.167     albertel 5750: }
                   5751: 
1.9       www      5752: # ----------------------------------------------------------------------- Store
                   5753: 
                   5754: sub store {
1.1269    raeburn  5755:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5756:     my $home='';
                   5757: 
1.168     albertel 5758:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5759: 
1.213     www      5760:     $symb=&symbclean($symb);
1.122     albertel 5761:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5762: 
1.620     albertel 5763:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5764:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5765: 
                   5766:     &devalidate($symb,$stuname,$domain);
1.109     www      5767: 
                   5768:     $symb=escape($symb);
1.187     www      5769:     if (!$namespace) { 
1.620     albertel 5770:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5771:           return ''; 
                   5772:        } 
                   5773:     }
1.620     albertel 5774:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5775: 
                   5776:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5777:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5778: 
1.12      www      5779:     my $namevalue='';
1.800     albertel 5780:     foreach my $key (keys(%$storehash)) {
                   5781:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5782:     }
1.12      www      5783:     $namevalue=~s/\&$//;
1.187     www      5784:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5785:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5786: }
                   5787: 
1.47      www      5788: # -------------------------------------------------------------- Critical Store
                   5789: 
                   5790: sub cstore {
1.1269    raeburn  5791:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5792:     my $home='';
                   5793: 
1.168     albertel 5794:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5795: 
1.213     www      5796:     $symb=&symbclean($symb);
1.122     albertel 5797:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5798: 
1.620     albertel 5799:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5800:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5801: 
                   5802:     &devalidate($symb,$stuname,$domain);
1.109     www      5803: 
                   5804:     $symb=escape($symb);
1.187     www      5805:     if (!$namespace) { 
1.620     albertel 5806:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5807:           return ''; 
                   5808:        } 
                   5809:     }
1.620     albertel 5810:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5811: 
                   5812:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5813:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5814: 
1.47      www      5815:     my $namevalue='';
1.800     albertel 5816:     foreach my $key (keys(%$storehash)) {
                   5817:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5818:     }
1.47      www      5819:     $namevalue=~s/\&$//;
1.187     www      5820:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5821:     return critical
1.1269    raeburn  5822:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5823: }
                   5824: 
1.9       www      5825: # --------------------------------------------------------------------- Restore
                   5826: 
                   5827: sub restore {
1.124     www      5828:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5829:     my $home='';
                   5830: 
1.168     albertel 5831:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5832: 
1.122     albertel 5833:     if (!$symb) {
1.1224    raeburn  5834:         return if ($namespace eq 'courserequests');
                   5835:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5836:     } else {
1.1224    raeburn  5837:         unless ($namespace eq 'courserequests') {
                   5838:             $symb=&escape(&symbclean($symb));
                   5839:         }
1.122     albertel 5840:     }
1.188     www      5841:     if (!$namespace) { 
1.620     albertel 5842:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5843:           return ''; 
                   5844:        } 
                   5845:     }
1.620     albertel 5846:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5847:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5848:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5849:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5850: 
1.12      www      5851:     my %returnhash=();
1.800     albertel 5852:     foreach my $line (split(/\&/,$answer)) {
                   5853: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5854:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5855:     }
1.75      www      5856:     my $version;
                   5857:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5858:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5859:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5860:        }
1.75      www      5861:     }
1.13      www      5862:     return %returnhash;
1.34      www      5863: }
                   5864: 
                   5865: # ---------------------------------------------------------- Course Description
1.1118    foxr     5866: #
                   5867: #  
1.34      www      5868: 
                   5869: sub coursedescription {
1.731     albertel 5870:     my ($courseid,$args)=@_;
1.34      www      5871:     $courseid=~s/^\///;
1.49      www      5872:     $courseid=~s/\_/\//g;
1.34      www      5873:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5874:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5875:     my $normalid=$cdomain.'_'.$cnum;
                   5876:     # need to always cache even if we get errors otherwise we keep 
                   5877:     # trying and trying and trying to get the course description.
                   5878:     my %envhash=();
                   5879:     my %returnhash=();
1.731     albertel 5880:     
                   5881:     my $expiretime=600;
                   5882:     if ($env{'request.course.id'} eq $normalid) {
                   5883: 	$expiretime=120;
                   5884:     }
                   5885: 
                   5886:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5887:     if (!$args->{'freshen_cache'}
                   5888: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5889: 	foreach my $key (keys(%env)) {
                   5890: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5891: 	    my ($setting) = $1;
                   5892: 	    $returnhash{$setting} = $env{$key};
                   5893: 	}
                   5894: 	return %returnhash;
                   5895:     }
                   5896: 
1.1118    foxr     5897:     # get the data again
                   5898: 
1.731     albertel 5899:     if (!$args->{'one_time'}) {
                   5900: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5901:     }
1.811     albertel 5902: 
1.34      www      5903:     if ($chome ne 'no_host') {
1.302     albertel 5904:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5905:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5906: 	   my $username = $env{'user.name'}; # Defult username
                   5907: 	   if(defined $args->{'user'}) {
                   5908: 	       $username = $args->{'user'};
                   5909: 	   }
1.129     albertel 5910:            $returnhash{'home'}= $chome;
                   5911: 	   $returnhash{'domain'} = $cdomain;
                   5912: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5913:            if (!defined($returnhash{'type'})) {
                   5914:                $returnhash{'type'} = 'Course';
                   5915:            }
1.130     albertel 5916:            while (my ($name,$value) = each %returnhash) {
1.53      www      5917:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5918:            }
1.270     www      5919:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5920:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5921: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5922:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5923:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5924:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5925:        }
                   5926:     }
1.731     albertel 5927:     if (!$args->{'one_time'}) {
1.949     raeburn  5928: 	&appenv(\%envhash);
1.731     albertel 5929:     }
1.302     albertel 5930:     return %returnhash;
1.461     www      5931: }
                   5932: 
1.1080    raeburn  5933: sub update_released_required {
                   5934:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5935:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5936:         $cid = $env{'request.course.id'};
                   5937:         $cdom = $env{'course.'.$cid.'.domain'};
                   5938:         $cnum = $env{'course.'.$cid.'.num'};
                   5939:         $chome = $env{'course.'.$cid.'.home'};
                   5940:     }
                   5941:     if ($needsrelease) {
                   5942:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5943:         my $needsupdate;
                   5944:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5945:             $needsupdate = 1;
                   5946:         } else {
                   5947:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5948:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5949:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5950:                 $needsupdate = 1;
                   5951:             }
                   5952:         }
                   5953:         if ($needsupdate) {
                   5954:             my %needshash = (
                   5955:                              'internal.releaserequired' => $needsrelease,
                   5956:                             );
                   5957:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5958:             if ($putresult eq 'ok') {
                   5959:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5960:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5961:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5962:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5963:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5964:                 }
                   5965:             }
                   5966:         }
                   5967:     }
                   5968:     return;
                   5969: }
                   5970: 
1.461     www      5971: # -------------------------------------------------See if a user is privileged
                   5972: 
                   5973: sub privileged {
1.1219    raeburn  5974:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5975:     my $now = time;
1.1219    raeburn  5976:     my $roles;
                   5977:     if (ref($possroles) eq 'ARRAY') {
                   5978:         $roles = $possroles; 
                   5979:     } else {
                   5980:         $roles = ['dc','su'];
                   5981:     }
                   5982:     if (ref($possdomains) eq 'ARRAY') {
                   5983:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5984:         foreach my $dom (@{$possdomains}) {
                   5985:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5986:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5987:                 foreach my $role (@{$roles}) {
                   5988:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5989:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5990:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5991:                             return 1 unless (($end && $end < $now) ||
                   5992:                                              ($start && $start > $now));
                   5993:                         }
                   5994:                     }
                   5995:                 }
                   5996:             }
                   5997:         }
                   5998:     } else {
                   5999:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6000:         my $now = time;
1.1170    droeschl 6001: 
1.1275    musolffc 6002:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6003:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6004:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6005:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6006:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6007:             }
1.1219    raeburn  6008:         }
                   6009:     }
                   6010:     return 0;
                   6011: }
1.1170    droeschl 6012: 
1.1219    raeburn  6013: sub privileged_by_domain {
                   6014:     my ($domains,$roles) = @_;
                   6015:     my %privileged = ();
                   6016:     my $cachetime = 60*60*24;
                   6017:     my $now = time;
                   6018:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6019:         return %privileged;
                   6020:     }
                   6021:     foreach my $dom (@{$domains}) {
                   6022:         next if (ref($privileged{$dom}) eq 'HASH');
                   6023:         my $needroles;
                   6024:         foreach my $role (@{$roles}) {
                   6025:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6026:             if (defined($cached)) {
                   6027:                 if (ref($result) eq 'HASH') {
                   6028:                     $privileged{$dom}{$role} = $result;
                   6029:                 }
                   6030:             } else {
                   6031:                 $needroles = 1;
                   6032:             }
                   6033:         }
                   6034:         if ($needroles) {
                   6035:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6036:             $privileged{$dom} = {};
                   6037:             foreach my $server (keys(%dompersonnel)) {
                   6038:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6039:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6040:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6041:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6042:                         next if ($end && $end < $now);
                   6043:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6044:                             $dompersonnel{$server}{$item};
                   6045:                     }
                   6046:                 }
                   6047:             }
                   6048:             if (ref($privileged{$dom}) eq 'HASH') {
                   6049:                 foreach my $role (@{$roles}) {
                   6050:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6051:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6052:                     } else {
                   6053:                         my %hash = ();
                   6054:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6055:                     }
                   6056:                 }
                   6057:             }
                   6058:         }
                   6059:     }
                   6060:     return %privileged;
1.9       www      6061: }
1.1       albertel 6062: 
1.103     harris41 6063: # -------------------------------------------------------- Get user privileges
1.11      www      6064: 
                   6065: sub rolesinit {
1.1169    droeschl 6066:     my ($domain, $username) = @_;
                   6067:     my %userroles = ('user.login.time' => time);
                   6068:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6069: 
                   6070:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6071:     # also, blocking can be triggered by an activating timer
                   6072:     # it's saved in the user's %env.
                   6073:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6074:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6075:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6076:         %timerintchk, %timerintenv);
                   6077: 
1.1162    raeburn  6078:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6079:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6080:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6081:     }
1.1169    droeschl 6082: 
1.1162    raeburn  6083:     foreach my $key (keys(%timerinterval)) {
                   6084:         my ($cid,$rest) = split(/\0/,$key);
                   6085:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6086:     }
1.1169    droeschl 6087: 
1.11      www      6088:     my %allroles=();
1.1162    raeburn  6089:     my %allgroups=();
1.11      www      6090: 
1.1274    raeburn  6091:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6092:         my $role = $rolesdump{$area};
                   6093:         $area =~ s/\_\w\w$//;
                   6094: 
                   6095:         my ($trole, $tend, $tstart, $group_privs);
                   6096: 
                   6097:         if ($role =~ /^cr/) {
                   6098:         # Custom role, defined by a user 
                   6099:         # e.g., user.role.cr/msu/smith/mynewrole
                   6100:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6101:                 $trole = $1;
                   6102:                 ($tend, $tstart) = split('_', $2);
                   6103:             } else {
                   6104:                 $trole = $role;
                   6105:             }
                   6106:         } elsif ($role =~ m|^gr/|) {
                   6107:         # Role of member in a group, defined within a course/community
                   6108:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6109:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6110:             next if $tstart eq '-1';
                   6111:             ($trole, $group_privs) = split(/\//, $trole);
                   6112:             $group_privs = &unescape($group_privs);
                   6113:         } else {
                   6114:         # Just a normal role, defined in roles.tab
                   6115:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6116:         }
                   6117: 
                   6118:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6119:                  $username);
                   6120:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6121: 
                   6122:         # role expired or not available yet?
                   6123:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6124:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6125: 
                   6126:         next if $area eq '' or $trole eq '';
                   6127: 
                   6128:         my $spec = "$trole.$area";
                   6129:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6130: 
                   6131:         if ($trole =~ /^cr\//) {
                   6132:         # Custom role, defined by a user
                   6133:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6134:         } elsif ($trole eq 'gr') {
                   6135:         # Role of a member in a group, defined within a course/community
                   6136:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6137:             next;
                   6138:         } else {
                   6139:         # Normal role, defined in roles.tab
                   6140:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6141:         }
                   6142: 
                   6143:         my $cid = $tdomain.'_'.$trest;
                   6144:         unless ($firstaccchk{$cid}) {
                   6145:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6146:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6147:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6148:                         $coursetimerstarts{$cid}{$item}; 
                   6149:                 }
                   6150:             }
                   6151:             $firstaccchk{$cid} = 1;
                   6152:         }
                   6153:         unless ($timerintchk{$cid}) {
                   6154:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6155:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6156:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6157:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6158:                 }
1.12      www      6159:             }
1.1169    droeschl 6160:             $timerintchk{$cid} = 1;
1.191     harris41 6161:         }
1.11      www      6162:     }
1.1169    droeschl 6163: 
1.1341    raeburn  6164:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6165:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6166:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6167:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6168: 
1.1162    raeburn  6169:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6170: }
                   6171: 
1.567     raeburn  6172: sub set_arearole {
1.1215    raeburn  6173:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6174:     unless ($nolog) {
1.567     raeburn  6175: # log the associated role with the area
1.1215    raeburn  6176:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6177:     }
1.743     albertel 6178:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6179: }
                   6180: 
                   6181: sub custom_roleprivs {
                   6182:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6183:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6184:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6185:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6186:         my ($rdummy,$roledef)=
                   6187:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6188:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6189:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6190:             if (defined($syspriv)) {
1.1043    raeburn  6191:                 if ($trest =~ /^$match_community$/) {
                   6192:                     $syspriv =~ s/bre\&S//; 
                   6193:                 }
1.567     raeburn  6194:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6195:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6196:             }
                   6197:             if ($tdomain ne '') {
                   6198:                 if (defined($dompriv)) {
                   6199:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6200:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6201:                 }
                   6202:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6203:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6204:                         my $rolename = $1;
                   6205:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6206:                     }
1.567     raeburn  6207:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6208:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6209:                 }
                   6210:             }
                   6211:         }
                   6212:     }
                   6213: }
                   6214: 
1.1332    raeburn  6215: sub course_adhocrole_privs {
                   6216:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6217:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6218:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6219:         my (%currprivs,%storeprivs);
                   6220:         foreach my $item (split(/:/,$coursepriv)) {
                   6221:             my ($priv,$restrict) = split(/\&/,$item);
                   6222:             $currprivs{$priv} = $restrict;
                   6223:         }
                   6224:         my (%possadd,%possremove,%full);
                   6225:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6226:             my ($priv,$restrict)=split(/\&/,$item);
                   6227:             $full{$priv} = $restrict;
                   6228:         }
                   6229:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6230:              next if ($item eq '');
                   6231:              my ($rule,$rest) = split(/=/,$item);
                   6232:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6233:              foreach my $priv (split(/:/,$rest)) {
                   6234:                  if ($priv ne '') {
                   6235:                      if ($rule eq 'off') {
                   6236:                          $possremove{$priv} = 1;
                   6237:                      } else {
                   6238:                          $possadd{$priv} = 1;
                   6239:                      }
                   6240:                  }
                   6241:              }
                   6242:          }
                   6243:          foreach my $priv (sort(keys(%full))) {
                   6244:              if (exists($currprivs{$priv})) {
                   6245:                  unless (exists($possremove{$priv})) {
                   6246:                      $storeprivs{$priv} = $currprivs{$priv};
                   6247:                  }
                   6248:              } elsif (exists($possadd{$priv})) {
                   6249:                  $storeprivs{$priv} = $full{$priv};
                   6250:              }
                   6251:          }
                   6252:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6253:      }
                   6254:      return $coursepriv;
                   6255: }
                   6256: 
1.678     raeburn  6257: sub group_roleprivs {
                   6258:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6259:     my $access = 1;
                   6260:     my $now = time;
                   6261:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6262:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6263:     if ($access) {
1.811     albertel 6264:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6265:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6266:     }
                   6267: }
1.567     raeburn  6268: 
                   6269: sub standard_roleprivs {
                   6270:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6271:     if (defined($pr{$trole.':s'})) {
                   6272:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6273:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6274:     }
                   6275:     if ($tdomain ne '') {
                   6276:         if (defined($pr{$trole.':d'})) {
                   6277:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6278:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6279:         }
                   6280:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6281:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6282:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6283:         }
                   6284:     }
                   6285: }
                   6286: 
                   6287: sub set_userprivs {
1.1064    raeburn  6288:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6289:     my $author=0;
                   6290:     my $adv=0;
1.1341    raeburn  6291:     my $rar=0;
1.678     raeburn  6292:     my %grouproles = ();
                   6293:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6294:         my @groupkeys; 
1.1000    raeburn  6295:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6296:             push(@groupkeys,$role);
                   6297:         }
                   6298:         if (ref($groups_roles) eq 'HASH') {
                   6299:             foreach my $key (keys(%{$groups_roles})) {
                   6300:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6301:                     push(@groupkeys,$key);
                   6302:                 }
                   6303:             }
                   6304:         }
                   6305:         if (@groupkeys > 0) {
                   6306:             foreach my $role (@groupkeys) {
                   6307:                 my ($trole,$area,$sec,$extendedarea);
                   6308:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6309:                     $trole = $1;
                   6310:                     $area = $2;
                   6311:                     $sec = $3;
                   6312:                     $extendedarea = $area.$sec;
                   6313:                     if (exists($$allgroups{$area})) {
                   6314:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6315:                             my $spec = $trole.'.'.$extendedarea;
                   6316:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6317:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6318:                         }
1.678     raeburn  6319:                     }
                   6320:                 }
                   6321:             }
                   6322:         }
                   6323:     }
1.800     albertel 6324:     foreach my $group (keys(%grouproles)) {
                   6325:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6326:     }
1.800     albertel 6327:     foreach my $role (keys(%{$allroles})) {
                   6328:         my %thesepriv;
1.941     raeburn  6329:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6330:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6331:             if ($item ne '') {
                   6332:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6333:                 if ($restrictions eq '') {
                   6334:                     $thesepriv{$privilege}='F';
                   6335:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6336:                     $thesepriv{$privilege}.=$restrictions;
                   6337:                 }
                   6338:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6339:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6340:             }
                   6341:         }
                   6342:         my $thesestr='';
1.1104    raeburn  6343:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6344: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6345: 	}
                   6346:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6347:     }
1.1341    raeburn  6348:     return ($author,$adv,$rar);
1.567     raeburn  6349: }
                   6350: 
1.994     raeburn  6351: sub role_status {
1.1104    raeburn  6352:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6353:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6354:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6355:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6356:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6357:             $$where = '/'.$two;
1.994     raeburn  6358:             $$trolecode=$$role.'.'.$$where;
                   6359:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6360:             $$tstatus='is';
1.1104    raeburn  6361:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6362:                 $$tstatus='future';
1.1034    raeburn  6363:                 if ($$tstart<$now) {
                   6364:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6365:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6366:                             my (%allroles,%allgroups,$group_privs,
                   6367:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6368:                             my %userroles = (
                   6369:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6370:                             );
1.1064    raeburn  6371:                             @rolecodes = ('cm'); 
1.1002    raeburn  6372:                             my $spec=$$role.'.'.$$where;
                   6373:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6374:                             if ($$role =~ /^cr\//) {
                   6375:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6376:                                 push(@rolecodes,'cr');
1.1002    raeburn  6377:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6378:                                 push(@rolecodes,$$role);
1.1002    raeburn  6379:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6380:                                                     $env{'user.name'});
1.1064    raeburn  6381:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6382:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6383:                                 $group_privs = &unescape($group_privs);
                   6384:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6385:                                 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  6386:                                 &get_groups_roles($tdomain,$trest,
                   6387:                                                   \%course_roles,\@rolecodes,
                   6388:                                                   \%groups_roles);
1.1002    raeburn  6389:                             } else {
1.1064    raeburn  6390:                                 push(@rolecodes,$$role);
1.1002    raeburn  6391:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6392:                             }
1.1341    raeburn  6393:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6394:                                                                    \%groups_roles);
1.1064    raeburn  6395:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6396:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6397:                         }
                   6398:                     }
1.1034    raeburn  6399:                     $$tstatus = 'is';
1.1002    raeburn  6400:                 }
1.994     raeburn  6401:             }
                   6402:             if ($$tend) {
1.1104    raeburn  6403:                 if ($$tend<$update) {
1.994     raeburn  6404:                     $$tstatus='expired';
                   6405:                 } elsif ($$tend<$now) {
                   6406:                     $$tstatus='will_not';
                   6407:                 }
                   6408:             }
                   6409:         }
                   6410:     }
                   6411: }
                   6412: 
1.1104    raeburn  6413: sub get_groups_roles {
                   6414:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6415:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6416:                   (ref($rolecodes) eq 'ARRAY') && 
                   6417:                   (ref($groups_roles) eq 'HASH')); 
                   6418:     if (keys(%{$cdom_courseroles}) > 0) {
                   6419:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6420:         if ($cdom ne '' && $cnum ne '') {
                   6421:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6422:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6423:                     my $crsrole = $1;
                   6424:                     my $crssec = $2;
                   6425:                     if ($crsrole =~ /^cr/) {
                   6426:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6427:                             push(@{$rolecodes},'cr');
                   6428:                         }
                   6429:                     } else {
                   6430:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6431:                             push(@{$rolecodes},$crsrole);
                   6432:                         }
                   6433:                     }
                   6434:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6435:                     if ($crssec ne '') {
                   6436:                         $rolekey .= "/$crssec";
                   6437:                     }
                   6438:                     $rolekey .= './';
                   6439:                     $groups_roles->{$rolekey} = $rolecodes;
                   6440:                 }
                   6441:             }
                   6442:         }
                   6443:     }
                   6444:     return;
                   6445: }
                   6446: 
                   6447: sub delete_env_groupprivs {
                   6448:     my ($where,$courseroles,$possroles) = @_;
                   6449:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6450:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6451:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6452:         %{$courseroles->{$udom}} =
                   6453:             &get_my_roles('','','userroles',['active'],
                   6454:                           $possroles,[$udom],1);
                   6455:     }
                   6456:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6457:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6458:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6459:             my $area = '/'.$cdom.'/'.$cnum;
                   6460:             my $privkey = "user.priv.$crsrole.$area";
                   6461:             if ($crssec ne '') {
                   6462:                 $privkey .= '/'.$crssec;
                   6463:             }
                   6464:             $privkey .= ".$area/$group";
                   6465:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6466:         }
                   6467:     }
                   6468:     return;
                   6469: }
                   6470: 
1.994     raeburn  6471: sub check_adhoc_privs {
1.1329    raeburn  6472:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6473:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6474:     if ($sec) {
                   6475:         $cckey .= '/'.$sec;
                   6476:     } 
1.1185    raeburn  6477:     my $setprivs;
1.994     raeburn  6478:     if ($env{$cckey}) {
                   6479:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6480:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6481:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6482:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6483:             $setprivs = 1;
1.994     raeburn  6484:         }
                   6485:     } else {
1.1330    raeburn  6486:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6487:         $setprivs = 1;
1.994     raeburn  6488:     }
1.1185    raeburn  6489:     return $setprivs;
1.994     raeburn  6490: }
                   6491: 
                   6492: sub set_adhoc_privileges {
1.1326    raeburn  6493: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6494:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6495:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6496:     if ($sec ne '') {
                   6497:         $area .= '/'.$sec;
                   6498:     }
1.994     raeburn  6499:     my $spec = $role.'.'.$area;
                   6500:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6501:                                   $env{'user.name'},1);
1.1326    raeburn  6502:     my %rolehash = ();
1.1332    raeburn  6503:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6504:         my $rolename = $1;
1.1326    raeburn  6505:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6506:         my %domdef = &get_domain_defaults($dcdom);
                   6507:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6508:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6509:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6510:             }
                   6511:         }
1.1326    raeburn  6512:     } else {
                   6513:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6514:     }
1.1341    raeburn  6515:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6516:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6517:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6518:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6519:         &appenv( {'request.role'        => $spec,
                   6520:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6521:                   'request.course.sec'  => $sec,
1.1088    raeburn  6522:                  }
                   6523:                );
                   6524:         my $tadv=0;
                   6525:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6526:         &appenv({'request.role.adv'    => $tadv});
                   6527:     }
1.994     raeburn  6528: }
                   6529: 
1.12      www      6530: # --------------------------------------------------------------- get interface
                   6531: 
                   6532: sub get {
1.131     albertel 6533:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6534:    my $items='';
1.800     albertel 6535:    foreach my $item (@$storearr) {
                   6536:        $items.=&escape($item).'&';
1.191     harris41 6537:    }
1.12      www      6538:    $items=~s/\&$//;
1.620     albertel 6539:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6540:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6541:    my $uhome=&homeserver($uname,$udomain);
                   6542: 
1.133     albertel 6543:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6544:    my @pairs=split(/\&/,$rep);
1.273     albertel 6545:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6546:      return @pairs;
                   6547:    }
1.15      www      6548:    my %returnhash=();
1.42      www      6549:    my $i=0;
1.800     albertel 6550:    foreach my $item (@$storearr) {
                   6551:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6552:       $i++;
1.191     harris41 6553:    }
1.15      www      6554:    return %returnhash;
1.27      www      6555: }
                   6556: 
                   6557: # --------------------------------------------------------------- del interface
                   6558: 
                   6559: sub del {
1.133     albertel 6560:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6561:    my $items='';
1.800     albertel 6562:    foreach my $item (@$storearr) {
                   6563:        $items.=&escape($item).'&';
1.191     harris41 6564:    }
1.984     neumanie 6565: 
1.27      www      6566:    $items=~s/\&$//;
1.620     albertel 6567:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6568:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6569:    my $uhome=&homeserver($uname,$udomain);
                   6570:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6571: }
                   6572: 
                   6573: # -------------------------------------------------------------- dump interface
                   6574: 
1.1180    droeschl 6575: sub unserialize {
                   6576:     my ($rep, $escapedkeys) = @_;
                   6577: 
                   6578:     return {} if $rep =~ /^error/;
                   6579: 
                   6580:     my %returnhash=();
1.1252    raeburn  6581: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6582: 	    my ($key, $value) = split(/=/, $item, 2);
                   6583: 	    $key = unescape($key) unless $escapedkeys;
                   6584: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6585: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6586: 	}
                   6587:     #return %returnhash;
                   6588:     return \%returnhash;
                   6589: }        
                   6590: 
                   6591: # see Lond::dump_with_regexp
                   6592: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6593: sub dump {
1.1180    droeschl 6594:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6595:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6596:     if (!$uname) { $uname=$env{'user.name'}; }
                   6597:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6598: 
1.1266    raeburn  6599:     if ($regexp) {
                   6600:         $regexp=&escape($regexp);
                   6601:     } else {
                   6602:         $regexp='.';
                   6603:     }
1.1180    droeschl 6604:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6605:         # user is hosted on this machine
1.1266    raeburn  6606:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6607:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6608:         return %{unserialize($reply, $escapedkeys)};
                   6609:     }
1.1166    raeburn  6610:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6611:     my @pairs=split(/\&/,$rep);
                   6612:     my %returnhash=();
1.1098    foxr     6613:     if (!($rep =~ /^error/ )) {
                   6614: 	foreach my $item (@pairs) {
                   6615: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6616:         $key = unescape($key) unless $escapedkeys;
                   6617:         #$key = &unescape($key);
1.1098    foxr     6618: 	    next if ($key =~ /^error: 2 /);
                   6619: 	    $returnhash{$key}=&thaw_unescape($value);
                   6620: 	}
1.755     albertel 6621:     }
                   6622:     return %returnhash;
1.407     www      6623: }
                   6624: 
1.1098    foxr     6625: 
1.717     albertel 6626: # --------------------------------------------------------- dumpstore interface
                   6627: 
                   6628: sub dumpstore {
                   6629:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6630:    # same as dump but keys must be escaped. They may contain colon separated
                   6631:    # lists of values that may themself contain colons (e.g. symbs).
                   6632:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6633: }
                   6634: 
1.407     www      6635: # -------------------------------------------------------------- keys interface
                   6636: 
                   6637: sub getkeys {
                   6638:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6639:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6640:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6641:    my $uhome=&homeserver($uname,$udomain);
                   6642:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6643:    my @keyarray=();
1.800     albertel 6644:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6645:       next if ($key =~ /^error: 2 /);
1.800     albertel 6646:       push(@keyarray,&unescape($key));
1.407     www      6647:    }
                   6648:    return @keyarray;
1.318     matthew  6649: }
                   6650: 
1.319     matthew  6651: # --------------------------------------------------------------- currentdump
                   6652: sub currentdump {
1.328     matthew  6653:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6654:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6655:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6656:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6657:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6658:    my $rep;
                   6659: 
                   6660:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6661:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6662:                    $courseid)));
                   6663:    } else {
                   6664:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6665:    }
                   6666: 
1.318     matthew  6667:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6668:    #
1.318     matthew  6669:    my %returnhash=();
1.319     matthew  6670:    #
1.1343    raeburn  6671:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6672:        # an old lond will not know currentdump
                   6673:        # Do a dump and make it look like a currentdump
1.822     albertel 6674:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6675:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6676:        my %hash = @tmp;
                   6677:        @tmp=();
1.424     matthew  6678:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6679:    } else {
                   6680:        my @pairs=split(/\&/,$rep);
1.800     albertel 6681:        foreach my $pair (@pairs) {
                   6682:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6683:            my ($symb,$param) = split(/:/,$key);
                   6684:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6685:                                                         &thaw_unescape($value);
1.319     matthew  6686:        }
1.191     harris41 6687:    }
1.12      www      6688:    return %returnhash;
1.424     matthew  6689: }
                   6690: 
                   6691: sub convert_dump_to_currentdump{
                   6692:     my %hash = %{shift()};
                   6693:     my %returnhash;
                   6694:     # Code ripped from lond, essentially.  The only difference
                   6695:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6696:     # we might run in to problems with parameter names =~ /^v\./
                   6697:     while (my ($key,$value) = each(%hash)) {
                   6698:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6699: 	$symb  = &unescape($symb);
                   6700: 	$param = &unescape($param);
1.424     matthew  6701:         next if ($v eq 'version' || $symb eq 'keys');
                   6702:         next if (exists($returnhash{$symb}) &&
                   6703:                  exists($returnhash{$symb}->{$param}) &&
                   6704:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6705:         $returnhash{$symb}->{$param}=$value;
                   6706:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6707:     }
                   6708:     #
                   6709:     # Remove all of the keys in the hashes which keep track of
                   6710:     # the version of the parameter.
                   6711:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6712:         # use a foreach because we are going to delete from the hash.
                   6713:         foreach my $key (keys(%$param_hash)) {
                   6714:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6715:         }
                   6716:     }
                   6717:     return \%returnhash;
1.12      www      6718: }
                   6719: 
1.627     albertel 6720: # ------------------------------------------------------ critical inc interface
                   6721: 
                   6722: sub cinc {
                   6723:     return &inc(@_,'critical');
                   6724: }
                   6725: 
1.449     matthew  6726: # --------------------------------------------------------------- inc interface
                   6727: 
                   6728: sub inc {
1.627     albertel 6729:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6730:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6731:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6732:     my $uhome=&homeserver($uname,$udomain);
                   6733:     my $items='';
                   6734:     if (! ref($store)) {
                   6735:         # got a single value, so use that instead
                   6736:         $items = &escape($store).'=&';
                   6737:     } elsif (ref($store) eq 'SCALAR') {
                   6738:         $items = &escape($$store).'=&';        
                   6739:     } elsif (ref($store) eq 'ARRAY') {
                   6740:         $items = join('=&',map {&escape($_);} @{$store});
                   6741:     } elsif (ref($store) eq 'HASH') {
                   6742:         while (my($key,$value) = each(%{$store})) {
                   6743:             $items.= &escape($key).'='.&escape($value).'&';
                   6744:         }
                   6745:     }
                   6746:     $items=~s/\&$//;
1.627     albertel 6747:     if ($critical) {
                   6748: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6749:     } else {
                   6750: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6751:     }
1.449     matthew  6752: }
                   6753: 
1.12      www      6754: # --------------------------------------------------------------- put interface
                   6755: 
                   6756: sub put {
1.134     albertel 6757:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6758:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6759:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6760:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6761:    my $items='';
1.800     albertel 6762:    foreach my $item (keys(%$storehash)) {
                   6763:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6764:    }
1.12      www      6765:    $items=~s/\&$//;
1.134     albertel 6766:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6767: }
                   6768: 
1.631     albertel 6769: # ------------------------------------------------------------ newput interface
                   6770: 
                   6771: sub newput {
                   6772:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6773:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6774:    if (!$uname) { $uname=$env{'user.name'}; }
                   6775:    my $uhome=&homeserver($uname,$udomain);
                   6776:    my $items='';
                   6777:    foreach my $key (keys(%$storehash)) {
                   6778:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6779:    }
                   6780:    $items=~s/\&$//;
                   6781:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6782: }
                   6783: 
                   6784: # ---------------------------------------------------------  putstore interface
                   6785: 
1.524     raeburn  6786: sub putstore {
1.1269    raeburn  6787:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6788:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6789:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6790:    my $uhome=&homeserver($uname,$udomain);
                   6791:    my $items='';
1.715     albertel 6792:    foreach my $key (keys(%$storehash)) {
                   6793:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6794:    }
1.715     albertel 6795:    $items=~s/\&$//;
1.716     albertel 6796:    my $esc_symb=&escape($symb);
                   6797:    my $esc_v=&escape($version);
1.715     albertel 6798:    my $reply =
1.716     albertel 6799:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6800: 	      $uhome);
1.1269    raeburn  6801:    if (($tolog) && ($reply eq 'ok')) {
                   6802:        my $namevalue='';
                   6803:        foreach my $key (keys(%{$storehash})) {
                   6804:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6805:        }
                   6806:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6807:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6808:                      '&version='.$esc_v.
                   6809:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6810:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6811:    }
1.715     albertel 6812:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6813:        # gfall back to way things use to be done
1.715     albertel 6814:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6815: 			    $uname);
1.524     raeburn  6816:    }
1.715     albertel 6817:    return $reply;
                   6818: }
                   6819: 
                   6820: sub old_putstore {
1.716     albertel 6821:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6822:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6823:     if (!$uname) { $uname=$env{'user.name'}; }
                   6824:     my $uhome=&homeserver($uname,$udomain);
                   6825:     my %newstorehash;
1.800     albertel 6826:     foreach my $item (keys(%$storehash)) {
                   6827: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6828: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6829:     }
                   6830:     my $items='';
                   6831:     my %allitems = ();
1.800     albertel 6832:     foreach my $item (keys(%newstorehash)) {
                   6833: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6834: 	    my $key = $1.':keys:'.$2;
                   6835: 	    $allitems{$key} .= $3.':';
                   6836: 	}
1.800     albertel 6837: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6838:     }
1.800     albertel 6839:     foreach my $item (keys(%allitems)) {
                   6840: 	$allitems{$item} =~ s/\:$//;
                   6841: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6842:     }
                   6843:     $items=~s/\&$//;
                   6844:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6845: }
                   6846: 
1.47      www      6847: # ------------------------------------------------------ critical put interface
                   6848: 
                   6849: sub cput {
1.134     albertel 6850:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6851:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6852:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6853:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6854:    my $items='';
1.800     albertel 6855:    foreach my $item (keys(%$storehash)) {
                   6856:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6857:    }
1.47      www      6858:    $items=~s/\&$//;
1.134     albertel 6859:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6860: }
                   6861: 
                   6862: # -------------------------------------------------------------- eget interface
                   6863: 
                   6864: sub eget {
1.133     albertel 6865:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6866:    my $items='';
1.800     albertel 6867:    foreach my $item (@$storearr) {
                   6868:        $items.=&escape($item).'&';
1.191     harris41 6869:    }
1.12      www      6870:    $items=~s/\&$//;
1.620     albertel 6871:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6872:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6873:    my $uhome=&homeserver($uname,$udomain);
                   6874:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6875:    my @pairs=split(/\&/,$rep);
                   6876:    my %returnhash=();
1.42      www      6877:    my $i=0;
1.800     albertel 6878:    foreach my $item (@$storearr) {
                   6879:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6880:       $i++;
1.191     harris41 6881:    }
1.12      www      6882:    return %returnhash;
                   6883: }
                   6884: 
1.667     albertel 6885: # ------------------------------------------------------------ tmpput interface
                   6886: sub tmpput {
1.802     raeburn  6887:     my ($storehash,$server,$context)=@_;
1.667     albertel 6888:     my $items='';
1.800     albertel 6889:     foreach my $item (keys(%$storehash)) {
                   6890: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6891:     }
                   6892:     $items=~s/\&$//;
1.802     raeburn  6893:     if (defined($context)) {
                   6894:         $items .= ':'.&escape($context);
                   6895:     }
1.667     albertel 6896:     return &reply("tmpput:$items",$server);
                   6897: }
                   6898: 
                   6899: # ------------------------------------------------------------ tmpget interface
                   6900: sub tmpget {
1.688     albertel 6901:     my ($token,$server)=@_;
                   6902:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6903:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6904:     my %returnhash;
1.1328    raeburn  6905:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6906:         return %returnhash;
                   6907:     }
1.667     albertel 6908:     foreach my $item (split(/\&/,$rep)) {
                   6909: 	my ($key,$value)=split(/=/,$item);
                   6910: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6911:     }
                   6912:     return %returnhash;
                   6913: }
                   6914: 
1.1113    raeburn  6915: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6916: sub tmpdel {
                   6917:     my ($token,$server)=@_;
                   6918:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6919:     return &reply("tmpdel:$token",$server);
                   6920: }
                   6921: 
1.1198    raeburn  6922: # ------------------------------------------------------------ get_timebased_id 
                   6923: 
                   6924: sub get_timebased_id {
                   6925:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6926:         $maxtries) = @_;
                   6927:     my ($newid,$error,$dellock);
                   6928:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6929:         return ('','ok','invalid call to get suffix');
                   6930:     }
                   6931: 
                   6932: # set defaults for any optional args for which values were not supplied
                   6933:     if ($who eq '') {
                   6934:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6935:     }
                   6936:     if (!$locktries) {
                   6937:         $locktries = 3;
                   6938:     }
                   6939:     if (!$maxtries) {
                   6940:         $maxtries = 10;
                   6941:     }
                   6942:     
                   6943:     if (($cdom eq '') || ($cnum eq '')) {
                   6944:         if ($env{'request.course.id'}) {
                   6945:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6946:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6947:         }
                   6948:         if (($cdom eq '') || ($cnum eq '')) {
                   6949:             return ('','ok','call to get suffix not in course context');
                   6950:         }
                   6951:     }
                   6952: 
                   6953: # construct locking item
                   6954:     my $lockhash = {
                   6955:                       $prefix."\0".'locked_'.$keyid => $who,
                   6956:                    };
                   6957:     my $tries = 0;
                   6958: 
                   6959: # attempt to get lock on nohist_$namespace file
                   6960:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6961:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6962:         $tries ++;
                   6963:         sleep 1;
                   6964:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6965:     }
                   6966: 
                   6967: # attempt to get unique identifier, based on current timestamp
                   6968:     if ($gotlock eq 'ok') {
                   6969:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6970:         my $id = time;
                   6971:         $newid = $id;
1.1268    raeburn  6972:         if ($idtype eq 'addcode') {
                   6973:             $newid .= &sixnum_code();
                   6974:         }
1.1198    raeburn  6975:         my $idtries = 0;
                   6976:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6977:             if ($idtype eq 'concat') {
                   6978:                 $newid = $id.$idtries;
1.1268    raeburn  6979:             } elsif ($idtype eq 'addcode') {
                   6980:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6981:             } else {
                   6982:                 $newid ++;
                   6983:             }
                   6984:             $idtries ++;
                   6985:         }
                   6986:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6987:             my %new_item =  (
                   6988:                               $prefix."\0".$newid => $who,
                   6989:                             );
                   6990:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6991:                                                  $cdom,$cnum);
                   6992:             if ($putresult ne 'ok') {
                   6993:                 undef($newid);
                   6994:                 $error = 'error saving new item: '.$putresult;
                   6995:             }
                   6996:         } else {
1.1268    raeburn  6997:              undef($newid);
1.1198    raeburn  6998:              $error = ('error: no unique suffix available for the new item ');
                   6999:         }
                   7000: #  remove lock
                   7001:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7002:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7003:     } else {
                   7004:         $error = "error: could not obtain lockfile\n";
                   7005:         $dellock = 'ok';
1.1276    raeburn  7006:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7007:             $dellock = 'nolock';
                   7008:         }
1.1198    raeburn  7009:     }
                   7010:     return ($newid,$dellock,$error);
                   7011: }
                   7012: 
1.1268    raeburn  7013: sub sixnum_code {
                   7014:     my $code;
                   7015:     for (0..6) {
                   7016:         $code .= int( rand(9) );
                   7017:     }
                   7018:     return $code;
                   7019: }
                   7020: 
1.765     albertel 7021: # -------------------------------------------------- portfolio access checking
                   7022: 
                   7023: sub portfolio_access {
1.1270    raeburn  7024:     my ($requrl,$clientip) = @_;
1.765     albertel 7025:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7026:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7027:     if ($result) {
                   7028:         my %setters;
                   7029:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7030:             my ($startblock,$endblock) =
                   7031:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7032:             if ($startblock && $endblock) {
                   7033:                 return 'B';
                   7034:             }
                   7035:         } else {
                   7036:             my ($startblock,$endblock) =
                   7037:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7038:             if ($startblock && $endblock) {
                   7039:                 return 'B';
                   7040:             }
                   7041:         }
                   7042:     }
1.765     albertel 7043:     if ($result eq 'ok') {
1.766     albertel 7044:        return 'F';
1.765     albertel 7045:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7046:        return 'A';
1.765     albertel 7047:     }
1.766     albertel 7048:     return '';
1.765     albertel 7049: }
                   7050: 
                   7051: sub get_portfolio_access {
1.1270    raeburn  7052:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7053: 
                   7054:     if (!ref($access_hash)) {
                   7055: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7056: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7057: 						   $file_name);
                   7058: 	$access_hash = $access_controls{$file_name};
                   7059:     }
                   7060: 
1.1270    raeburn  7061:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7062:     my $now = time;
                   7063:     if (ref($access_hash) eq 'HASH') {
                   7064:         foreach my $key (keys(%{$access_hash})) {
                   7065:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7066:             if ($start > $now) {
                   7067:                 next;
                   7068:             }
                   7069:             if ($end && $end<$now) {
                   7070:                 next;
                   7071:             }
                   7072:             if ($scope eq 'public') {
                   7073:                 $public = $key;
                   7074:                 last;
                   7075:             } elsif ($scope eq 'guest') {
                   7076:                 $guest = $key;
                   7077:             } elsif ($scope eq 'domains') {
                   7078:                 push(@domains,$key);
                   7079:             } elsif ($scope eq 'users') {
                   7080:                 push(@users,$key);
                   7081:             } elsif ($scope eq 'course') {
                   7082:                 push(@courses,$key);
                   7083:             } elsif ($scope eq 'group') {
                   7084:                 push(@groups,$key);
1.1270    raeburn  7085:             } elsif ($scope eq 'ip') {
                   7086:                 push(@ips,$key);
1.765     albertel 7087:             }
                   7088:         }
                   7089:         if ($public) {
                   7090:             return 'ok';
1.1270    raeburn  7091:         } elsif (@ips > 0) {
                   7092:             my $allowed;
                   7093:             foreach my $ipkey (@ips) {
                   7094:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7095:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7096:                         $allowed = 1;
                   7097:                         last; 
                   7098:                     }
                   7099:                 }
                   7100:             }
                   7101:             if ($allowed) {
                   7102:                 return 'ok';
                   7103:             }
1.765     albertel 7104:         }
                   7105:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7106:             if ($guest) {
                   7107:                 return $guest;
                   7108:             }
                   7109:         } else {
                   7110:             if (@domains > 0) {
                   7111:                 foreach my $domkey (@domains) {
                   7112:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7113:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7114:                             return 'ok';
                   7115:                         }
                   7116:                     }
                   7117:                 }
                   7118:             }
                   7119:             if (@users > 0) {
                   7120:                 foreach my $userkey (@users) {
1.865     raeburn  7121:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7122:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7123:                             if (ref($item) eq 'HASH') {
                   7124:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7125:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7126:                                     return 'ok';
                   7127:                                 }
                   7128:                             }
                   7129:                         }
                   7130:                     } 
1.765     albertel 7131:                 }
                   7132:             }
                   7133:             my %roleshash;
                   7134:             my @courses_and_groups = @courses;
                   7135:             push(@courses_and_groups,@groups); 
                   7136:             if (@courses_and_groups > 0) {
                   7137:                 my (%allgroups,%allroles); 
                   7138:                 my ($start,$end,$role,$sec,$group);
                   7139:                 foreach my $envkey (%env) {
1.1060    raeburn  7140:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7141:                         my $cid = $2.'_'.$3; 
                   7142:                         if ($1 eq 'gr') {
                   7143:                             $group = $4;
                   7144:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7145:                         } else {
                   7146:                             if ($4 eq '') {
                   7147:                                 $sec = 'none';
                   7148:                             } else {
                   7149:                                 $sec = $4;
                   7150:                             }
                   7151:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7152:                         }
1.811     albertel 7153:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7154:                         my $cid = $2.'_'.$3;
                   7155:                         if ($4 eq '') {
                   7156:                             $sec = 'none';
                   7157:                         } else {
                   7158:                             $sec = $4;
                   7159:                         }
                   7160:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7161:                     }
                   7162:                 }
                   7163:                 if (keys(%allroles) == 0) {
                   7164:                     return;
                   7165:                 }
                   7166:                 foreach my $key (@courses_and_groups) {
                   7167:                     my %content = %{$$access_hash{$key}};
                   7168:                     my $cnum = $content{'number'};
                   7169:                     my $cdom = $content{'domain'};
                   7170:                     my $cid = $cdom.'_'.$cnum;
                   7171:                     if (!exists($allroles{$cid})) {
                   7172:                         next;
                   7173:                     }    
                   7174:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7175:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7176:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7177:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7178:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7179:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7180:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7181:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7182:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7183:                                         if (grep/^all$/,@sections) {
                   7184:                                             return 'ok';
                   7185:                                         } else {
                   7186:                                             if (grep/^$sec$/,@sections) {
                   7187:                                                 return 'ok';
                   7188:                                             }
                   7189:                                         }
                   7190:                                     }
                   7191:                                 }
                   7192:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7193:                                     if (grep/^none$/,@groups) {
                   7194:                                         return 'ok';
                   7195:                                     }
                   7196:                                 } else {
                   7197:                                     if (grep/^all$/,@groups) {
                   7198:                                         return 'ok';
                   7199:                                     } 
                   7200:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7201:                                         if (grep/^$group$/,@groups) {
                   7202:                                             return 'ok';
                   7203:                                         }
                   7204:                                     }
                   7205:                                 } 
                   7206:                             }
                   7207:                         }
                   7208:                     }
                   7209:                 }
                   7210:             }
                   7211:             if ($guest) {
                   7212:                 return $guest;
                   7213:             }
                   7214:         }
                   7215:     }
                   7216:     return;
                   7217: }
                   7218: 
                   7219: sub course_group_datechecker {
                   7220:     my ($dates,$now,$status) = @_;
                   7221:     my ($start,$end) = split(/\./,$dates);
                   7222:     if (!$start && !$end) {
                   7223:         return 'ok';
                   7224:     }
                   7225:     if (grep/^active$/,@{$status}) {
                   7226:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7227:             return 'ok';
                   7228:         }
                   7229:     }
                   7230:     if (grep/^previous$/,@{$status}) {
                   7231:         if ($end > $now ) {
                   7232:             return 'ok';
                   7233:         }
                   7234:     }
                   7235:     if (grep/^future$/,@{$status}) {
                   7236:         if ($start > $now) {
                   7237:             return 'ok';
                   7238:         }
                   7239:     }
                   7240:     return; 
                   7241: }
                   7242: 
                   7243: sub parse_portfolio_url {
                   7244:     my ($url) = @_;
                   7245: 
                   7246:     my ($type,$udom,$unum,$group,$file_name);
                   7247:     
1.823     albertel 7248:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7249: 	$type = 1;
                   7250:         $udom = $1;
                   7251:         $unum = $2;
                   7252:         $file_name = $3;
1.823     albertel 7253:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7254: 	$type = 2;
                   7255:         $udom = $1;
                   7256:         $unum = $2;
                   7257:         $group = $3;
                   7258:         $file_name = $3.'/'.$4;
                   7259:     }
                   7260:     if (wantarray) {
                   7261: 	return ($type,$udom,$unum,$file_name,$group);
                   7262:     }
                   7263:     return $type;
                   7264: }
                   7265: 
                   7266: sub is_portfolio_url {
                   7267:     my ($url) = @_;
                   7268:     return scalar(&parse_portfolio_url($url));
                   7269: }
                   7270: 
1.798     raeburn  7271: sub is_portfolio_file {
                   7272:     my ($file) = @_;
1.820     raeburn  7273:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7274:         return 1;
                   7275:     }
                   7276:     return;
                   7277: }
                   7278: 
1.976     raeburn  7279: sub usertools_access {
1.1084    raeburn  7280:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7281:     my ($access,%tools);
                   7282:     if ($context eq '') {
                   7283:         $context = 'tools';
                   7284:     }
                   7285:     if ($context eq 'requestcourses') {
                   7286:         %tools = (
                   7287:                       official   => 1,
                   7288:                       unofficial => 1,
1.1006    raeburn  7289:                       community  => 1,
1.1246    raeburn  7290:                       textbook   => 1,
1.1305    raeburn  7291:                       placement  => 1,
1.1368    raeburn  7292:                       lti        => 1,
1.985     raeburn  7293:                  );
1.1183    raeburn  7294:     } elsif ($context eq 'requestauthor') {
                   7295:         %tools = (
                   7296:                       requestauthor => 1,
                   7297:                  );
1.985     raeburn  7298:     } else {
                   7299:         %tools = (
                   7300:                       aboutme   => 1,
                   7301:                       blog      => 1,
1.1177    raeburn  7302:                       webdav    => 1,
1.985     raeburn  7303:                       portfolio => 1,
                   7304:                  );
                   7305:     }
1.976     raeburn  7306:     return if (!defined($tools{$tool}));
                   7307: 
1.1242    raeburn  7308:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7309:         $udom = $env{'user.domain'};
                   7310:         $uname = $env{'user.name'};
                   7311:     }
                   7312: 
1.978     raeburn  7313:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7314:         if ($action ne 'reload') {
1.985     raeburn  7315:             if ($context eq 'requestcourses') {
                   7316:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7317:             } elsif ($context eq 'requestauthor') {
                   7318:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7319:             } else {
                   7320:                 return $env{'environment.availabletools.'.$tool};
                   7321:             }
                   7322:         }
1.976     raeburn  7323:     }
                   7324: 
1.1183    raeburn  7325:     my ($toolstatus,$inststatus,$envkey);
                   7326:     if ($context eq 'requestauthor') {
                   7327:         $envkey = $context; 
                   7328:     } else {
                   7329:         $envkey = $context.'.'.$tool;
                   7330:     }
1.976     raeburn  7331: 
1.985     raeburn  7332:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7333:          ($action ne 'reload')) {
1.1183    raeburn  7334:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7335:         $inststatus = $env{'environment.inststatus'};
                   7336:     } else {
1.1084    raeburn  7337:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7338:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7339:             $inststatus = $userenvref->{'inststatus'};
                   7340:         } else {
1.1183    raeburn  7341:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7342:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7343:             $inststatus = $userenv{'inststatus'};
                   7344:         }
1.976     raeburn  7345:     }
                   7346: 
                   7347:     if ($toolstatus ne '') {
                   7348:         if ($toolstatus) {
                   7349:             $access = 1;
                   7350:         } else {
                   7351:             $access = 0;
                   7352:         }
                   7353:         return $access;
                   7354:     }
                   7355: 
1.1084    raeburn  7356:     my ($is_adv,%domdef);
                   7357:     if (ref($is_advref) eq 'HASH') {
                   7358:         $is_adv = $is_advref->{'is_adv'};
                   7359:     } else {
                   7360:         $is_adv = &is_advanced_user($udom,$uname);
                   7361:     }
                   7362:     if (ref($domdefref) eq 'HASH') {
                   7363:         %domdef = %{$domdefref};
                   7364:     } else {
                   7365:         %domdef = &get_domain_defaults($udom);
                   7366:     }
1.976     raeburn  7367:     if (ref($domdef{$tool}) eq 'HASH') {
                   7368:         if ($is_adv) {
                   7369:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7370:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7371:                     $access = 1;
                   7372:                 } else {
                   7373:                     $access = 0;
                   7374:                 }
                   7375:                 return $access;
                   7376:             }
                   7377:         }
                   7378:         if ($inststatus ne '') {
                   7379:             my ($hasaccess,$hasnoaccess);
                   7380:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7381:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7382:                     if ($domdef{$tool}{$affiliation}) {
                   7383:                         $hasaccess = 1;
                   7384:                     } else {
                   7385:                         $hasnoaccess = 1;
                   7386:                     }
                   7387:                 }
                   7388:             }
                   7389:             if ($hasaccess || $hasnoaccess) {
                   7390:                 if ($hasaccess) {
                   7391:                     $access = 1;
                   7392:                 } elsif ($hasnoaccess) {
                   7393:                     $access = 0; 
                   7394:                 }
                   7395:                 return $access;
                   7396:             }
                   7397:         } else {
                   7398:             if ($domdef{$tool}{'default'} ne '') {
                   7399:                 if ($domdef{$tool}{'default'}) {
                   7400:                     $access = 1;
                   7401:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7402:                     $access = 0;
                   7403:                 }
                   7404:                 return $access;
                   7405:             }
                   7406:         }
                   7407:     } else {
1.1177    raeburn  7408:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7409:             $access = 1;
                   7410:         } else {
                   7411:             $access = 0;
                   7412:         }
1.976     raeburn  7413:         return $access;
                   7414:     }
                   7415: }
                   7416: 
1.1050    raeburn  7417: sub is_course_owner {
                   7418:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7419:     if (($udom eq '') || ($uname eq '')) {
                   7420:         $udom = $env{'user.domain'};
                   7421:         $uname = $env{'user.name'};
                   7422:     }
                   7423:     unless (($udom eq '') || ($uname eq '')) {
                   7424:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7425:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7426:                 return 1;
                   7427:             } else {
                   7428:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7429:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7430:                     return 1;
                   7431:                 }
                   7432:             }
                   7433:         }
                   7434:     }
                   7435:     return;
                   7436: }
                   7437: 
1.976     raeburn  7438: sub is_advanced_user {
                   7439:     my ($udom,$uname) = @_;
1.1085    raeburn  7440:     if ($udom ne '' && $uname ne '') {
                   7441:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7442:             if (wantarray) {
                   7443:                 return ($env{'user.adv'},$env{'user.author'});
                   7444:             } else {
                   7445:                 return $env{'user.adv'};
                   7446:             }
1.1085    raeburn  7447:         }
                   7448:     }
1.976     raeburn  7449:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7450:     my %allroles;
1.1128    raeburn  7451:     my ($is_adv,$is_author);
1.976     raeburn  7452:     foreach my $role (keys(%roleshash)) {
                   7453:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7454:         my $area = '/'.$tdomain.'/'.$trest;
                   7455:         if ($sec ne '') {
                   7456:             $area .= '/'.$sec;
                   7457:         }
                   7458:         if (($area ne '') && ($trole ne '')) {
                   7459:             my $spec=$trole.'.'.$area;
                   7460:             if ($trole =~ /^cr\//) {
                   7461:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7462:             } elsif ($trole ne 'gr') {
                   7463:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7464:             }
1.1128    raeburn  7465:             if ($trole eq 'au') {
                   7466:                 $is_author = 1;
                   7467:             }
1.976     raeburn  7468:         }
                   7469:     }
                   7470:     foreach my $role (keys(%allroles)) {
                   7471:         last if ($is_adv);
                   7472:         foreach my $item (split(/:/,$allroles{$role})) {
                   7473:             if ($item ne '') {
                   7474:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7475:                 if ($privilege eq 'adv') {
                   7476:                     $is_adv = 1;
                   7477:                     last;
                   7478:                 }
                   7479:             }
                   7480:         }
                   7481:     }
1.1128    raeburn  7482:     if (wantarray) {
                   7483:         return ($is_adv,$is_author);
                   7484:     }
1.976     raeburn  7485:     return $is_adv;
                   7486: }
1.798     raeburn  7487: 
1.1035    raeburn  7488: sub check_can_request {
1.1368    raeburn  7489:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7490:     my $canreq = 0;
1.1368    raeburn  7491:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7492:         $uname = $env{'user.name'};
                   7493:         $udom = $env{'user.domain'};
                   7494:     }
1.1035    raeburn  7495:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7496:     my @options = ('approval','validate','autolimit');
                   7497:     my $optregex = join('|',@options);
                   7498:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7499:         foreach my $type (@{$types}) {
1.1368    raeburn  7500:             if (&usertools_access($uname,$udom,$type,undef,
                   7501:                                   'requestcourses')) {
1.1035    raeburn  7502:                 $canreq ++;
1.1036    raeburn  7503:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7504:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7505:                 }
1.1368    raeburn  7506:                 if ($dom eq $udom) {
1.1035    raeburn  7507:                     $can_request->{$type} = 1;
                   7508:                 }
                   7509:             }
1.1368    raeburn  7510:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7511:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7512:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7513:                 if (@curr > 0) {
1.1036    raeburn  7514:                     foreach my $item (@curr) {
                   7515:                         if (ref($request_domains) eq 'HASH') {
                   7516:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7517:                             if ($otherdom ne '') {
                   7518:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7519:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7520:                                         push(@{$request_domains->{$type}},$otherdom);
                   7521:                                     }
                   7522:                                 } else {
                   7523:                                     push(@{$request_domains->{$type}},$otherdom);
                   7524:                                 }
                   7525:                             }
                   7526:                         }
                   7527:                     }
1.1368    raeburn  7528:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7529:                         $canreq ++;
1.1035    raeburn  7530:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7531:                             $can_request->{$type} = 1;
                   7532:                         }
                   7533:                     }
                   7534:                 }
                   7535:             }
                   7536:         }
                   7537:     }
                   7538:     return $canreq;
                   7539: }
                   7540: 
1.341     www      7541: # ---------------------------------------------- Custom access rule evaluation
                   7542: 
                   7543: sub customaccess {
                   7544:     my ($priv,$uri)=@_;
1.807     albertel 7545:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7546:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7547:     $udom = &LONCAPA::clean_domain($udom);
                   7548:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7549:     my $access=0;
1.800     albertel 7550:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7551: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7552: 	if ($type eq 'user') {
                   7553: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7554: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7555: 		if ($tdom) {
                   7556: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7557: 		}
1.896     albertel 7558: 		if ($tuname) {
                   7559: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7560: 		}
                   7561: 		$access=($effect eq 'allow');
                   7562: 		last;
                   7563: 	    }
                   7564: 	} else {
                   7565: 	    if ($role) {
                   7566: 		if ($role ne $urole) { next; }
                   7567: 	    }
                   7568: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7569: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7570: 		if ($tdom) {
                   7571: 		    if ($tdom ne $udom) { next; }
                   7572: 		}
                   7573: 		if ($tcrs) {
                   7574: 		    if ($tcrs ne $ucrs) { next; }
                   7575: 		}
                   7576: 		if ($tsec) {
                   7577: 		    if ($tsec ne $usec) { next; }
                   7578: 		}
                   7579: 		$access=($effect eq 'allow');
                   7580: 		last;
                   7581: 	    }
                   7582: 	    if ($realm eq '' && $role eq '') {
                   7583: 		$access=($effect eq 'allow');
                   7584: 	    }
1.402     bowersj2 7585: 	}
1.341     www      7586:     }
                   7587:     return $access;
                   7588: }
                   7589: 
1.103     harris41 7590: # ------------------------------------------------- Check for a user privilege
1.12      www      7591: 
                   7592: sub allowed {
1.1281    raeburn  7593:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7594:     my $ver_orguri=$uri;
1.439     www      7595:     $uri=&deversion($uri);
1.152     www      7596:     my $orguri=$uri;
1.52      www      7597:     $uri=&declutter($uri);
1.809     raeburn  7598: 
1.810     raeburn  7599:     if ($priv eq 'evb') {
                   7600: # Evade communication block restrictions for specified role in a course
                   7601:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7602:             return $1;
                   7603:         } else {
                   7604:             return;
                   7605:         }
                   7606:     }
                   7607: 
1.620     albertel 7608:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7609: # Free bre access to adm and meta resources
1.1343    raeburn  7610:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7611: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7612: 	&& ($priv eq 'bre')) {
1.14      www      7613: 	return 'F';
1.159     www      7614:     }
                   7615: 
1.545     banghart 7616: # Free bre access to user's own portfolio contents
1.714     raeburn  7617:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7618:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7619: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7620:         my %setters;
                   7621:         my ($startblock,$endblock) = 
                   7622:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7623:         if ($startblock && $endblock) {
                   7624:             return 'B';
                   7625:         } else {
                   7626:             return 'F';
                   7627:         }
1.545     banghart 7628:     }
                   7629: 
1.762     raeburn  7630: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7631:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7632:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7633:         if (exists($env{'request.course.id'})) {
                   7634:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7635:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7636:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7637:                 my $courseprivid=$env{'request.course.id'};
                   7638:                 $courseprivid=~s/\_/\//;
                   7639:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7640:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7641:                     return $1; 
1.762     raeburn  7642:                 } else {
                   7643:                     if ($env{'request.course.sec'}) {
                   7644:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7645:                     }
                   7646:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7647:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7648:                         return $2;
                   7649:                     }
1.714     raeburn  7650:                 }
                   7651:             }
                   7652:         }
                   7653:     }
                   7654: 
1.159     www      7655: # Free bre to public access
                   7656: 
                   7657:     if ($priv eq 'bre') {
1.1362    raeburn  7658:         my $copyright;
                   7659:         unless ($uri =~ /ext\.tool/) {
                   7660:             $copyright=&metadata($uri,'copyright');
                   7661:         }
1.620     albertel 7662: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7663:            return 'F'; 
                   7664:         }
1.238     www      7665:         if ($copyright eq 'priv') {
                   7666:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7667: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7668: 		return '';
                   7669:             }
                   7670:         }
                   7671:         if ($copyright eq 'domain') {
                   7672:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7673: 	    unless (($env{'user.domain'} eq $1) ||
                   7674:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7675: 		return '';
                   7676:             }
1.262     matthew  7677:         }
1.620     albertel 7678:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7679:             # Library role, so allow browsing of resources in this domain.
                   7680:             return 'F';
1.238     www      7681:         }
1.341     www      7682:         if ($copyright eq 'custom') {
                   7683: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7684:         }
1.14      www      7685:     }
1.264     matthew  7686:     # Domain coordinator is trying to create a course
1.620     albertel 7687:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7688:         # uri is the requested domain in this case.
                   7689:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7690:         # a role of dc for the domain in question.
1.620     albertel 7691:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7692:     }
1.29      www      7693: 
1.52      www      7694:     my $thisallowed='';
                   7695:     my $statecond=0;
                   7696:     my $courseprivid='';
                   7697: 
1.1039    raeburn  7698:     my $ownaccess;
1.1043    raeburn  7699:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7700:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7701:         if ($uri eq '') {
                   7702:             $ownaccess = 1;
                   7703:         } else {
                   7704:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7705:                 my $udom = $env{'user.domain'};
                   7706:                 my $uname = $env{'user.name'};
                   7707:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7708:                     $ownaccess = 1;
1.1040    raeburn  7709:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7710:                     unless ($uri =~ m{\.\./}) {
                   7711:                         $ownaccess = 1;
                   7712:                     }
                   7713:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7714:                     my $now = time;
                   7715:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7716:                         my $adom = $1;
                   7717:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7718:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7719:                                 my ($start,$end) = split('.',$env{$key});
                   7720:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7721:                                     $ownaccess = 1;
                   7722:                                     last;
                   7723:                                 }
                   7724:                             }
                   7725:                         }
                   7726:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7727:                         my $adom = $1;
                   7728:                         my $aname = $2;
1.1042    raeburn  7729:                         foreach my $role ('ca','aa') { 
                   7730:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7731:                                 my ($start,$end) =
                   7732:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7733:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7734:                                     $ownaccess = 1;
                   7735:                                     last;
                   7736:                                 }
1.1039    raeburn  7737:                             }
                   7738:                         }
                   7739:                     }
                   7740:                 }
                   7741:             }
                   7742:         }
                   7743:     }
                   7744: 
1.52      www      7745: # Course
                   7746: 
1.620     albertel 7747:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7748:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7749:             $thisallowed.=$1;
                   7750:         }
1.52      www      7751:     }
1.29      www      7752: 
1.52      www      7753: # Domain
                   7754: 
1.620     albertel 7755:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7756:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7757:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7758:             $thisallowed.=$1;
                   7759:         }
1.12      www      7760:     }
1.52      www      7761: 
1.1141    raeburn  7762: # User who is not author or co-author might still be able to edit
                   7763: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7764:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7765:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7766:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7767:             $thisallowed.=$1;
                   7768:         }
                   7769:     }
                   7770: 
1.52      www      7771: # Course: uri itself is a course
1.66      www      7772:     my $courseuri=$uri;
                   7773:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7774:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7775: 
1.620     albertel 7776:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7777:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7778:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7779:             $thisallowed.=$1;
                   7780:         }
1.12      www      7781:     }
1.29      www      7782: 
1.665     albertel 7783: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7784: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7785:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7786: 	$thisallowed='';
1.671     raeburn  7787:         my ($match)=&is_on_map($uri);
                   7788:         if ($match) {
                   7789:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7790:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7791:                 my $value = $1;
                   7792:                 if ($noblockcheck) {
                   7793:                     $thisallowed.=$value;
1.1162    raeburn  7794:                 } else {
1.1281    raeburn  7795:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7796:                     if (@blockers > 0) {
                   7797:                         $thisallowed = 'B';
                   7798:                     } else {
                   7799:                         $thisallowed.=$value;
                   7800:                     }
1.1162    raeburn  7801:                 }
1.671     raeburn  7802:             }
                   7803:         } else {
1.705     albertel 7804:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7805:             if ($refuri) {
                   7806:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7807:                     $thisallowed='F';
1.671     raeburn  7808:                 } else {
                   7809:                     $refuri=&declutter($refuri);
                   7810:                     my ($match) = &is_on_map($refuri);
                   7811:                     if ($match) {
1.1281    raeburn  7812:                         if ($noblockcheck) {
                   7813:                             $thisallowed='F';
1.1162    raeburn  7814:                         } else {
1.1281    raeburn  7815:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7816:                             if (@blockers > 0) {
                   7817:                                 $thisallowed = 'B';
                   7818:                             } else {
                   7819:                                 $thisallowed='F';
                   7820:                             }
1.1162    raeburn  7821:                         }
1.671     raeburn  7822:                     }
1.669     raeburn  7823:                 }
1.671     raeburn  7824:             }
                   7825:         }
1.314     www      7826:     }
1.492     albertel 7827: 
1.766     albertel 7828:     if ($priv eq 'bre'
                   7829: 	&& $thisallowed ne 'F' 
                   7830: 	&& $thisallowed ne '2'
                   7831: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7832: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7833:     }
1.1250    raeburn  7834: 
1.52      www      7835: # Full access at system, domain or course-wide level? Exit.
1.29      www      7836:     if ($thisallowed=~/F/) {
                   7837: 	return 'F';
                   7838:     }
                   7839: 
1.52      www      7840: # If this is generating or modifying users, exit with special codes
1.29      www      7841: 
1.643     www      7842:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7843: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7844: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7845: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7846: 	    unless ($auname) { return $thisallowed; }
                   7847: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7848: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7849: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7850: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7851: 	}
1.52      www      7852: 	return $thisallowed;
                   7853:     }
                   7854: #
1.103     harris41 7855: # Gathered so far: system, domain and course wide privileges
1.52      www      7856: #
                   7857: # Course: See if uri or referer is an individual resource that is part of 
                   7858: # the course
                   7859: 
1.620     albertel 7860:     if ($env{'request.course.id'}) {
1.232     www      7861: 
1.620     albertel 7862:        $courseprivid=$env{'request.course.id'};
                   7863:        if ($env{'request.course.sec'}) {
                   7864:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7865:        }
                   7866:        $courseprivid=~s/\_/\//;
                   7867:        my $checkreferer=1;
1.232     www      7868:        my ($match,$cond)=&is_on_map($uri);
                   7869:        if ($match) {
                   7870:            $statecond=$cond;
1.620     albertel 7871:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7872:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7873:                my $value = $1;
                   7874:                if ($priv eq 'bre') {
1.1281    raeburn  7875:                    if ($noblockcheck) {
                   7876:                        $thisallowed.=$value;
1.1162    raeburn  7877:                    } else {
1.1281    raeburn  7878:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7879:                        if (@blockers > 0) {
                   7880:                            $thisallowed = 'B';
                   7881:                        } else {
                   7882:                            $thisallowed.=$value;
                   7883:                        }
1.1162    raeburn  7884:                    }
                   7885:                } else {
                   7886:                    $thisallowed.=$value;
                   7887:                }
1.52      www      7888:                $checkreferer=0;
                   7889:            }
1.29      www      7890:        }
1.83      www      7891:        
1.148     www      7892:        if ($checkreferer) {
1.620     albertel 7893: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7894:             unless ($refuri) {
1.800     albertel 7895:                 foreach my $key (keys(%env)) {
                   7896: 		    if ($key=~/^httpref\..*\*/) {
                   7897: 			my $pattern=$key;
1.156     www      7898:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7899:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7900:                         $pattern=~s/\//\\\//g;
1.152     www      7901:                         if ($orguri=~/$pattern/) {
1.800     albertel 7902: 			    $refuri=$env{$key};
1.148     www      7903:                         }
                   7904:                     }
1.191     harris41 7905:                 }
1.148     www      7906:             }
1.232     www      7907: 
1.148     www      7908:          if ($refuri) { 
1.152     www      7909: 	  $refuri=&declutter($refuri);
1.232     www      7910:           my ($match,$cond)=&is_on_map($refuri);
                   7911:             if ($match) {
                   7912:               my $refstatecond=$cond;
1.620     albertel 7913:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7914:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7915:                   my $value = $1;
                   7916:                   if ($priv eq 'bre') {
1.1281    raeburn  7917:                       if ($noblockcheck) {
                   7918:                           $thisallowed.=$value;
1.1162    raeburn  7919:                       } else {
1.1281    raeburn  7920:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7921:                           if (@blockers > 0) {
                   7922:                               $thisallowed = 'B';
                   7923:                           } else {
                   7924:                               $thisallowed.=$value;
                   7925:                           }
1.1162    raeburn  7926:                       }
                   7927:                   } else {
                   7928:                       $thisallowed.=$value;
                   7929:                   }
1.53      www      7930:                   $uri=$refuri;
                   7931:                   $statecond=$refstatecond;
1.52      www      7932:               }
                   7933:           }
1.148     www      7934:         }
1.29      www      7935:        }
1.52      www      7936:    }
1.29      www      7937: 
1.52      www      7938: #
1.103     harris41 7939: # Gathered now: all privileges that could apply, and condition number
1.52      www      7940: # 
                   7941: #
                   7942: # Full or no access?
                   7943: #
1.29      www      7944: 
1.52      www      7945:     if ($thisallowed=~/F/) {
                   7946: 	return 'F';
                   7947:     }
1.29      www      7948: 
1.52      www      7949:     unless ($thisallowed) {
                   7950:         return '';
                   7951:     }
1.29      www      7952: 
1.52      www      7953: # Restrictions exist, deal with them
                   7954: #
                   7955: #   C:according to course preferences
                   7956: #   R:according to resource settings
                   7957: #   L:unless locked
                   7958: #   X:according to user session state
                   7959: #
                   7960: 
                   7961: # Possibly locked functionality, check all courses
1.54      www      7962: # Locks might take effect only after 10 minutes cache expiration for other
                   7963: # courses, and 2 minutes for current course
1.52      www      7964: 
                   7965:     my $envkey;
                   7966:     if ($thisallowed=~/L/) {
1.1000    raeburn  7967:         foreach $envkey (keys(%env)) {
1.54      www      7968:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7969:                my $courseid=$2;
                   7970:                my $roleid=$1.'.'.$2;
1.92      www      7971:                $courseid=~s/^\///;
1.54      www      7972:                my $expiretime=600;
1.620     albertel 7973:                if ($env{'request.role'} eq $roleid) {
1.54      www      7974: 		  $expiretime=120;
                   7975:                }
                   7976: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7977:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7978:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7979: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7980:                }
1.620     albertel 7981:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7982:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7983: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7984:                        &log($env{'user.domain'},$env{'user.name'},
                   7985:                             $env{'user.home'},
1.57      www      7986:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7987:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7988:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7989: 		       return '';
                   7990:                    }
                   7991:                }
1.620     albertel 7992:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7993:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7994: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7995:                        &log($env{'user.domain'},$env{'user.name'},
                   7996:                             $env{'user.home'},
1.57      www      7997:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7998:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7999:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8000: 		       return '';
                   8001:                    }
                   8002:                }
                   8003: 	   }
1.29      www      8004:        }
1.52      www      8005:     }
                   8006:    
                   8007: #
                   8008: # Rest of the restrictions depend on selected course
                   8009: #
                   8010: 
1.620     albertel 8011:     unless ($env{'request.course.id'}) {
1.766     albertel 8012: 	if ($thisallowed eq 'A') {
                   8013: 	    return 'A';
1.814     raeburn  8014:         } elsif ($thisallowed eq 'B') {
                   8015:             return 'B';
1.766     albertel 8016: 	} else {
                   8017: 	    return '1';
                   8018: 	}
1.52      www      8019:     }
1.29      www      8020: 
1.52      www      8021: #
                   8022: # Now user is definitely in a course
                   8023: #
1.53      www      8024: 
                   8025: 
                   8026: # Course preferences
                   8027: 
                   8028:    if ($thisallowed=~/C/) {
1.620     albertel 8029:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8030:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8031:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8032: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8033: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8034: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8035: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8036: 			$env{'request.course.id'});
                   8037: 	   }
1.237     www      8038:            return '';
                   8039:        }
                   8040: 
1.620     albertel 8041:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8042: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8043: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8044: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8045: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8046: 			$env{'request.course.id'});
                   8047: 	   }
1.54      www      8048:            return '';
                   8049:        }
1.53      www      8050:    }
                   8051: 
                   8052: # Resource preferences
                   8053: 
                   8054:    if ($thisallowed=~/R/) {
1.620     albertel 8055:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8056:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8057: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8058: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8059: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8060: 	   }
                   8061: 	   return '';
1.54      www      8062:        }
1.53      www      8063:    }
1.30      www      8064: 
1.246     www      8065: # Restricted by state or randomout?
1.30      www      8066: 
1.52      www      8067:    if ($thisallowed=~/X/) {
1.620     albertel 8068:       if ($env{'acc.randomout'}) {
1.579     albertel 8069: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8070:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8071:             return ''; 
                   8072:          }
1.247     www      8073:       }
                   8074:       if (&condval($statecond)) {
1.52      www      8075: 	 return '2';
                   8076:       } else {
                   8077:          return '';
                   8078:       }
                   8079:    }
1.30      www      8080: 
1.766     albertel 8081:     if ($thisallowed eq 'A') {
                   8082: 	return 'A';
1.814     raeburn  8083:     } elsif ($thisallowed eq 'B') {
                   8084:         return 'B';
1.766     albertel 8085:     }
1.52      www      8086:    return 'F';
1.232     www      8087: }
1.1162    raeburn  8088: 
1.1192    raeburn  8089: # ------------------------------------------- Check construction space access
                   8090: 
                   8091: sub constructaccess {
                   8092:     my ($url,$setpriv)=@_;
                   8093: 
                   8094: # We do not allow editing of previous versions of files
                   8095:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8096: 
                   8097: # Get username and domain from URL
                   8098:     my ($ownername,$ownerdomain,$ownerhome);
                   8099: 
                   8100:     ($ownerdomain,$ownername) =
1.1325    raeburn  8101:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8102: 
                   8103: # The URL does not really point to any authorspace, forget it
                   8104:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8105: 
                   8106: # Now we need to see if the user has access to the authorspace of
                   8107: # $ownername at $ownerdomain
                   8108: 
                   8109:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8110: # Real author for this?
                   8111:        $ownerhome = $env{'user.home'};
                   8112:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8113:           return ($ownername,$ownerdomain,$ownerhome);
                   8114:        }
                   8115:     } else {
                   8116: # Co-author for this?
                   8117:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8118:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8119:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8120:             return ($ownername,$ownerdomain,$ownerhome);
                   8121:         }
1.1312    raeburn  8122:         if ($env{'request.course.id'}) {
                   8123:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8124:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8125:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8126:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8127:                     return ($ownername,$ownerdomain,$ownerhome);
                   8128:                 }
                   8129:             }
                   8130:         }
1.1192    raeburn  8131:     }
                   8132: 
                   8133: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8134: # we might as well leave
                   8135:    unless ($setpriv) { return ''; }
                   8136: 
                   8137: # Backdoor access?
                   8138:     my $allowed=&allowed('eco',$ownerdomain);
                   8139: # Nope
                   8140:     unless ($allowed) { return ''; }
                   8141: # Looks like we may have access, but could be locked by the owner of the construction space
                   8142:     if ($allowed eq 'U') {
                   8143:         my %blocked=&get('environment',['domcoord.author'],
                   8144:                          $ownerdomain,$ownername);
                   8145: # Is blocked by owner
                   8146:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8147:     }
                   8148:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8149: # Grant temporary access
                   8150:         my $then=$env{'user.login.time'};
1.1209    raeburn  8151:         my $update=$env{'user.update.time'};
1.1192    raeburn  8152:         if (!$update) { $update = $then; }
                   8153:         my $refresh=$env{'user.refresh.time'};
                   8154:         if (!$refresh) { $refresh = $update; }
                   8155:         my $now = time;
                   8156:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8157:                            $now,'ca','constructaccess');
                   8158:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8159:         return($ownername,$ownerdomain,$ownerhome);
                   8160:     }
                   8161: # No business here
                   8162:     return '';
                   8163: }
                   8164: 
1.1282    raeburn  8165: # ----------------------------------------------------------- Content Blocking
                   8166: 
                   8167: {
                   8168: # Caches for faster Course Contents display where content blocking
                   8169: # is in operation (i.e., interval param set) for timed quiz.
                   8170: #
                   8171: # User for whom data are being temporarily cached.
                   8172: my $cacheduser='';
                   8173: # Cached blockers for this user (a hash of blocking items). 
                   8174: my %cachedblockers=();
                   8175: # When the data were last cached.
                   8176: my $cachedlast='';
                   8177: 
                   8178: sub load_all_blockers {
                   8179:     my ($uname,$udom,$blocks)=@_;
                   8180:     if (($uname ne '') && ($udom ne '')) { 
                   8181:         if (($cacheduser eq $uname.':'.$udom) &&
                   8182:             (abs($cachedlast-time)<5)) {
                   8183:             return;
                   8184:         }
                   8185:     }
                   8186:     $cachedlast=time;
                   8187:     $cacheduser=$uname.':'.$udom;
                   8188:     %cachedblockers = &get_commblock_resources($blocks);
                   8189: }
                   8190: 
1.1162    raeburn  8191: sub get_comm_blocks {
                   8192:     my ($cdom,$cnum) = @_;
                   8193:     if ($cdom eq '' || $cnum eq '') {
                   8194:         return unless ($env{'request.course.id'});
                   8195:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8196:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8197:     }
                   8198:     my %commblocks;
                   8199:     my $hashid=$cdom.'_'.$cnum;
                   8200:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8201:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8202:         %commblocks = %{$blocksref};
                   8203:     } else {
                   8204:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8205:         my $cachetime = 600;
                   8206:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8207:     }
                   8208:     return %commblocks;
                   8209: }
                   8210: 
1.1282    raeburn  8211: sub get_commblock_resources {
                   8212:     my ($blocks) = @_;
                   8213:     my %blockers = ();
                   8214:     return %blockers unless ($env{'request.course.id'});
                   8215:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8216:     my %commblocks;
                   8217:     if (ref($blocks) eq 'HASH') {
                   8218:         %commblocks = %{$blocks};
                   8219:     } else {
                   8220:         %commblocks = &get_comm_blocks();
                   8221:     }
1.1282    raeburn  8222:     return %blockers unless (keys(%commblocks) > 0); 
                   8223:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8224:     return %blockers unless (ref($navmap));
1.1162    raeburn  8225:     my $now = time;
                   8226:     foreach my $block (keys(%commblocks)) {
                   8227:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8228:             my ($start,$end) = ($1,$2);
                   8229:             if ($start <= $now && $end >= $now) {
                   8230:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8231:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8232:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8233:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8234:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8235:                             }
                   8236:                         }
                   8237:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8238:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8239:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8240:                             }
                   8241:                         }
                   8242:                     }
                   8243:                 }
                   8244:             }
                   8245:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8246:             my $item = $1;
1.1163    raeburn  8247:             my @to_test;
1.1162    raeburn  8248:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8249:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8250:                     my @interval;
                   8251:                     my $type = 'map';
                   8252:                     if ($item eq 'course') {
                   8253:                         $type = 'course';
                   8254:                         @interval=&EXT("resource.0.interval");
                   8255:                     } else {
                   8256:                         if ($item =~ /___\d+___/) {
                   8257:                             $type = 'resource';
                   8258:                             @interval=&EXT("resource.0.interval",$item);
                   8259:                             if (ref($navmap)) {                        
                   8260:                                 my $res = $navmap->getBySymb($item); 
                   8261:                                 push(@to_test,$res);
                   8262:                             }
1.1162    raeburn  8263:                         } else {
1.1282    raeburn  8264:                             my $mapsymb = &symbread($item,1);
                   8265:                             if ($mapsymb) {
                   8266:                                 if (ref($navmap)) {
                   8267:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8268:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8269:                                     foreach my $res (@to_test) {
                   8270:                                         my $symb = $res->symb();
                   8271:                                         next if ($symb eq $mapsymb);
                   8272:                                         if ($symb ne '') {
                   8273:                                             @interval=&EXT("resource.0.interval",$symb);
                   8274:                                             if ($interval[1] eq 'map') {
                   8275:                                                 last;
1.1162    raeburn  8276:                                             }
                   8277:                                         }
                   8278:                                     }
                   8279:                                 }
                   8280:                             }
                   8281:                         }
1.1282    raeburn  8282:                     }
1.1310    raeburn  8283:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8284:                         my $timelimit = $1; 
1.1282    raeburn  8285:                         my $first_access;
                   8286:                         if ($type eq 'resource') {
                   8287:                             $first_access=&get_first_access($interval[1],$item);
                   8288:                         } elsif ($type eq 'map') {
                   8289:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8290:                         } else {
                   8291:                             $first_access=&get_first_access($interval[1]);
                   8292:                         }
                   8293:                         if ($first_access) {
1.1292    raeburn  8294:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8295:                             if ($timesup > $now) {
                   8296:                                 my $activeblock;
                   8297:                                 foreach my $res (@to_test) {
1.1283    raeburn  8298:                                     if ($res->answerable()) {
1.1282    raeburn  8299:                                         $activeblock = 1;
                   8300:                                         last;
                   8301:                                     }
                   8302:                                 }
                   8303:                                 if ($activeblock) {
                   8304:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8305:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8306:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8307:                                          }
                   8308:                                     }
                   8309:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8310:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8311:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8312:                                         }
1.1162    raeburn  8313:                                     }
                   8314:                                 }
                   8315:                             }
                   8316:                         }
                   8317:                     }
                   8318:                 }
                   8319:             }
                   8320:         }
                   8321:     }
1.1282    raeburn  8322:     return %blockers;
1.1162    raeburn  8323: }
                   8324: 
1.1282    raeburn  8325: sub has_comm_blocking {
                   8326:     my ($priv,$symb,$uri,$blocks) = @_;
                   8327:     my @blockers;
                   8328:     return unless ($env{'request.course.id'});
                   8329:     return unless ($priv eq 'bre');
                   8330:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8331:     return if ($env{'request.state'} eq 'construct');
                   8332:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8333:     return unless (keys(%cachedblockers) > 0);
                   8334:     my (%possibles,@symbs);
                   8335:     if (!$symb) {
                   8336:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8337:     }
1.1282    raeburn  8338:     if ($symb) {
                   8339:         @symbs = ($symb);
                   8340:     } elsif (keys(%possibles)) { 
                   8341:         @symbs = keys(%possibles);
                   8342:     }
                   8343:     my $noblock;
                   8344:     foreach my $symb (@symbs) {
                   8345:         last if ($noblock);
                   8346:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8347:         foreach my $block (keys(%cachedblockers)) {
                   8348:             if ($block =~ /^firstaccess____(.+)$/) {
                   8349:                 my $item = $1;
                   8350:                 if (($item eq $map) || ($item eq $symb)) {
                   8351:                     $noblock = 1;
                   8352:                     last;
                   8353:                 }
                   8354:             }
                   8355:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8356:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8357:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8358:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8359:                             push(@blockers,$block);
                   8360:                         }
                   8361:                     }
                   8362:                 }
1.1162    raeburn  8363:             }
1.1282    raeburn  8364:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8365:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8366:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8367:                         push(@blockers,$block);
                   8368:                     }
                   8369:                 }
1.1162    raeburn  8370:             }
                   8371:         }
                   8372:     }
1.1282    raeburn  8373:     return if ($noblock);
                   8374:     return @blockers;
                   8375: }
1.1162    raeburn  8376: }
                   8377: 
1.1282    raeburn  8378: # -------------------------------- Deversion and split uri into path an filename   
                   8379: 
1.1133    foxr     8380: #
1.1282    raeburn  8381: #   Removes the version from a URI and
1.1133    foxr     8382: #   splits it in to its filename and path to the filename.
                   8383: #   Seems like File::Basename could have done this more clearly.
                   8384: #   Parameters:
                   8385: #      $uri   - input URI
                   8386: #   Returns:
                   8387: #     Two element list consisting of 
                   8388: #     $pathname  - the URI up to and excluding the trailing /
                   8389: #     $filename  - The part of the URI following the last /
                   8390: #  NOTE:
                   8391: #    Another realization of this is simply:
                   8392: #    use File::Basename;
                   8393: #    ...
                   8394: #    $uri = shift;
                   8395: #    $filename = basename($uri);
                   8396: #    $path     = dirname($uri);
                   8397: #    return ($filename, $path);
                   8398: #
                   8399: #     The implementation below is probably faster however.
                   8400: #
1.710     albertel 8401: sub split_uri_for_cond {
                   8402:     my $uri=&deversion(&declutter(shift));
                   8403:     my @uriparts=split(/\//,$uri);
                   8404:     my $filename=pop(@uriparts);
                   8405:     my $pathname=join('/',@uriparts);
                   8406:     return ($pathname,$filename);
                   8407: }
1.232     www      8408: # --------------------------------------------------- Is a resource on the map?
                   8409: 
                   8410: sub is_on_map {
1.710     albertel 8411:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8412:     #Trying to find the conditional for the file
1.620     albertel 8413:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8414: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8415:     if ($match) {
1.289     bowersj2 8416: 	return (1,$1);
                   8417:     } else {
1.434     www      8418: 	return (0,0);
1.289     bowersj2 8419:     }
1.12      www      8420: }
                   8421: 
1.427     www      8422: # --------------------------------------------------------- Get symb from alias
                   8423: 
                   8424: sub get_symb_from_alias {
                   8425:     my $symb=shift;
                   8426:     my ($map,$resid,$url)=&decode_symb($symb);
                   8427: # Already is a symb
                   8428:     if ($url) { return $symb; }
                   8429: # Must be an alias
                   8430:     my $aliassymb='';
                   8431:     my %bighash;
1.620     albertel 8432:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8433:                             &GDBM_READER(),0640)) {
                   8434:         my $rid=$bighash{'mapalias_'.$symb};
                   8435: 	if ($rid) {
                   8436: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8437: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8438: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8439: 	}
                   8440:         untie %bighash;
                   8441:     }
                   8442:     return $aliassymb;
                   8443: }
                   8444: 
1.12      www      8445: # ----------------------------------------------------------------- Define Role
                   8446: 
                   8447: sub definerole {
                   8448:   if (allowed('mcr','/')) {
1.1326    raeburn  8449:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8450:     foreach my $role (split(':',$sysrole)) {
                   8451: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8452:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8453:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8454: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8455:                return "refused:s:$crole&$cqual"; 
                   8456:             }
                   8457:         }
1.191     harris41 8458:     }
1.800     albertel 8459:     foreach my $role (split(':',$domrole)) {
                   8460: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8461:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8462:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8463: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8464:                return "refused:d:$crole&$cqual"; 
                   8465:             }
                   8466:         }
1.191     harris41 8467:     }
1.800     albertel 8468:     foreach my $role (split(':',$courole)) {
                   8469: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8470:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8471:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8472: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8473:                return "refused:c:$crole&$cqual"; 
                   8474:             }
                   8475:         }
1.191     harris41 8476:     }
1.1326    raeburn  8477:     my $uhome;
                   8478:     if (($uname ne '') && ($udom ne '')) {
                   8479:         $uhome = &homeserver($uname,$udom);
                   8480:         return $uhome if ($uhome eq 'no_host');
                   8481:     } else {
                   8482:         $uname = $env{'user.name'};
                   8483:         $udom = $env{'user.domain'};
                   8484:         $uhome = $env{'user.home'};
                   8485:     }
1.620     albertel 8486:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8487:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8488:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8489:     return reply($command,$uhome);
1.12      www      8490:   } else {
                   8491:     return 'refused';
                   8492:   }
1.105     harris41 8493: }
                   8494: 
                   8495: # ---------------- Make a metadata query against the network of library servers
                   8496: 
                   8497: sub metadata_query {
1.1237    raeburn  8498:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8499:     my %rhash;
1.845     albertel 8500:     my %libserv = &all_library();
1.244     matthew  8501:     my @server_list = (defined($server_array) ? @$server_array
                   8502:                                               : keys(%libserv) );
                   8503:     for my $server (@server_list) {
1.1237    raeburn  8504:         my $domains = ''; 
                   8505:         if (ref($domains_hash) eq 'HASH') {
                   8506:             $domains = $domains_hash->{$server}; 
                   8507:         }
1.118     harris41 8508: 	unless ($custom or $customshow) {
1.1237    raeburn  8509: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8510: 	    $rhash{$server}=$reply;
                   8511: 	}
                   8512: 	else {
                   8513: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8514: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8515: 			     $server);
                   8516: 	    $rhash{$server}=$reply;
                   8517: 	}
1.112     harris41 8518:     }
1.118     harris41 8519:     return \%rhash;
1.240     www      8520: }
                   8521: 
                   8522: # ----------------------------------------- Send log queries and wait for reply
                   8523: 
                   8524: sub log_query {
                   8525:     my ($uname,$udom,$query,%filters)=@_;
                   8526:     my $uhome=&homeserver($uname,$udom);
                   8527:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8528:     my $uhost=&hostname($uhome);
1.800     albertel 8529:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8530:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8531:                        $uhome);
1.479     albertel 8532:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8533:     return get_query_reply($queryid);
                   8534: }
                   8535: 
1.818     raeburn  8536: # -------------------------- Update MySQL table for portfolio file
                   8537: 
                   8538: sub update_portfolio_table {
1.821     raeburn  8539:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8540:     if ($group ne '') {
                   8541:         $file_name =~s /^\Q$group\E//;
                   8542:     }
1.818     raeburn  8543:     my $homeserver = &homeserver($uname,$udom);
                   8544:     my $queryid=
1.821     raeburn  8545:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8546:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8547:     my $reply = &get_query_reply($queryid);
                   8548:     return $reply;
                   8549: }
                   8550: 
1.899     raeburn  8551: # -------------------------- Update MySQL allusers table
                   8552: 
                   8553: sub update_allusers_table {
                   8554:     my ($uname,$udom,$names) = @_;
                   8555:     my $homeserver = &homeserver($uname,$udom);
                   8556:     my $queryid=
                   8557:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8558:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8559:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8560:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8561:                'generation='.&escape($names->{'generation'}).'%%'.
                   8562:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8563:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8564:     return;
1.899     raeburn  8565: }
                   8566: 
1.508     raeburn  8567: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8568: 
                   8569: sub fetch_enrollment_query {
1.511     raeburn  8570:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8571:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8572:     my $maxtries = 1;
1.508     raeburn  8573:     if ($context eq 'automated') {
                   8574:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8575:         $sleep = 2;
                   8576:         $loopmax = 100;
1.547     raeburn  8577:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8578:     } else {
                   8579:         $homeserver = &homeserver($cnum,$dom);
                   8580:     }
1.838     albertel 8581:     my $host=&hostname($homeserver);
1.506     raeburn  8582:     my $cmd = '';
1.1000    raeburn  8583:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8584:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8585:     }
                   8586:     $cmd =~ s/%%$//;
                   8587:     $cmd = &escape($cmd);
                   8588:     my $query = 'fetchenrollment';
1.620     albertel 8589:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8590:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8591:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8592:         return 'error: '.$queryid;
                   8593:     }
1.1317    raeburn  8594:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8595:     my $tries = 1;
                   8596:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8597:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8598:         $tries ++;
                   8599:     }
1.526     raeburn  8600:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8601:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8602:     } else {
1.901     albertel 8603:         my @responses = split(/:/,$reply);
1.1322    raeburn  8604:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8605:             foreach my $line (@responses) {
                   8606:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8607:                 $$replyref{$key} = $value;
                   8608:             }
                   8609:         } else {
1.1117    foxr     8610:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8611:             foreach my $line (@responses) {
                   8612:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8613:                 $$replyref{$key} = $value;
                   8614:                 if ($value > 0) {
1.800     albertel 8615:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8616:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8617:                         my $destname = $pathname.'/'.$filename;
                   8618:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8619:                         if ($xml_classlist =~ /^error/) {
                   8620:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8621:                         } else {
1.1359    raeburn  8622:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8623:                                 print FILE &unescape($xml_classlist);
                   8624:                                 close(FILE);
1.526     raeburn  8625:                             } else {
                   8626:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8627:                             }
                   8628:                         }
                   8629:                     }
                   8630:                 }
                   8631:             }
                   8632:         }
                   8633:         return 'ok';
                   8634:     }
                   8635:     return 'error';
                   8636: }
                   8637: 
1.242     www      8638: sub get_query_reply {
1.1317    raeburn  8639:     my ($queryid,$sleep,$loopmax) = @_;;
                   8640:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8641:         $sleep = 0.2;
                   8642:     }
                   8643:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8644:         $loopmax = 100;
                   8645:     }
1.1117    foxr     8646:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8647:     my $reply='';
1.1317    raeburn  8648:     for (1..$loopmax) {
                   8649: 	sleep($sleep);
1.240     www      8650:         if (-e $replyfile.'.end') {
1.1359    raeburn  8651: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8652: 		$reply = join('',<$fh>);
                   8653: 		close($fh);
1.240     www      8654: 	   } else { return 'error: reply_file_error'; }
1.242     www      8655:            return &unescape($reply);
                   8656: 	}
1.240     www      8657:     }
1.242     www      8658:     return 'timeout:'.$queryid;
1.240     www      8659: }
                   8660: 
                   8661: sub courselog_query {
1.241     www      8662: #
                   8663: # possible filters:
                   8664: # url: url or symb
                   8665: # username
                   8666: # domain
                   8667: # action: view, submit, grade
                   8668: # start: timestamp
                   8669: # end: timestamp
                   8670: #
1.240     www      8671:     my (%filters)=@_;
1.620     albertel 8672:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8673:     if ($filters{'url'}) {
                   8674: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8675:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8676:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8677:     }
1.620     albertel 8678:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8679:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8680:     return &log_query($cname,$cdom,'courselog',%filters);
                   8681: }
                   8682: 
                   8683: sub userlog_query {
1.858     raeburn  8684: #
                   8685: # possible filters:
                   8686: # action: log check role
                   8687: # start: timestamp
                   8688: # end: timestamp
                   8689: #
1.240     www      8690:     my ($uname,$udom,%filters)=@_;
                   8691:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8692: }
                   8693: 
1.506     raeburn  8694: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8695: 
                   8696: sub auto_run {
1.508     raeburn  8697:     my ($cnum,$cdom) = @_;
1.876     raeburn  8698:     my $response = 0;
                   8699:     my $settings;
                   8700:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8701:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8702:         $settings = $domconfig{'autoenroll'};
                   8703:         if ($settings->{'run'} eq '1') {
                   8704:             $response = 1;
                   8705:         }
                   8706:     } else {
1.934     raeburn  8707:         my $homeserver;
                   8708:         if (&is_course($cdom,$cnum)) {
                   8709:             $homeserver = &homeserver($cnum,$cdom);
                   8710:         } else {
                   8711:             $homeserver = &domain($cdom,'primary');
                   8712:         }
                   8713:         if ($homeserver ne 'no_host') {
                   8714:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8715:         }
1.876     raeburn  8716:     }
1.506     raeburn  8717:     return $response;
                   8718: }
1.776     albertel 8719: 
1.506     raeburn  8720: sub auto_get_sections {
1.508     raeburn  8721:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8722:     my $homeserver;
                   8723:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8724:         $homeserver = &homeserver($cnum,$cdom);
                   8725:     }
                   8726:     if (!defined($homeserver)) { 
                   8727:         if ($cdom =~ /^$match_domain$/) {
                   8728:             $homeserver = &domain($cdom,'primary');
                   8729:         }
                   8730:     }
                   8731:     my @secs;
                   8732:     if (defined($homeserver)) {
                   8733:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8734:         unless ($response eq 'refused') {
                   8735:             @secs = split(/:/,$response);
                   8736:         }
1.506     raeburn  8737:     }
                   8738:     return @secs;
                   8739: }
1.776     albertel 8740: 
1.506     raeburn  8741: sub auto_new_course {
1.1099    raeburn  8742:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8743:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8744:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8745:     return $response;
                   8746: }
1.776     albertel 8747: 
1.506     raeburn  8748: sub auto_validate_courseID {
1.508     raeburn  8749:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8750:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8751:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8752:     return $response;
                   8753: }
1.776     albertel 8754: 
1.1007    raeburn  8755: sub auto_validate_instcode {
1.1020    raeburn  8756:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8757:     my ($homeserver,$response);
                   8758:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8759:         $homeserver = &homeserver($cnum,$cdom);
                   8760:     }
                   8761:     if (!defined($homeserver)) {
                   8762:         if ($cdom =~ /^$match_domain$/) {
                   8763:             $homeserver = &domain($cdom,'primary');
                   8764:         }
                   8765:     }
1.1065    raeburn  8766:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8767:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8768:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8769:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8770: }
                   8771: 
1.506     raeburn  8772: sub auto_create_password {
1.873     raeburn  8773:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8774:     my ($homeserver,$response);
1.506     raeburn  8775:     my $create_passwd = 0;
                   8776:     my $authchk = '';
1.873     raeburn  8777:     if ($udom =~ /^$match_domain$/) {
                   8778:         $homeserver = &domain($udom,'primary');
                   8779:     }
                   8780:     if ($homeserver eq '') {
                   8781:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8782:             $homeserver = &homeserver($cnum,$cdom);
                   8783:         }
                   8784:     }
                   8785:     if ($homeserver eq '') {
                   8786:         $authchk = 'nodomain';
1.506     raeburn  8787:     } else {
1.873     raeburn  8788:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8789:         if ($response eq 'refused') {
                   8790:             $authchk = 'refused';
                   8791:         } else {
1.901     albertel 8792:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8793:         }
1.506     raeburn  8794:     }
                   8795:     return ($authparam,$create_passwd,$authchk);
                   8796: }
                   8797: 
1.706     raeburn  8798: sub auto_photo_permission {
                   8799:     my ($cnum,$cdom,$students) = @_;
                   8800:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8801:     my ($outcome,$perm_reqd,$conditions) = 
                   8802: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8803:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8804: 	return (undef,undef);
                   8805:     }
1.706     raeburn  8806:     return ($outcome,$perm_reqd,$conditions);
                   8807: }
                   8808: 
                   8809: sub auto_checkphotos {
                   8810:     my ($uname,$udom,$pid) = @_;
                   8811:     my $homeserver = &homeserver($uname,$udom);
                   8812:     my ($result,$resulttype);
                   8813:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8814: 				   &escape($uname).':'.&escape($pid),
                   8815: 				   $homeserver));
1.709     albertel 8816:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8817: 	return (undef,undef);
                   8818:     }
1.706     raeburn  8819:     if ($outcome) {
                   8820:         ($result,$resulttype) = split(/:/,$outcome);
                   8821:     } 
                   8822:     return ($result,$resulttype);
                   8823: }
                   8824: 
                   8825: sub auto_photochoice {
                   8826:     my ($cnum,$cdom) = @_;
                   8827:     my $homeserver = &homeserver($cnum,$cdom);
                   8828:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8829: 						       &escape($cdom),
                   8830: 						       $homeserver)));
1.709     albertel 8831:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8832: 	return (undef,undef);
                   8833:     }
1.706     raeburn  8834:     return ($update,$comment);
                   8835: }
                   8836: 
                   8837: sub auto_photoupdate {
                   8838:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8839:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8840:     my $host=&hostname($homeserver);
1.706     raeburn  8841:     my $cmd = '';
                   8842:     my $maxtries = 1;
1.800     albertel 8843:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8844:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8845:     }
                   8846:     $cmd =~ s/%%$//;
                   8847:     $cmd = &escape($cmd);
                   8848:     my $query = 'institutionalphotos';
                   8849:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8850:     unless ($queryid=~/^\Q$host\E\_/) {
                   8851:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8852:         return 'error: '.$queryid;
                   8853:     }
                   8854:     my $reply = &get_query_reply($queryid);
                   8855:     my $tries = 1;
                   8856:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8857:         $reply = &get_query_reply($queryid);
                   8858:         $tries ++;
                   8859:     }
                   8860:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8861:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8862:     } else {
                   8863:         my @responses = split(/:/,$reply);
                   8864:         my $outcome = shift(@responses); 
                   8865:         foreach my $item (@responses) {
                   8866:             my ($key,$value) = split(/=/,$item);
                   8867:             $$photo{$key} = $value;
                   8868:         }
                   8869:         return $outcome;
                   8870:     }
                   8871:     return 'error';
                   8872: }
                   8873: 
1.521     raeburn  8874: sub auto_instcode_format {
1.793     albertel 8875:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8876: 	$cat_order) = @_;
1.521     raeburn  8877:     my $courses = '';
1.772     raeburn  8878:     my @homeservers;
1.521     raeburn  8879:     if ($caller eq 'global') {
1.841     albertel 8880: 	my %servers = &get_servers($codedom,'library');
                   8881: 	foreach my $tryserver (keys(%servers)) {
                   8882: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8883: 		push(@homeservers,$tryserver);
                   8884: 	    }
1.584     raeburn  8885:         }
1.1022    raeburn  8886:     } elsif ($caller eq 'requests') {
                   8887:         if ($codedom =~ /^$match_domain$/) {
                   8888:             my $chome = &domain($codedom,'primary');
                   8889:             unless ($chome eq 'no_host') {
                   8890:                 push(@homeservers,$chome);
                   8891:             }
                   8892:         }
1.521     raeburn  8893:     } else {
1.772     raeburn  8894:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8895:     }
1.793     albertel 8896:     foreach my $code (keys(%{$instcodes})) {
                   8897:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8898:     }
                   8899:     chop($courses);
1.772     raeburn  8900:     my $ok_response = 0;
                   8901:     my $response;
                   8902:     while (@homeservers > 0 && $ok_response == 0) {
                   8903:         my $server = shift(@homeservers); 
                   8904:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8905:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8906:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8907: 		split(/:/,$response);
1.772     raeburn  8908:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8909:             push(@{$codetitles},&str2array($codetitles_str));
                   8910:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8911:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8912:             $ok_response = 1;
                   8913:         }
                   8914:     }
                   8915:     if ($ok_response) {
1.521     raeburn  8916:         return 'ok';
1.772     raeburn  8917:     } else {
                   8918:         return $response;
1.521     raeburn  8919:     }
                   8920: }
                   8921: 
1.792     raeburn  8922: sub auto_instcode_defaults {
                   8923:     my ($domain,$returnhash,$code_order) = @_;
                   8924:     my @homeservers;
1.841     albertel 8925: 
                   8926:     my %servers = &get_servers($domain,'library');
                   8927:     foreach my $tryserver (keys(%servers)) {
                   8928: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8929: 	    push(@homeservers,$tryserver);
                   8930: 	}
1.792     raeburn  8931:     }
1.841     albertel 8932: 
1.792     raeburn  8933:     my $response;
1.841     albertel 8934:     foreach my $server (@homeservers) {
1.792     raeburn  8935:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8936:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8937: 	
                   8938: 	foreach my $pair (split(/\&/,$response)) {
                   8939: 	    my ($name,$value)=split(/\=/,$pair);
                   8940: 	    if ($name eq 'code_order') {
                   8941: 		@{$code_order} = split(/\&/,&unescape($value));
                   8942: 	    } else {
                   8943: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8944: 	    }
                   8945: 	}
                   8946: 	return 'ok';
1.792     raeburn  8947:     }
1.841     albertel 8948: 
                   8949:     return $response;
1.1003    raeburn  8950: }
                   8951: 
                   8952: sub auto_possible_instcodes {
1.1007    raeburn  8953:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8954:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8955:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8956:         return;
                   8957:     }
1.1003    raeburn  8958:     my (@homeservers,$uhome);
                   8959:     if (defined(&domain($domain,'primary'))) {
                   8960:         $uhome=&domain($domain,'primary');
                   8961:         push(@homeservers,&domain($domain,'primary'));
                   8962:     } else {
                   8963:         my %servers = &get_servers($domain,'library');
                   8964:         foreach my $tryserver (keys(%servers)) {
                   8965:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8966:                 push(@homeservers,$tryserver);
                   8967:             }
                   8968:         }
                   8969:     }
                   8970:     my $response;
                   8971:     foreach my $server (@homeservers) {
                   8972:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8973:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8974:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8975:             split(':',$response);
                   8976:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8977:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8978:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8979:             my ($name,$value)=split('=',$item);
                   8980:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8981:         }
                   8982:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8983:             my ($name,$value)=split('=',$item);
                   8984:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8985:         }
                   8986:         return 'ok';
                   8987:     }
                   8988:     return $response;
                   8989: }
1.792     raeburn  8990: 
1.1010    raeburn  8991: sub auto_courserequest_checks {
                   8992:     my ($dom) = @_;
1.1020    raeburn  8993:     my ($homeserver,%validations);
                   8994:     if ($dom =~ /^$match_domain$/) {
                   8995:         $homeserver = &domain($dom,'primary');
                   8996:     }
                   8997:     unless ($homeserver eq 'no_host') {
                   8998:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8999:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9000:             my @items = split(/&/,$response);
                   9001:             foreach my $item (@items) {
                   9002:                 my ($key,$value) = split('=',$item);
                   9003:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9004:             }
                   9005:         }
                   9006:     }
1.1010    raeburn  9007:     return %validations; 
                   9008: }
                   9009: 
1.1020    raeburn  9010: sub auto_courserequest_validation {
1.1255    raeburn  9011:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9012:     my ($homeserver,$response);
                   9013:     if ($dom =~ /^$match_domain$/) {
                   9014:         $homeserver = &domain($dom,'primary');
                   9015:     }
1.1255    raeburn  9016:     unless ($homeserver eq 'no_host') {
                   9017:         my $customdata;
                   9018:         if (ref($custominfo) eq 'HASH') {
                   9019:             $customdata = &freeze_escape($custominfo);
                   9020:         }
1.1020    raeburn  9021:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9022:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9023:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9024:                                     $customdata,$homeserver));
1.1020    raeburn  9025:     }
                   9026:     return $response;
                   9027: }
                   9028: 
1.777     albertel 9029: sub auto_validate_class_sec {
1.918     raeburn  9030:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9031:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9032:     my $ownerlist;
                   9033:     if (ref($owners) eq 'ARRAY') {
                   9034:         $ownerlist = join(',',@{$owners});
                   9035:     } else {
                   9036:         $ownerlist = $owners;
                   9037:     }
1.773     raeburn  9038:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9039:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9040:     return $response;
                   9041: }
                   9042: 
1.1367    raeburn  9043: sub auto_validate_instclasses {
                   9044:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9045:     my ($homeserver,%validations);
                   9046:     $homeserver = &homeserver($cnum,$cdom);
                   9047:     unless ($homeserver eq 'no_host') {
                   9048:         my $ownerlist;
                   9049:         if (ref($owners) eq 'ARRAY') {
                   9050:             $ownerlist = join(',',@{$owners});
                   9051:         } else {
                   9052:             $ownerlist = $owners;
                   9053:         }
                   9054:         if (ref($classesref) eq 'HASH') {
                   9055:             my $classes = &freeze_escape($classesref);
                   9056:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9057:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9058:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9059:                 my @items = split(/&/,$response);
                   9060:                 foreach my $item (@items) {
                   9061:                     my ($key,$value) = split('=',$item);
                   9062:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9063:                 }
                   9064:             }
                   9065:         }
                   9066:     }
                   9067:     return %validations;
                   9068: }
                   9069: 
1.1248    raeburn  9070: sub auto_crsreq_update {
                   9071:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9072:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9073:     my ($homeserver,%crsreqresponse);
                   9074:     if ($cdom =~ /^$match_domain$/) {
                   9075:         $homeserver = &domain($cdom,'primary');
                   9076:     }
                   9077:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9078:         my $info;
                   9079:         if (ref($inbound) eq 'HASH') {
                   9080:             $info = &freeze_escape($inbound);
                   9081:         }
                   9082:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9083:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9084:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9085:                             &escape($title).':'.&escape($code).':'.
                   9086:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9087:                             $homeserver);
1.1248    raeburn  9088:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9089:             my @items = split(/&/,$response);
                   9090:             foreach my $item (@items) {
                   9091:                 my ($key,$value) = split('=',$item);
                   9092:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9093:             }
                   9094:         }
                   9095:     }
                   9096:     return \%crsreqresponse;
                   9097: }
                   9098: 
1.1305    raeburn  9099: sub auto_export_grades {
1.1309    raeburn  9100:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9101:     my ($homeserver,%exportresponse);
                   9102:     if ($cdom =~ /^$match_domain$/) {
                   9103:         $homeserver = &domain($cdom,'primary');
                   9104:     }
                   9105:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9106:         my $info;
                   9107:         if (ref($inforef) eq 'HASH') {
                   9108:             $info = &freeze_escape($inforef);
                   9109:         }
                   9110:         if (ref($gradesref) eq 'HASH') {
                   9111:             my $grades = &freeze_escape($gradesref);
                   9112:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9113:                                 $info.':'.$grades,$homeserver);
                   9114:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9115:                 my @items = split(/&/,$response);
                   9116:                 foreach my $item (@items) {
                   9117:                     my ($key,$value) = split('=',$item);
                   9118:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9119:                 }
                   9120:             }
                   9121:         }
                   9122:     }
                   9123:     return \%exportresponse;
1.1305    raeburn  9124: }
                   9125: 
1.1287    raeburn  9126: sub check_instcode_cloning {
                   9127:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9128:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9129:         return;
                   9130:     }
                   9131:     my $canclone;
                   9132:     if (@{$code_order} > 0) {
                   9133:         my $instcoderegexp ='^';
                   9134:         my @clonecodes = split(/\&/,$cloner);
                   9135:         foreach my $item (@{$code_order}) {
                   9136:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9137:                 foreach my $pair (@clonecodes) {
                   9138:                     my ($key,$val) = split(/\=/,$pair,2);
                   9139:                     $val = &unescape($val);
                   9140:                     if ($key eq $item) {
                   9141:                         $instcoderegexp .= '('.$val.')';
                   9142:                         last;
                   9143:                     }
                   9144:                 }
                   9145:             } else {
                   9146:                 $instcoderegexp .= $codedefaults->{$item};
                   9147:             }
                   9148:         }
                   9149:         $instcoderegexp .= '$';
                   9150:         my (@from,@to);
                   9151:         eval {
                   9152:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9153:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9154:         };
                   9155:         if ((@from > 0) && (@to > 0)) {
                   9156:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9157:             if (!@diffs) {
                   9158:                 $canclone = 1;
                   9159:             }
                   9160:         }
                   9161:     }
                   9162:     return $canclone;
                   9163: }
                   9164: 
                   9165: sub default_instcode_cloning {
                   9166:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9167:     my (%codedefaults,@code_order,$canclone);
                   9168:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9169:         %codedefaults = %{$codedefaultsref};
                   9170:         @code_order = @{$codeorderref};
                   9171:     } elsif ($clonedom) {
                   9172:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9173:     }
                   9174:     if (($domdefclone) && (@code_order)) {
                   9175:         my @clonecodes = split(/\+/,$domdefclone);
                   9176:         my $instcoderegexp ='^';
                   9177:         foreach my $item (@code_order) {
                   9178:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9179:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9180:             } else {
                   9181:                 $instcoderegexp .= $codedefaults{$item};
                   9182:             }
                   9183:         }
                   9184:         $instcoderegexp .= '$';
                   9185:         my (@from,@to);
                   9186:         eval {
                   9187:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9188:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9189:         };
                   9190:         if ((@from > 0) && (@to > 0)) {
                   9191:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9192:             if (!@diffs) {
                   9193:                 $canclone = 1;
                   9194:             }
                   9195:         }
                   9196:     }
                   9197:     return $canclone;
                   9198: }
                   9199: 
1.679     raeburn  9200: # ------------------------------------------------------- Course Group routines
                   9201: 
                   9202: sub get_coursegroups {
1.809     raeburn  9203:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9204:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9205: }
                   9206: 
1.679     raeburn  9207: sub modify_coursegroup {
                   9208:     my ($cdom,$cnum,$groupsettings) = @_;
                   9209:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9210: }
                   9211: 
1.809     raeburn  9212: sub toggle_coursegroup_status {
                   9213:     my ($cdom,$cnum,$group,$action) = @_;
                   9214:     my ($from_namespace,$to_namespace);
                   9215:     if ($action eq 'delete') {
                   9216:         $from_namespace = 'coursegroups';
                   9217:         $to_namespace = 'deleted_groups';
                   9218:     } else {
                   9219:         $from_namespace = 'deleted_groups';
                   9220:         $to_namespace = 'coursegroups';
                   9221:     }
                   9222:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9223:     if (my $tmp = &error(%curr_group)) {
                   9224:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9225:         return ('read error',$tmp);
                   9226:     } else {
                   9227:         my %savedsettings = %curr_group; 
1.809     raeburn  9228:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9229:         my $deloutcome;
                   9230:         if ($result eq 'ok') {
1.809     raeburn  9231:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9232:         } else {
                   9233:             return ('write error',$result);
                   9234:         }
                   9235:         if ($deloutcome eq 'ok') {
                   9236:             return 'ok';
                   9237:         } else {
                   9238:             return ('delete error',$deloutcome);
                   9239:         }
                   9240:     }
                   9241: }
                   9242: 
1.679     raeburn  9243: sub modify_group_roles {
1.957     raeburn  9244:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9245:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9246:     my $role = 'gr/'.&escape($userprivs);
                   9247:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9248:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9249:     if ($result eq 'ok') {
                   9250:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9251:     }
1.679     raeburn  9252:     return $result;
                   9253: }
                   9254: 
                   9255: sub modify_coursegroup_membership {
                   9256:     my ($cdom,$cnum,$membership) = @_;
                   9257:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9258:     return $result;
                   9259: }
                   9260: 
1.682     raeburn  9261: sub get_active_groups {
                   9262:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9263:     my $now = time;
                   9264:     my %groups = ();
                   9265:     foreach my $key (keys(%env)) {
1.811     albertel 9266:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9267:             my ($start,$end) = split(/\./,$env{$key});
                   9268:             if (($end!=0) && ($end<$now)) { next; }
                   9269:             if (($start!=0) && ($start>$now)) { next; }
                   9270:             if ($1 eq $cdom && $2 eq $cnum) {
                   9271:                 $groups{$3} = $env{$key} ;
                   9272:             }
                   9273:         }
                   9274:     }
                   9275:     return %groups;
                   9276: }
                   9277: 
1.683     raeburn  9278: sub get_group_membership {
                   9279:     my ($cdom,$cnum,$group) = @_;
                   9280:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9281: }
                   9282: 
                   9283: sub get_users_groups {
                   9284:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9285:     my @usersgroups;
1.683     raeburn  9286:     my $cachetime=1800;
                   9287: 
                   9288:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9289:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9290:     if (defined($cached)) {
1.734     albertel 9291:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9292:     } else {  
                   9293:         $grouplist = '';
1.816     raeburn  9294:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9295:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9296:         my $access_end = $env{'course.'.$courseid.
                   9297:                               '.default_enrollment_end_date'};
                   9298:         my $now = time;
                   9299:         foreach my $key (keys(%roleshash)) {
                   9300:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9301:                 my $group = $1;
                   9302:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9303:                     my $start = $2;
                   9304:                     my $end = $1;
                   9305:                     if ($start == -1) { next; } # deleted from group
                   9306:                     if (($start!=0) && ($start>$now)) { next; }
                   9307:                     if (($end!=0) && ($end<$now)) {
                   9308:                         if ($access_end && $access_end < $now) {
                   9309:                             if ($access_end - $end < 86400) {
                   9310:                                 push(@usersgroups,$group);
1.733     raeburn  9311:                             }
                   9312:                         }
1.817     raeburn  9313:                         next;
1.733     raeburn  9314:                     }
1.817     raeburn  9315:                     push(@usersgroups,$group);
1.683     raeburn  9316:                 }
                   9317:             }
                   9318:         }
1.817     raeburn  9319:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9320:         $grouplist = join(':',@usersgroups);
                   9321:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9322:     }
1.733     raeburn  9323:     return @usersgroups;
1.683     raeburn  9324: }
                   9325: 
                   9326: sub devalidate_getgroups_cache {
                   9327:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9328:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9329: 
1.683     raeburn  9330:     my $hashid="$udom:$uname:$courseid";
                   9331:     &devalidate_cache_new('getgroups',$hashid);
                   9332: }
                   9333: 
1.12      www      9334: # ------------------------------------------------------------------ Plain Text
                   9335: 
                   9336: sub plaintext {
1.988     raeburn  9337:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9338:     if ($short =~ m{^cr/}) {
1.758     albertel 9339: 	return (split('/',$short))[-1];
                   9340:     }
1.742     raeburn  9341:     if (!defined($cid)) {
                   9342:         $cid = $env{'request.course.id'};
                   9343:     }
                   9344:     my %rolenames = (
1.1008    raeburn  9345:                       Course    => 'std',
                   9346:                       Community => 'alt1',
1.1305    raeburn  9347:                       Placement => 'std',
1.742     raeburn  9348:                     );
1.1037    raeburn  9349:     if ($cid ne '') {
                   9350:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9351:             unless ($forcedefault) {
                   9352:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9353:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9354:                 return &Apache::lonlocal::mt($roletext);
                   9355:             }
                   9356:         }
                   9357:     }
                   9358:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9359:         (defined($rolenames{$type})) && 
                   9360:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9361:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9362:     } elsif ($cid ne '') {
                   9363:         my $crstype = $env{'course.'.$cid.'.type'};
                   9364:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9365:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9366:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9367:         }
1.742     raeburn  9368:     }
1.1037    raeburn  9369:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9370: }
                   9371: 
                   9372: # ----------------------------------------------------------------- Assign Role
                   9373: 
                   9374: sub assignrole {
1.957     raeburn  9375:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9376:         $context)=@_;
1.21      www      9377:     my $mrole;
                   9378:     if ($role =~ /^cr\//) {
1.393     www      9379:         my $cwosec=$url;
1.811     albertel 9380:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9381: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9382:            my $refused = 1;
                   9383:            if ($context eq 'requestcourses') {
                   9384:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9385:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9386:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9387:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9388:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9389:                            if ($crsenv{'internal.courseowner'} eq
                   9390:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9391:                                $refused = '';
                   9392:                            }
                   9393:                        }
                   9394:                    }
                   9395:                }
                   9396:            }
                   9397:            if ($refused) {
                   9398:                &logthis('Refused custom assignrole: '.
                   9399:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9400:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9401:                return 'refused';
                   9402:            }
1.104     www      9403:         }
1.21      www      9404:         $mrole='cr';
1.678     raeburn  9405:     } elsif ($role =~ /^gr\//) {
                   9406:         my $cwogrp=$url;
1.811     albertel 9407:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9408:         unless (&allowed('mdg',$cwogrp)) {
                   9409:             &logthis('Refused group assignrole: '.
                   9410:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9411:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9412:             return 'refused';
                   9413:         }
                   9414:         $mrole='gr';
1.21      www      9415:     } else {
1.82      www      9416:         my $cwosec=$url;
1.811     albertel 9417:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9418:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9419:             my $refused;
                   9420:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9421:                 if (!(&allowed('c'.$role,$url))) {
                   9422:                     $refused = 1;
                   9423:                 }
                   9424:             } else {
                   9425:                 $refused = 1;
                   9426:             }
1.947     raeburn  9427:             if ($refused) {
1.1045    raeburn  9428:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9429:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9430:                     my %crsenv;
                   9431:                     if ($role eq 'cc' || $role eq 'co') {
                   9432:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9433:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9434:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9435:                                 if ($crsenv{'internal.courseowner'} eq 
                   9436:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9437:                                     $refused = '';
                   9438:                                 }
                   9439:                             }
                   9440:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9441:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9442:                                 if ($crsenv{'internal.courseowner'} eq 
                   9443:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9444:                                     $refused = '';
                   9445:                                 }
                   9446:                             }
                   9447:                         }
                   9448:                     }
1.1368    raeburn  9449:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9450:                     if ($role eq 'st') {
                   9451:                         $refused = '';
1.1377    raeburn  9452:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9453:                         $refused = '';
                   9454:                     }
1.1017    raeburn  9455:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9456:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9457:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9458:                         my $wrongcc;
                   9459:                         if ($cnum =~ /^$match_community$/) {
                   9460:                             $wrongcc = 1 if ($role eq 'cc');
                   9461:                         } else {
                   9462:                             $wrongcc = 1 if ($role eq 'co');
                   9463:                         }
                   9464:                         unless ($wrongcc) {
                   9465:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9466:                             if ($crsenv{'internal.courseowner'} eq 
                   9467:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9468:                                 $refused = '';
                   9469:                             }
1.1017    raeburn  9470:                         }
                   9471:                     }
1.1183    raeburn  9472:                 } elsif ($context eq 'requestauthor') {
                   9473:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9474:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9475:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9476:                             $refused = '';
                   9477:                         } else {
                   9478:                             my %domdefaults = &get_domain_defaults($udom);
                   9479:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9480:                                 my $checkbystatus;
                   9481:                                 if ($env{'user.adv'}) { 
                   9482:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9483:                                     if ($disposition eq 'automatic') {
                   9484:                                         $refused = '';
                   9485:                                     } elsif ($disposition eq '') {
                   9486:                                         $checkbystatus = 1;
                   9487:                                     } 
                   9488:                                 } else {
                   9489:                                     $checkbystatus = 1;
                   9490:                                 }
                   9491:                                 if ($checkbystatus) {
                   9492:                                     if ($env{'environment.inststatus'}) {
                   9493:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9494:                                         foreach my $type (@inststatuses) {
                   9495:                                             if (($type ne '') &&
                   9496:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9497:                                                 $refused = '';
                   9498:                                             }
                   9499:                                         }
                   9500:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9501:                                         $refused = '';
                   9502:                                     }
                   9503:                                 }
                   9504:                             }
                   9505:                         }
                   9506:                     }
1.1017    raeburn  9507:                 }
                   9508:                 if ($refused) {
1.947     raeburn  9509:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9510:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9511: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9512:                     return 'refused';
                   9513:                 }
1.932     raeburn  9514:             }
1.1131    raeburn  9515:         } elsif ($role eq 'au') {
                   9516:             if ($url ne '/'.$udom.'/') {
                   9517:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9518:                          ' to assign author role for '.$uname.':'.$udom.
                   9519:                          ' in domain: '.$url.' refused (wrong domain).');
                   9520:                 return 'refused';
                   9521:             }
1.104     www      9522:         }
1.21      www      9523:         $mrole=$role;
                   9524:     }
1.620     albertel 9525:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9526:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9527:     if ($end) { $command.='_'.$end; }
1.21      www      9528:     if ($start) {
                   9529: 	if ($end) { 
1.81      www      9530:            $command.='_'.$start; 
1.21      www      9531:         } else {
1.81      www      9532:            $command.='_0_'.$start;
1.21      www      9533:         }
                   9534:     }
1.739     raeburn  9535:     my $origstart = $start;
                   9536:     my $origend = $end;
1.957     raeburn  9537:     my $delflag;
1.357     www      9538: # actually delete
                   9539:     if ($deleteflag) {
1.373     www      9540: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9541: # modify command to delete the role
1.620     albertel 9542:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9543:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9544: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9545: # set start and finish to negative values for userrolelog
                   9546:            $start=-1;
                   9547:            $end=-1;
1.957     raeburn  9548:            $delflag = 1;
1.357     www      9549:         }
                   9550:     }
                   9551: # send command
1.349     www      9552:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9553: # log new user role if status is ok
1.349     www      9554:     if ($answer eq 'ok') {
1.663     raeburn  9555: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9556:         if (($role eq 'cc') || ($role eq 'in') ||
                   9557:             ($role eq 'ep') || ($role eq 'ad') ||
                   9558:             ($role eq 'ta') || ($role eq 'st') ||
                   9559:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9560:             ($role eq 'co')) {
1.1200    raeburn  9561: # for course roles, perform group memberships changes triggered by role change.
                   9562:             unless ($role =~ /^gr/) {
                   9563:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9564:                                                  $origstart,$selfenroll,$context);
                   9565:             }
1.1184    raeburn  9566:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9567:                            $selfenroll,$context);
                   9568:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9569:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9570:                  ($role eq 'da')) {
1.1184    raeburn  9571:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9572:                            $context);
                   9573:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9574:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9575:                              $context); 
                   9576:         }
1.1053    raeburn  9577:         if ($role eq 'cc') {
                   9578:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9579:         }
1.349     www      9580:     }
                   9581:     return $answer;
1.169     harris41 9582: }
                   9583: 
1.1053    raeburn  9584: sub autoupdate_coowners {
                   9585:     my ($url,$end,$start,$uname,$udom) = @_;
                   9586:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9587:     if (($cdom ne '') && ($cnum ne '')) {
                   9588:         my $now = time;
                   9589:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9590:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9591:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9592:             my $instcode = $coursehash{'internal.coursecode'};
                   9593:             if ($instcode ne '') {
1.1056    raeburn  9594:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9595:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9596:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9597:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9598:                         if ($result eq 'valid') {
                   9599:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9600:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9601:                                     push(@newcoowners,$coowner);
                   9602:                                 }
                   9603:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9604:                                     push(@newcoowners,$uname.':'.$udom);
                   9605:                                 }
                   9606:                                 @newcoowners = sort(@newcoowners);
                   9607:                             } else {
                   9608:                                 push(@newcoowners,$uname.':'.$udom);
                   9609:                             }
                   9610:                         } else {
                   9611:                             if ($coursehash{'internal.co-owners'}) {
                   9612:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9613:                                     unless ($coowner eq $uname.':'.$udom) {
                   9614:                                         push(@newcoowners,$coowner);
                   9615:                                     }
                   9616:                                 }
                   9617:                                 unless (@newcoowners > 0) {
                   9618:                                     $delcoowners = 1;
                   9619:                                     $coowners = '';
                   9620:                                 }
                   9621:                             }
                   9622:                         }
                   9623:                         if (@newcoowners || $delcoowners) {
                   9624:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9625:                                             $delcoowners,@newcoowners);
                   9626:                         }
                   9627:                     }
                   9628:                 }
                   9629:             }
                   9630:         }
                   9631:     }
                   9632: }
                   9633: 
                   9634: sub store_coowners {
                   9635:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9636:     my $cid = $cdom.'_'.$cnum;
                   9637:     my ($coowners,$delresult,$putresult);
                   9638:     if (@newcoowners) {
                   9639:         $coowners = join(',',@newcoowners);
                   9640:         my %coownershash = (
                   9641:                             'internal.co-owners' => $coowners,
                   9642:                            );
                   9643:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9644:         if ($putresult eq 'ok') {
                   9645:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9646:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9647:             }
                   9648:         }
                   9649:     }
                   9650:     if ($delcoowners) {
                   9651:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9652:         if ($delresult eq 'ok') {
                   9653:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9654:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9655:             }
                   9656:         }
                   9657:     }
                   9658:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9659:         my %crsinfo =
                   9660:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9661:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9662:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9663:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9664:         }
                   9665:     }
                   9666: }
                   9667: 
1.169     harris41 9668: # -------------------------------------------------- Modify user authentication
1.197     www      9669: # Overrides without validation
                   9670: 
1.169     harris41 9671: sub modifyuserauth {
                   9672:     my ($udom,$uname,$umode,$upass)=@_;
                   9673:     my $uhome=&homeserver($uname,$udom);
1.197     www      9674:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9675:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9676:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9677:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9678:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9679: 		     &escape($upass),$uhome);
1.620     albertel 9680:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9681:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9682:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9683:     &log($udom,,$uname,$uhome,
1.620     albertel 9684:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9685:                                      $env{'user.name'}.', '.$umode.
1.197     www      9686:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9687:     unless ($reply eq 'ok') {
1.197     www      9688:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9689: 	return 'error: '.$reply;
                   9690:     }   
1.170     harris41 9691:     return 'ok';
1.80      www      9692: }
                   9693: 
1.81      www      9694: # --------------------------------------------------------------- Modify a user
1.80      www      9695: 
1.81      www      9696: sub modifyuser {
1.206     matthew  9697:     my ($udom,    $uname, $uid,
                   9698:         $umode,   $upass, $first,
                   9699:         $middle,  $last,  $gene,
1.1058    raeburn  9700:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9701:     $udom= &LONCAPA::clean_domain($udom);
                   9702:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9703:     my $showcandelete = 'none';
                   9704:     if (ref($candelete) eq 'ARRAY') {
                   9705:         if (@{$candelete} > 0) {
                   9706:             $showcandelete = join(', ',@{$candelete});
                   9707:         }
                   9708:     }
1.81      www      9709:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9710:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9711: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9712:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9713:                                      ' desiredhome not specified'). 
1.620     albertel 9714:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9715:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9716:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9717:     my $newuser;
                   9718:     if ($uhome eq 'no_host') {
                   9719:         $newuser = 1;
1.1368    raeburn  9720:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9721:                 ($umode eq 'lti')) {
                   9722:             return 'error: more information needed to create new user';
                   9723:         }
1.1075    raeburn  9724:     }
1.80      www      9725: # ----------------------------------------------------------------- Create User
1.406     albertel 9726:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9727: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9728:         my $unhome='';
1.844     albertel 9729:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9730:             $unhome = $desiredhome;
1.620     albertel 9731: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9732: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9733:         } else { # load balancing routine for determining $unhome
1.81      www      9734:             my $loadm=10000000;
1.841     albertel 9735: 	    my %servers = &get_servers($udom,'library');
                   9736: 	    foreach my $tryserver (keys(%servers)) {
                   9737: 		my $answer=reply('load',$tryserver);
                   9738: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9739: 		    $loadm=$answer;
                   9740: 		    $unhome=$tryserver;
                   9741: 		}
1.80      www      9742: 	    }
                   9743:         }
                   9744:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9745: 	    return 'error: unable to find a home server for '.$uname.
                   9746:                    ' in domain '.$udom;
1.80      www      9747:         }
                   9748:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9749:                          &escape($upass),$unhome);
                   9750: 	unless ($reply eq 'ok') {
                   9751:             return 'error: '.$reply;
                   9752:         }   
1.230     stredwic 9753:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9754:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9755: 	    return 'error: unable verify users home machine.';
1.80      www      9756:         }
1.209     matthew  9757:     }   # End of creation of new user
1.80      www      9758: # ---------------------------------------------------------------------- Add ID
                   9759:     if ($uid) {
                   9760:        $uid=~tr/A-Z/a-z/;
                   9761:        my %uidhash=&idrget($udom,$uname);
1.196     www      9762:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9763:          && (!$forceid)) {
1.80      www      9764: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9765: 	      return 'error: user id "'.$uid.'" does not match '.
                   9766:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9767:           }
                   9768:        } else {
1.1300    raeburn  9769: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9770:        }
                   9771:     }
                   9772: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9773:     my @tmp=&get('environment',
1.899     raeburn  9774: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9775:                     'permanentemail','inststatus'],
1.134     albertel 9776: 		   $udom,$uname);
1.1075    raeburn  9777:     my (%names,%oldnames);
1.313     matthew  9778:     if ($tmp[0] =~ m/^error:.*/) { 
                   9779:         %names=(); 
                   9780:     } else {
                   9781:         %names = @tmp;
1.1075    raeburn  9782:         %oldnames = %names;
1.313     matthew  9783:     }
1.388     www      9784: #
1.1058    raeburn  9785: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9786: # of users did not contain them), do not overwrite existing values
                   9787: # unless field is in $candelete array ref.  
                   9788: #
                   9789: 
                   9790:     my @fields = ('firstname','middlename','lastname','generation',
                   9791:                   'permanentemail','id');
                   9792:     my %newvalues;
                   9793:     if (ref($candelete) eq 'ARRAY') {
                   9794:         foreach my $field (@fields) {
                   9795:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9796:                 if ($field eq 'firstname') {
                   9797:                     $names{$field} = $first;
                   9798:                 } elsif ($field eq 'middlename') {
                   9799:                     $names{$field} = $middle;
                   9800:                 } elsif ($field eq 'lastname') {
                   9801:                     $names{$field} = $last;
                   9802:                 } elsif ($field eq 'generation') { 
                   9803:                     $names{$field} = $gene;
                   9804:                 } elsif ($field eq 'permanentemail') {
                   9805:                     $names{$field} = $email;
                   9806:                 } elsif ($field eq 'id') {
                   9807:                     $names{$field}  = $uid;
                   9808:                 }
                   9809:             }
                   9810:         }
                   9811:     }
1.388     www      9812:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9813:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9814:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9815:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9816:     if ($email) {
                   9817:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9818:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9819:     }
1.899     raeburn  9820:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9821:     if (defined($inststatus)) {
                   9822:         $names{'inststatus'} = '';
                   9823:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9824:         if (ref($usertypes) eq 'HASH') {
                   9825:             my @okstatuses; 
                   9826:             foreach my $item (split(/:/,$inststatus)) {
                   9827:                 if (defined($usertypes->{$item})) {
                   9828:                     push(@okstatuses,$item);  
                   9829:                 }
                   9830:             }
                   9831:             if (@okstatuses) {
                   9832:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9833:             }
                   9834:         }
                   9835:     }
1.1075    raeburn  9836:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9837:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9838:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9839:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9840:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9841:     } else {
                   9842:         $logmsg .= ' during self creation';
                   9843:     }
1.1075    raeburn  9844:     my $changed;
                   9845:     if ($newuser) {
                   9846:         $changed = 1;
                   9847:     } else {
                   9848:         foreach my $field (@fields) {
                   9849:             if ($names{$field} ne $oldnames{$field}) {
                   9850:                 $changed = 1;
                   9851:                 last;
                   9852:             }
                   9853:         }
                   9854:     }
                   9855:     unless ($changed) {
                   9856:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9857:         &logthis($logmsg);
                   9858:         return 'ok';
                   9859:     }
                   9860:     my $reply = &put('environment', \%names, $udom,$uname);
                   9861:     if ($reply ne 'ok') { 
                   9862:         return 'error: '.$reply;
                   9863:     }
1.1087    raeburn  9864:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9865:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9866:     }
1.1075    raeburn  9867:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9868:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9869:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9870:     &logthis($logmsg);
1.134     albertel 9871:     return 'ok';
1.80      www      9872: }
                   9873: 
1.81      www      9874: # -------------------------------------------------------------- Modify student
1.80      www      9875: 
1.81      www      9876: sub modifystudent {
                   9877:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9878:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9879:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9880:     if (!$cid) {
1.620     albertel 9881: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9882: 	    return 'not_in_class';
                   9883: 	}
1.80      www      9884:     }
                   9885: # --------------------------------------------------------------- Make the user
1.81      www      9886:     my $reply=&modifyuser
1.209     matthew  9887: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9888:          $desiredhome,$email,$inststatus);
1.80      www      9889:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9890:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9891:     # student's environment
1.297     matthew  9892:     $uid = undef if (!$forceid);
1.455     albertel 9893:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9894:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9895:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9896:     return $reply;
                   9897: }
                   9898: 
                   9899: sub modify_student_enrollment {
1.1216    raeburn  9900:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9901:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9902:     my ($cdom,$cnum,$chome);
                   9903:     if (!$cid) {
1.620     albertel 9904: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9905: 	    return 'not_in_class';
                   9906: 	}
1.620     albertel 9907: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9908: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9909:     } else {
                   9910: 	($cdom,$cnum)=split(/_/,$cid);
                   9911:     }
1.620     albertel 9912:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9913:     if (!$chome) {
1.457     raeburn  9914: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9915:     }
1.455     albertel 9916:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9917:     # Make sure the user exists
1.81      www      9918:     my $uhome=&homeserver($uname,$udom);
                   9919:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9920: 	return 'error: no such user';
                   9921:     }
1.297     matthew  9922:     # Get student data if we were not given enough information
                   9923:     if (!defined($first)  || $first  eq '' || 
                   9924:         !defined($last)   || $last   eq '' || 
                   9925:         !defined($uid)    || $uid    eq '' || 
                   9926:         !defined($middle) || $middle eq '' || 
                   9927:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9928:         # They did not supply us with enough data to enroll the student, so
                   9929:         # we need to pick up more information.
1.297     matthew  9930:         my %tmp = &get('environment',
1.294     matthew  9931:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9932:                        ,$udom,$uname);
                   9933: 
1.800     albertel 9934:         #foreach my $key (keys(%tmp)) {
                   9935:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9936:         #}
1.294     matthew  9937:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9938:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9939:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9940:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9941:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9942:     }
1.556     albertel 9943:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9944:     my $user = "$uname:$udom";
                   9945:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9946:     my $reply=cput('classlist',
1.1148    raeburn  9947: 		   {$user => 
1.1314    raeburn  9948: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9949: 		   $cdom,$cnum);
1.1148    raeburn  9950:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9951:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9952:     } else { 
1.81      www      9953: 	return 'error: '.$reply;
                   9954:     }
1.297     matthew  9955:     # Add student role to user
1.83      www      9956:     my $uurl='/'.$cid;
1.81      www      9957:     $uurl=~s/\_/\//g;
                   9958:     if ($usec) {
                   9959: 	$uurl.='/'.$usec;
                   9960:     }
1.1148    raeburn  9961:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9962:                              $selfenroll,$context);
                   9963:     if ($result ne 'ok') {
                   9964:         if ($old_entry{$user} ne '') {
                   9965:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9966:         } else {
                   9967:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9968:         }
                   9969:     }
                   9970:     return $result; 
1.21      www      9971: }
                   9972: 
1.556     albertel 9973: sub format_name {
                   9974:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9975:     my $name;
                   9976:     if ($first ne 'lastname') {
                   9977: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9978:     } else {
                   9979: 	if ($lastname=~/\S/) {
                   9980: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9981: 	    $name=~s/\s+,/,/;
                   9982: 	} else {
                   9983: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9984: 	}
                   9985:     }
                   9986:     $name=~s/^\s+//;
                   9987:     $name=~s/\s+$//;
                   9988:     $name=~s/\s+/ /g;
                   9989:     return $name;
                   9990: }
                   9991: 
1.84      www      9992: # ------------------------------------------------- Write to course preferences
                   9993: 
                   9994: sub writecoursepref {
                   9995:     my ($courseid,%prefs)=@_;
                   9996:     $courseid=~s/^\///;
                   9997:     $courseid=~s/\_/\//g;
                   9998:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9999:     my $chome=homeserver($cnum,$cdomain);
                   10000:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10001: 	return 'error: no such course';
                   10002:     }
                   10003:     my $cstring='';
1.800     albertel 10004:     foreach my $pref (keys(%prefs)) {
                   10005: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10006:     }
1.84      www      10007:     $cstring=~s/\&$//;
                   10008:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10009: }
                   10010: 
                   10011: # ---------------------------------------------------------- Make/modify course
                   10012: 
                   10013: sub createcourse {
1.741     raeburn  10014:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10015:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10016:     $url=&declutter($url);
                   10017:     my $cid='';
1.1028    raeburn  10018:     if ($context eq 'requestcourses') {
                   10019:         my $can_create = 0;
                   10020:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10021:         if ($udom eq $ownerdom) {
                   10022:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10023:                                   $context)) {
                   10024:                 $can_create = 1;
                   10025:             }
                   10026:         } else {
                   10027:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10028:                                            $category);
                   10029:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10030:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10031:                 if (@curr > 0) {
                   10032:                     my @options = qw(approval validate autolimit);
                   10033:                     my $optregex = join('|',@options);
                   10034:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10035:                         $can_create = 1;
                   10036:                     }
                   10037:                 }
                   10038:             }
                   10039:         }
                   10040:         if ($can_create) {
                   10041:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10042:                 unless (&allowed('ccc',$udom)) {
                   10043:                     return 'refused'; 
                   10044:                 }
1.1017    raeburn  10045:             }
                   10046:         } else {
                   10047:             return 'refused';
                   10048:         }
1.1028    raeburn  10049:     } elsif (!&allowed('ccc',$udom)) {
                   10050:         return 'refused';
1.84      www      10051:     }
1.1011    raeburn  10052: # --------------------------------------------------------------- Get Unique ID
                   10053:     my $uname;
                   10054:     if ($cnum =~ /^$match_courseid$/) {
                   10055:         my $chome=&homeserver($cnum,$udom,'true');
                   10056:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10057:             $uname = $cnum;
                   10058:         } else {
1.1038    raeburn  10059:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10060:         }
                   10061:     } else {
1.1038    raeburn  10062:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10063:     }
                   10064:     return $uname if ($uname =~ /^error/);
                   10065: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10066:     if (!defined($course_server)) {
                   10067:         if (defined(&domain($udom,'primary'))) {
                   10068:             $course_server = &domain($udom,'primary');
                   10069:         } else {
                   10070:             $course_server = $env{'user.home'}; 
                   10071:         }
                   10072:     }
                   10073:     my %host_servers =
                   10074:         &Apache::lonnet::get_servers($udom,'library');
                   10075:     unless ($host_servers{$course_server}) {
                   10076:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10077:     }
1.84      www      10078: # ------------------------------------------------------------- Make the course
                   10079:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10080:                       $course_server);
1.84      www      10081:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10082:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10083:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10084: 	return 'error: no such course';
                   10085:     }
1.271     www      10086: # ----------------------------------------------------------------- Course made
1.516     raeburn  10087: # log existence
1.1029    raeburn  10088:     my $now = time;
1.918     raeburn  10089:     my $newcourse = {
                   10090:                     $udom.'_'.$uname => {
1.921     raeburn  10091:                                      description => $description,
                   10092:                                      inst_code   => $inst_code,
                   10093:                                      owner       => $course_owner,
                   10094:                                      type        => $crstype,
1.1029    raeburn  10095:                                      creator     => $env{'user.name'}.':'.
                   10096:                                                     $env{'user.domain'},
                   10097:                                      created     => $now,
                   10098:                                      context     => $context,
1.918     raeburn  10099:                                                 },
                   10100:                     };
1.921     raeburn  10101:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10102: # set toplevel url
1.271     www      10103:     my $topurl=$url;
                   10104:     unless ($nonstandard) {
                   10105: # ------------------------------------------ For standard courses, make top url
                   10106:         my $mapurl=&clutter($url);
1.278     www      10107:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10108:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10109: <map>
                   10110: <resource id="1" type="start"></resource>
                   10111: <resource id="2" src="$mapurl"></resource>
                   10112: <resource id="3" type="finish"></resource>
                   10113: <link index="1" from="1" to="2"></link>
                   10114: <link index="2" from="2" to="3"></link>
                   10115: </map>
                   10116: ENDINITMAP
                   10117:         $topurl=&declutter(
1.638     albertel 10118:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10119:                           );
                   10120:     }
                   10121: # ----------------------------------------------------------- Write preferences
1.84      www      10122:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10123:                      ('description'              => $description,
                   10124:                       'url'                      => $topurl,
                   10125:                       'internal.creator'         => $env{'user.name'}.':'.
                   10126:                                                     $env{'user.domain'},
                   10127:                       'internal.created'         => $now,
                   10128:                       'internal.creationcontext' => $context)
                   10129:                     );
1.84      www      10130:     return '/'.$udom.'/'.$uname;
                   10131: }
                   10132: 
1.1011    raeburn  10133: # ------------------------------------------------------------------- Create ID
                   10134: sub generate_coursenum {
1.1038    raeburn  10135:     my ($udom,$crstype) = @_;
1.1011    raeburn  10136:     my $domdesc = &domain($udom);
                   10137:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10138:     my $first;
                   10139:     if ($crstype eq 'Community') {
                   10140:         $first = '0';
                   10141:     } else {
                   10142:         $first = int(1+rand(9)); 
                   10143:     } 
                   10144:     my $uname=$first.
1.1011    raeburn  10145:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10146:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10147:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10148: # ----------------------------------------------- Make sure that does not exist
                   10149:     my $uhome=&homeserver($uname,$udom,'true');
                   10150:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10151:         if ($crstype eq 'Community') {
                   10152:             $first = '0';
                   10153:         } else {
                   10154:             $first = int(1+rand(9));
                   10155:         }
                   10156:         $uname=$first.
1.1011    raeburn  10157:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10158:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10159:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10160:         $uhome=&homeserver($uname,$udom,'true');
                   10161:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10162:             return 'error: unable to generate unique course-ID';
                   10163:         }
                   10164:     }
                   10165:     return $uname;
                   10166: }
                   10167: 
1.813     albertel 10168: sub is_course {
1.1167    droeschl 10169:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10170:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10171: 
1.1381    raeburn  10172:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10173:     my $uhome=&homeserver($cnum,$cdom);
                   10174:     my $iscourse;
                   10175:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10176:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10177:     } else {
                   10178:         my $hashid = $cdom.':'.$cnum;
                   10179:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10180:         unless (defined($cached)) {
                   10181:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10182:                                         $cnum,undef,undef,'.');
                   10183:             $iscourse = 0;
                   10184:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10185:                 $iscourse = 1;
                   10186:             }
                   10187:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10188:         }
                   10189:     }
                   10190:     return unless ($iscourse);
1.1167    droeschl 10191:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10192: }
                   10193: 
1.1015    raeburn  10194: sub store_userdata {
                   10195:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10196:     my $result;
1.1016    raeburn  10197:     if ($datakey ne '') {
1.1013    raeburn  10198:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10199:             if ($udom eq '' || $uname eq '') {
                   10200:                 $udom = $env{'user.domain'};
                   10201:                 $uname = $env{'user.name'};
                   10202:             }
                   10203:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10204:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10205:                 $result = 'error: no_host';
                   10206:             } else {
                   10207:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10208:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10209: 
                   10210:                 my $namevalue='';
                   10211:                 foreach my $key (keys(%{$storehash})) {
                   10212:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10213:                 }
                   10214:                 $namevalue=~s/\&$//;
1.1224    raeburn  10215:                 unless ($namespace eq 'courserequests') {
                   10216:                     $datakey = &escape($datakey);
                   10217:                 }
1.1105    raeburn  10218:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10219:                                   $namevalue,$uhome);
1.1013    raeburn  10220:             }
                   10221:         } else {
                   10222:             $result = 'error: data to store was not a hash reference'; 
                   10223:         }
                   10224:     } else {
                   10225:         $result= 'error: invalid requestkey'; 
                   10226:     }
                   10227:     return $result;
                   10228: }
                   10229: 
1.21      www      10230: # ---------------------------------------------------------- Assign Custom Role
                   10231: 
                   10232: sub assigncustomrole {
1.957     raeburn  10233:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10234:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10235:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10236: }
                   10237: 
                   10238: # ----------------------------------------------------------------- Revoke Role
                   10239: 
                   10240: sub revokerole {
1.957     raeburn  10241:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10242:     my $now=time;
1.965     raeburn  10243:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10244: }
                   10245: 
                   10246: # ---------------------------------------------------------- Revoke Custom Role
                   10247: 
                   10248: sub revokecustomrole {
1.957     raeburn  10249:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10250:     my $now=time;
1.357     www      10251:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10252:            $deleteflag,$selfenroll,$context);
1.17      www      10253: }
                   10254: 
1.533     banghart 10255: # ------------------------------------------------------------ Disk usage
1.535     albertel 10256: sub diskusage {
1.955     raeburn  10257:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10258:     $directorypath =~ s/\/$//;
                   10259:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10260:                        .&escape($getpropath).':'.&escape($uname).':'
                   10261:                        .&escape($udom),homeserver($uname,$udom));
                   10262:     if ($listing eq 'unknown_cmd') {
                   10263:         if ($getpropath) {
                   10264:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10265:         }
                   10266:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10267:     }
1.514     albertel 10268:     return $listing;
1.512     banghart 10269: }
                   10270: 
1.566     banghart 10271: sub is_locked {
1.1096    raeburn  10272:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10273:     my @check;
                   10274:     my $is_locked;
1.1093    raeburn  10275:     push (@check,$file_name);
1.613     albertel 10276:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10277: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10278:     my ($tmp)=keys(%locked);
                   10279:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10280:     
1.566     banghart 10281:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10282:         $is_locked = 'false';
                   10283:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10284:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10285:                $is_locked = 'true';
1.1096    raeburn  10286:                if (ref($which) eq 'ARRAY') {
                   10287:                    push(@{$which},$entry);
                   10288:                } else {
                   10289:                    last;
                   10290:                }
1.745     raeburn  10291:            }
                   10292:        }
1.566     banghart 10293:     } else {
                   10294:         $is_locked = 'false';
                   10295:     }
1.1093    raeburn  10296:     return $is_locked;
1.566     banghart 10297: }
                   10298: 
1.759     albertel 10299: sub declutter_portfile {
                   10300:     my ($file) = @_;
1.833     albertel 10301:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10302:     return $file;
                   10303: }
                   10304: 
1.559     banghart 10305: # ------------------------------------------------------------- Mark as Read Only
                   10306: 
                   10307: sub mark_as_readonly {
                   10308:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10309:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10310:     my ($tmp)=keys(%current_permissions);
                   10311:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10312:     foreach my $file (@{$files}) {
1.759     albertel 10313: 	$file = &declutter_portfile($file);
1.561     banghart 10314:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10315:     }
1.613     albertel 10316:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10317:     return;
                   10318: }
                   10319: 
1.572     banghart 10320: # ------------------------------------------------------------Save Selected Files
                   10321: 
                   10322: sub save_selected_files {
                   10323:     my ($user, $path, @files) = @_;
                   10324:     my $filename = $user."savedfiles";
1.573     banghart 10325:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10326:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10327:     foreach my $file (@files) {
1.620     albertel 10328:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10329:     }
                   10330:     foreach my $file (@other_files) {
1.574     banghart 10331:         print (OUT $file."\n");
1.572     banghart 10332:     }
1.574     banghart 10333:     close (OUT);
1.572     banghart 10334:     return 'ok';
                   10335: }
                   10336: 
1.574     banghart 10337: sub clear_selected_files {
                   10338:     my ($user) = @_;
                   10339:     my $filename = $user."savedfiles";
1.1359    raeburn  10340:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10341:     print (OUT undef);
                   10342:     close (OUT);
                   10343:     return ("ok");    
                   10344: }
                   10345: 
1.572     banghart 10346: sub files_in_path {
                   10347:     my ($user, $path) = @_;
                   10348:     my $filename = $user."savedfiles";
                   10349:     my %return_files;
1.1359    raeburn  10350:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10351:     while (my $line_in = <IN>) {
1.574     banghart 10352:         chomp ($line_in);
                   10353:         my @paths_and_file = split (m!/!, $line_in);
                   10354:         my $file_part = pop (@paths_and_file);
                   10355:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10356:         $path_part.='/';
                   10357:         my $path_and_file = $path_part.$file_part;
                   10358:         if ($path_part eq $path) {
                   10359:             $return_files{$file_part}= 'selected';
                   10360:         }
                   10361:     }
1.574     banghart 10362:     close (IN);
                   10363:     return (\%return_files);
1.572     banghart 10364: }
                   10365: 
                   10366: # called in portfolio select mode, to show files selected NOT in current directory
                   10367: sub files_not_in_path {
                   10368:     my ($user, $path) = @_;
                   10369:     my $filename = $user."savedfiles";
                   10370:     my @return_files;
                   10371:     my $path_part;
1.1359    raeburn  10372:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10373:     while (my $line = <IN>) {
1.572     banghart 10374:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10375:         my @paths_and_file = split(m|/|, $line);
                   10376:         my $file_part = pop(@paths_and_file);
                   10377:         chomp($file_part);
                   10378:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10379:         $path_part .= '/';
                   10380:         my $path_and_file = $path_part.$file_part;
                   10381:         if ($path_part ne $path) {
1.800     albertel 10382:             push(@return_files, ($path_and_file));
1.572     banghart 10383:         }
                   10384:     }
1.800     albertel 10385:     close(OUT);
1.574     banghart 10386:     return (@return_files);
1.572     banghart 10387: }
                   10388: 
1.1273    raeburn  10389: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10390:  
                   10391: sub portfiles_versioning {
                   10392:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10393:     my $portfolio_root = '/userfiles/portfolio';
                   10394:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10395:     foreach my $file (@{$portfiles}) {
                   10396:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10397:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10398:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10399:         my $getpropath = 1;
                   10400:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10401:                                              $stu_name,$getpropath);
                   10402:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10403:         my $new_answer = 
                   10404:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10405:         if ($new_answer ne 'problem getting file') {
                   10406:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10407:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10408:                               [$symb,$env{'request.course.id'},'graded']);
                   10409:         }
                   10410:     }
                   10411: }
                   10412: 
                   10413: sub get_next_version {
                   10414:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10415:     my $version;
                   10416:     if (ref($dir_list) eq 'ARRAY') {
                   10417:         foreach my $row (@{$dir_list}) {
                   10418:             my ($file) = split(/\&/,$row,2);
                   10419:             my ($file_name,$file_version,$file_ext) =
                   10420:                 &file_name_version_ext($file);
                   10421:             if (($file_name eq $answer_name) &&
                   10422:                 ($file_ext eq $answer_ext)) {
                   10423:                      # gets here if filename and extension match,
                   10424:                      # regardless of version
                   10425:                 if ($file_version ne '') {
                   10426:                     # a versioned file is found  so save it for later
                   10427:                     if ($file_version > $version) {
                   10428:                         $version = $file_version;
                   10429:                     }
                   10430:                 }
                   10431:             }
                   10432:         }
                   10433:     }
                   10434:     $version ++;
                   10435:     return($version);
                   10436: }
                   10437: 
                   10438: sub version_selected_portfile {
                   10439:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10440:     my ($answer_name,$answer_ver,$answer_ext) =
                   10441:         &file_name_version_ext($file_name);
                   10442:     my $new_answer;
                   10443:     $env{'form.copy'} =
                   10444:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10445:     if($env{'form.copy'} eq '-1') {
                   10446:         $new_answer = 'problem getting file';
                   10447:     } else {
                   10448:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10449:         my $copy_result = 
                   10450:             &finishuserfileupload($stu_name,$domain,'copy',
                   10451:                                   '/portfolio'.$directory.$new_answer);
                   10452:     }
                   10453:     undef($env{'form.copy'});
                   10454:     return ($new_answer);
                   10455: }
                   10456: 
                   10457: sub file_name_version_ext {
                   10458:     my ($file)=@_;
                   10459:     my @file_parts = split(/\./, $file);
                   10460:     my ($name,$version,$ext);
                   10461:     if (@file_parts > 1) {
                   10462:         $ext=pop(@file_parts);
                   10463:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10464:             $version=pop(@file_parts);
                   10465:         }
                   10466:         $name=join('.',@file_parts);
                   10467:     } else {
                   10468:         $name=join('.',@file_parts);
                   10469:     }
                   10470:     return($name,$version,$ext);
                   10471: }
                   10472: 
1.745     raeburn  10473: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10474: 
1.745     raeburn  10475: sub get_portfile_permissions {
                   10476:     my ($domain,$user) = @_;
1.613     albertel 10477:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10478:     my ($tmp)=keys(%current_permissions);
                   10479:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10480:     return \%current_permissions;
                   10481: }
                   10482: 
                   10483: #---------------------------------------------Get portfolio file access controls
                   10484: 
1.749     raeburn  10485: sub get_access_controls {
1.745     raeburn  10486:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10487:     my %access;
                   10488:     my $real_file = $file;
                   10489:     $file =~ s/\.meta$//;
1.745     raeburn  10490:     if (defined($file)) {
1.749     raeburn  10491:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10492:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10493:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10494:             }
                   10495:         }
1.745     raeburn  10496:     } else {
1.749     raeburn  10497:         foreach my $key (keys(%{$current_permissions})) {
                   10498:             if ($key =~ /\0accesscontrol$/) {
                   10499:                 if (defined($group)) {
                   10500:                     if ($key !~ m-^\Q$group\E/-) {
                   10501:                         next;
                   10502:                     }
                   10503:                 }
                   10504:                 my ($fullpath) = split(/\0/,$key);
                   10505:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10506:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10507:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10508:                     }
                   10509:                 }
                   10510:             }
                   10511:         }
                   10512:     }
                   10513:     return %access;
                   10514: }
                   10515: 
                   10516: sub modify_access_controls {
                   10517:     my ($file_name,$changes,$domain,$user)=@_;
                   10518:     my ($outcome,$deloutcome);
                   10519:     my %store_permissions;
                   10520:     my %new_values;
                   10521:     my %new_control;
                   10522:     my %translation;
                   10523:     my @deletions = ();
                   10524:     my $now = time;
                   10525:     if (exists($$changes{'activate'})) {
                   10526:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10527:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10528:             my $numnew = scalar(@newitems);
                   10529:             for (my $i=0; $i<$numnew; $i++) {
                   10530:                 my $newkey = $newitems[$i];
                   10531:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10532:                 if ($newkey =~ /^\d+:/) { 
                   10533:                     $newkey =~ s/^(\d+)/$newid/;
                   10534:                     $translation{$1} = $newid;
                   10535:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10536:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10537:                     $translation{$1} = $newid;
                   10538:                 }
1.749     raeburn  10539:                 $new_values{$file_name."\0".$newkey} = 
                   10540:                                           $$changes{'activate'}{$newitems[$i]};
                   10541:                 $new_control{$newkey} = $now;
                   10542:             }
                   10543:         }
                   10544:     }
                   10545:     my %todelete;
                   10546:     my %changed_items;
                   10547:     foreach my $action ('delete','update') {
                   10548:         if (exists($$changes{$action})) {
                   10549:             if (ref($$changes{$action}) eq 'HASH') {
                   10550:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10551:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10552:                     if ($action eq 'delete') { 
                   10553:                         $todelete{$itemnum} = 1;
                   10554:                     } else {
                   10555:                         $changed_items{$itemnum} = $key;
                   10556:                     }
                   10557:                 }
1.745     raeburn  10558:             }
                   10559:         }
1.749     raeburn  10560:     }
                   10561:     # get lock on access controls for file.
                   10562:     my $lockhash = {
                   10563:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10564:                                                        ':'.$env{'user.domain'},
                   10565:                    }; 
                   10566:     my $tries = 0;
                   10567:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10568:    
1.1288    damieng  10569:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10570:         $tries ++;
1.1289    damieng  10571:         sleep(0.1);
1.749     raeburn  10572:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10573:     }
                   10574:     if ($gotlock eq 'ok') {
                   10575:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10576:         my ($tmp)=keys(%curr_permissions);
                   10577:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10578:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10579:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10580:             if (ref($curr_controls) eq 'HASH') {
                   10581:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10582:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10583:                     if (defined($todelete{$itemnum})) {
                   10584:                         push(@deletions,$file_name."\0".$control_item);
                   10585:                     } else {
                   10586:                         if (defined($changed_items{$itemnum})) {
                   10587:                             $new_control{$changed_items{$itemnum}} = $now;
                   10588:                             push(@deletions,$file_name."\0".$control_item);
                   10589:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10590:                         } else {
                   10591:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10592:                         }
                   10593:                     }
1.745     raeburn  10594:                 }
                   10595:             }
                   10596:         }
1.970     raeburn  10597:         my ($group);
                   10598:         if (&is_course($domain,$user)) {
                   10599:             ($group,my $file) = split(/\//,$file_name,2);
                   10600:         }
1.749     raeburn  10601:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10602:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10603:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10604:         #  remove lock
                   10605:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10606:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10607:         my $sqlresult =
1.970     raeburn  10608:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10609:                                     $group);
1.749     raeburn  10610:     } else {
                   10611:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10612:     }
1.749     raeburn  10613:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10614: }
                   10615: 
1.827     raeburn  10616: sub make_public_indefinitely {
1.1271    raeburn  10617:     my (@requrl) = @_;
                   10618:     return &automated_portfile_access('public',\@requrl);
                   10619: }
                   10620: 
                   10621: sub automated_portfile_access {
                   10622:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10623:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10624:         return 'invalid';
                   10625:     }
1.1271    raeburn  10626:     my %urls;
                   10627:     if (ref($addsref) eq 'ARRAY') {
                   10628:         foreach my $requrl (@{$addsref}) {
                   10629:             if (&is_portfolio_url($requrl)) {
                   10630:                 unless (exists($urls{$requrl})) {
                   10631:                     $urls{$requrl} = 'add';
                   10632:                 }
                   10633:             }
                   10634:         }
                   10635:     }
                   10636:     if (ref($delsref) eq 'ARRAY') {
                   10637:         foreach my $requrl (@{$delsref}) { 
                   10638:             if (&is_portfolio_url($requrl)) {
                   10639:                 unless (exists($urls{$requrl})) {
                   10640:                     $urls{$requrl} = 'delete'; 
                   10641:                 }
                   10642:             }
                   10643:         }
                   10644:     }
                   10645:     unless (keys(%urls)) {
                   10646:         return 'invalid';
                   10647:     }
                   10648:     my $ip;
                   10649:     if ($accesstype eq 'ip') {
                   10650:         if (ref($info) eq 'HASH') {
                   10651:             if ($info->{'ip'} ne '') {
                   10652:                 $ip = $info->{'ip'};
                   10653:             }
                   10654:         }
                   10655:         if ($ip eq '') {
                   10656:             return 'invalid';
                   10657:         }
                   10658:     }
                   10659:     my $errors;
1.827     raeburn  10660:     my $now = time;
1.1271    raeburn  10661:     my %current_perms;
                   10662:     foreach my $requrl (sort(keys(%urls))) {
                   10663:         my $action;
                   10664:         if ($urls{$requrl} eq 'add') {
                   10665:             $action = 'activate';
                   10666:         } else {
                   10667:             $action = 'none';
                   10668:         }
                   10669:         my $aclnum = 0;
1.827     raeburn  10670:         my (undef,$udom,$unum,$file_name,$group) =
                   10671:             &parse_portfolio_url($requrl);
1.1271    raeburn  10672:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10673:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10674:         }
                   10675:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10676:                                                    $group,$file_name);
                   10677:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10678:             my ($num,$scope,$end,$start) = 
                   10679:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10680:             if ($scope eq $accesstype) {
                   10681:                 if (($start <= $now) && ($end == 0)) {
                   10682:                     if ($accesstype eq 'ip') {
                   10683:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10684:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10685:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10686:                                     if ($urls{$requrl} eq 'add') {
                   10687:                                         $action = 'none';
                   10688:                                         last;
                   10689:                                     } else {
                   10690:                                         $action = 'delete';
                   10691:                                         $aclnum = $num;
                   10692:                                         last;
                   10693:                                     }
                   10694:                                 }
                   10695:                             }
                   10696:                         }
                   10697:                     } elsif ($accesstype eq 'public') {
                   10698:                         if ($urls{$requrl} eq 'add') {
                   10699:                             $action = 'none';
                   10700:                             last;
                   10701:                         } else {
                   10702:                             $action = 'delete';
                   10703:                             $aclnum = $num;
                   10704:                             last;
                   10705:                         }
                   10706:                     }
                   10707:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10708:                     $action = 'update';
                   10709:                     $aclnum = $num;
1.1271    raeburn  10710:                     last;
1.827     raeburn  10711:                 }
                   10712:             }
                   10713:         }
                   10714:         if ($action eq 'none') {
1.1271    raeburn  10715:             next;
1.827     raeburn  10716:         } else {
                   10717:             my %changes;
                   10718:             my $newend = 0;
                   10719:             my $newstart = $now;
1.1271    raeburn  10720:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10721:             $changes{$action}{$newkey} = {
1.1271    raeburn  10722:                 type => $accesstype,
1.827     raeburn  10723:                 time => {
                   10724:                     start => $newstart,
                   10725:                     end   => $newend,
                   10726:                 },
                   10727:             };
1.1271    raeburn  10728:             if ($accesstype eq 'ip') {
                   10729:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10730:             }
1.827     raeburn  10731:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10732:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10733:             unless ($outcome eq 'ok') {
                   10734:                 $errors .= $outcome.' ';
                   10735:             }
1.827     raeburn  10736:         }
1.1271    raeburn  10737:     }
                   10738:     if ($errors) {
                   10739:         $errors =~ s/\s$//;
                   10740:         return $errors;
1.827     raeburn  10741:     } else {
1.1271    raeburn  10742:         return 'ok';
1.827     raeburn  10743:     }
                   10744: }
                   10745: 
1.745     raeburn  10746: #------------------------------------------------------Get Marked as Read Only
                   10747: 
                   10748: sub get_marked_as_readonly {
                   10749:     my ($domain,$user,$what,$group) = @_;
                   10750:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10751:     my @readonly_files;
1.629     banghart 10752:     my $cmp1=$what;
                   10753:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10754:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10755:         if (defined($group)) {
                   10756:             if ($file_name !~ m-^\Q$group\E/-) {
                   10757:                 next;
                   10758:             }
                   10759:         }
1.561     banghart 10760:         if (ref($value) eq "ARRAY"){
                   10761:             foreach my $stored_what (@{$value}) {
1.629     banghart 10762:                 my $cmp2=$stored_what;
1.759     albertel 10763:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10764:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10765:                 }
1.629     banghart 10766:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10767:                     push(@readonly_files, $file_name);
1.745     raeburn  10768:                     last;
1.563     banghart 10769:                 } elsif (!defined($what)) {
                   10770:                     push(@readonly_files, $file_name);
1.745     raeburn  10771:                     last;
1.561     banghart 10772:                 }
                   10773:             }
1.745     raeburn  10774:         }
1.561     banghart 10775:     }
                   10776:     return @readonly_files;
                   10777: }
1.577     banghart 10778: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10779: 
1.577     banghart 10780: sub get_marked_as_readonly_hash {
1.745     raeburn  10781:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10782:     my %readonly_files;
1.745     raeburn  10783:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10784:         if (defined($group)) {
                   10785:             if ($file_name !~ m-^\Q$group\E/-) {
                   10786:                 next;
                   10787:             }
                   10788:         }
1.577     banghart 10789:         if (ref($value) eq "ARRAY"){
                   10790:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10791:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10792:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10793:                         if ($lock_descriptor eq 'graded') {
                   10794:                             $readonly_files{$file_name} = 'graded';
                   10795:                         } elsif ($lock_descriptor eq 'handback') {
                   10796:                             $readonly_files{$file_name} = 'handback';
                   10797:                         } else {
                   10798:                             if (!exists($readonly_files{$file_name})) {
                   10799:                                 $readonly_files{$file_name} = 'locked';
                   10800:                             }
                   10801:                         }
1.745     raeburn  10802:                     }
1.750     banghart 10803:                 } 
1.577     banghart 10804:             }
                   10805:         } 
                   10806:     }
                   10807:     return %readonly_files;
                   10808: }
1.559     banghart 10809: # ------------------------------------------------------------ Unmark as Read Only
                   10810: 
                   10811: sub unmark_as_readonly {
1.629     banghart 10812:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10813:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10814:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10815:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10816:     my $symb_crs = $what;
                   10817:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10818:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10819:     my ($tmp)=keys(%current_permissions);
                   10820:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10821:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10822:     foreach my $file (@readonly_files) {
1.759     albertel 10823: 	my $clean_file = &declutter_portfile($file);
                   10824: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10825: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10826:         my @new_locks;
                   10827:         my @del_keys;
                   10828:         if (ref($current_locks) eq "ARRAY"){
                   10829:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10830:                 my $compare=$locker;
1.749     raeburn  10831:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10832:                     $compare=join('',@{$locker});
1.746     raeburn  10833:                     if ($compare ne $symb_crs) {
                   10834:                         push(@new_locks, $locker);
                   10835:                     }
1.563     banghart 10836:                 }
                   10837:             }
1.650     albertel 10838:             if (scalar(@new_locks) > 0) {
1.563     banghart 10839:                 $current_permissions{$file} = \@new_locks;
                   10840:             } else {
                   10841:                 push(@del_keys, $file);
1.613     albertel 10842:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10843:                 delete($current_permissions{$file});
1.563     banghart 10844:             }
                   10845:         }
1.561     banghart 10846:     }
1.613     albertel 10847:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10848:     return;
                   10849: }
1.512     banghart 10850: 
1.17      www      10851: # ------------------------------------------------------------ Directory lister
                   10852: 
                   10853: sub dirlist {
1.955     raeburn  10854:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10855:     $uri=~s/^\///;
                   10856:     $uri=~s/\/$//;
1.253     stredwic 10857:     my ($udom, $uname);
1.955     raeburn  10858:     if ($getuserdir) {
1.253     stredwic 10859:         $udom = $userdomain;
                   10860:         $uname = $username;
1.955     raeburn  10861:     } else {
                   10862:         (undef,$udom,$uname)=split(/\//,$uri);
                   10863:         if(defined($userdomain)) {
                   10864:             $udom = $userdomain;
                   10865:         }
                   10866:         if(defined($username)) {
                   10867:             $uname = $username;
                   10868:         }
1.253     stredwic 10869:     }
1.955     raeburn  10870:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10871: 
1.955     raeburn  10872:     $dirRoot = $perlvar{'lonDocRoot'};
                   10873:     if (defined($getpropath)) {
                   10874:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10875:         $dirRoot =~ s/\/$//;
1.955     raeburn  10876:     } elsif (defined($getuserdir)) {
                   10877:         my $subdir=$uname.'__';
                   10878:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10879:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10880:                    ."/$udom/$subdir/$uname";
                   10881:     } elsif (defined($alternateRoot)) {
                   10882:         $dirRoot = $alternateRoot;
1.751     banghart 10883:     }
1.253     stredwic 10884: 
                   10885:     if($udom) {
                   10886:         if($uname) {
1.1135    raeburn  10887:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10888:             if ($uhome eq 'no_host') {
                   10889:                 return ([],'no_host');
                   10890:             }
1.955     raeburn  10891:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10892:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10893:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10894:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10895:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10896:             } else {
                   10897:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10898:             }
1.605     matthew  10899:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10900:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10901:                 @listing_results = split(/:/,$listing);
                   10902:             } else {
                   10903:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10904:             }
1.1135    raeburn  10905:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10906:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10907:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10908:                 return ([],$listing);
                   10909:             } else {
                   10910:                 return (\@listing_results);
1.1135    raeburn  10911:             }
1.955     raeburn  10912:         } elsif(!$alternateRoot) {
1.1136    raeburn  10913:             my (%allusers,%listerror);
1.841     albertel 10914: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10915:  	    foreach my $tryserver (keys(%servers)) {
                   10916:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10917:                                   &escape($udom),$tryserver);
                   10918:                 if ($listing eq 'unknown_cmd') {
                   10919: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10920: 				      $udom, $tryserver);
                   10921:                 } else {
                   10922:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10923:                 }
1.841     albertel 10924: 		if ($listing eq 'unknown_cmd') {
                   10925: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10926: 				      $udom, $tryserver);
                   10927: 		    @listing_results = split(/:/,$listing);
                   10928: 		} else {
                   10929: 		    @listing_results =
                   10930: 			map { &unescape($_); } split(/:/,$listing);
                   10931: 		}
1.1136    raeburn  10932:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10933:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10934:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10935:                     $listerror{$tryserver} = $listing;
                   10936:                 } else {
1.841     albertel 10937: 		    foreach my $line (@listing_results) {
                   10938: 			my ($entry) = split(/&/,$line,2);
                   10939: 			$allusers{$entry} = 1;
                   10940: 		    }
                   10941: 		}
1.253     stredwic 10942:             }
1.1136    raeburn  10943:             my @alluserslist=();
1.800     albertel 10944:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10945:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10946:             }
1.1318    droeschl 10947: 
                   10948:             if (!%listerror) {
                   10949:                 # no errors
                   10950:                 return (\@alluserslist);
                   10951:             } elsif (scalar(keys(%servers)) == 1) {
                   10952:                 # one library server, one error 
                   10953:                 my ($key) = keys(%listerror);
                   10954:                 return (\@alluserslist, $listerror{$key});
                   10955:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10956:                 # con_lost indicates that we might miss data from at least one
                   10957:                 # library server
                   10958:                 return (\@alluserslist, 'con_lost');
                   10959:             } else {
                   10960:                 # multiple library servers and no con_lost -> data should be
                   10961:                 # complete. 
                   10962:                 return (\@alluserslist);
                   10963:             }
                   10964: 
1.253     stredwic 10965:         } else {
1.1136    raeburn  10966:             return ([],'missing username');
1.253     stredwic 10967:         }
1.955     raeburn  10968:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10969:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10970:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10971:         return (\@all_domains);
1.955     raeburn  10972:     } else {
1.1136    raeburn  10973:         return ([],'missing domain');
1.275     stredwic 10974:     }
                   10975: }
                   10976: 
                   10977: # --------------------------------------------- GetFileTimestamp
                   10978: # This function utilizes dirlist and returns the date stamp for
                   10979: # when it was last modified.  It will also return an error of -1
                   10980: # if an error occurs
                   10981: 
                   10982: sub GetFileTimestamp {
1.955     raeburn  10983:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10984:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10985:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10986:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10987:                                     undef,$getuserdir);
                   10988:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10989:         return -1;
                   10990:     }
                   10991:     if (ref($fileref) eq 'ARRAY') {
                   10992:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10993:         # @stats contains first the filename, then the stat output
                   10994:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10995:     } else {
                   10996:         return -1;
1.253     stredwic 10997:     }
1.26      www      10998: }
                   10999: 
1.712     albertel 11000: sub stat_file {
                   11001:     my ($uri) = @_;
1.787     albertel 11002:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11003: 
1.955     raeburn  11004:     my ($udom,$uname,$file);
1.712     albertel 11005:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11006: 	($udom,$uname,$file) =
1.811     albertel 11007: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11008: 	$file = 'userfiles/'.$file;
                   11009:     }
                   11010:     if ($uri =~ m-^/res/-) {
                   11011: 	($udom,$uname) = 
1.807     albertel 11012: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11013: 	$file = $uri;
                   11014:     }
                   11015: 
                   11016:     if (!$udom || !$uname || !$file) {
                   11017: 	# unable to handle the uri
                   11018: 	return ();
                   11019:     }
1.956     raeburn  11020:     my $getpropath;
                   11021:     if ($file =~ /^userfiles\//) {
                   11022:         $getpropath = 1;
                   11023:     }
1.1136    raeburn  11024:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11025:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11026:         return ();
                   11027:     } else {
                   11028:         if (ref($listref) eq 'ARRAY') {
                   11029:             my @stats = split('&',$listref->[0]);
                   11030: 	    shift(@stats); #filename is first
                   11031: 	    return @stats;
                   11032:         }
1.712     albertel 11033:     }
                   11034:     return ();
                   11035: }
                   11036: 
1.1313    raeburn  11037: # --------------------------------------------------------- recursedirs
                   11038: # Recursive function to traverse either a specific user's Authoring Space
                   11039: # or corresponding Published Resource Space, and populate the hash ref:
                   11040: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11041: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11042: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11043: # files in Authoring Space.
                   11044: #
                   11045: # Inputs:
                   11046: #
                   11047: # $is_home - true if current server is home server for user's space
                   11048: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11049: # $docroot - Document root (i.e., /home/httpd/html
                   11050: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11051: # $relpath - Current path (relative to top level).
                   11052: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11053: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11054: #
                   11055: # Returns: nothing
                   11056: #
                   11057: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11058: #
                   11059: # Currently used by interface/londocs.pm to create linked select boxes for
                   11060: # directory and filename to import a Course "Author" resource into a course, and
                   11061: # also to create linked select boxes for Authoring Space and Directory to choose
                   11062: # save location for creation of a new "standard" problem from the Course Editor.
                   11063: #
                   11064: 
                   11065: sub recursedirs {
                   11066:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11067:     return unless (ref($dirhashref) eq 'HASH');
                   11068:     my $currpath = $docroot.$toppath;
                   11069:     if ($relpath) {
                   11070:         $currpath .= "/$relpath";
                   11071:     }
                   11072:     my $savefile;
                   11073:     if (ref($filehashref)) {
                   11074:         $savefile = 1;
                   11075:     }
                   11076:     if ($is_home) {
                   11077:         if (opendir(my $dirh,$currpath)) {
                   11078:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11079:                 next if ($item eq '');
                   11080:                 if (-d "$currpath/$item") {
                   11081:                     my $newpath;
                   11082:                     if ($relpath) {
                   11083:                         $newpath = "$relpath/$item";
                   11084:                     } else {
                   11085:                         $newpath = $item;
                   11086:                     }
                   11087:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11088:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11089:                 } elsif ($savefile) {
                   11090:                     if ($context eq 'priv') {
                   11091:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11092:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11093:                         }
                   11094:                     } else {
                   11095:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11096:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11097:                         }
                   11098:                     }
                   11099:                 }
                   11100:             }
                   11101:             closedir($dirh);
                   11102:         }
                   11103:     } else {
                   11104:         my ($dirlistref,$listerror) =
                   11105:             &dirlist($toppath.$relpath);
                   11106:         my @dir_lines;
                   11107:         my $dirptr=16384;
                   11108:         if (ref($dirlistref) eq 'ARRAY') {
                   11109:             foreach my $dir_line (sort
                   11110:                               {
                   11111:                                   my ($afile)=split('&',$a,2);
                   11112:                                   my ($bfile)=split('&',$b,2);
                   11113:                                   return (lc($afile) cmp lc($bfile));
                   11114:                               } (@{$dirlistref})) {
                   11115:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11116:                     split(/\&/,$dir_line,16);
                   11117:                 $item =~ s/\s+$//;
                   11118:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11119:                 if ($dirptr&$testdir) {
                   11120:                     my $newpath;
                   11121:                     if ($relpath) {
                   11122:                         $newpath = "$relpath/$item";
                   11123:                     } else {
                   11124:                         $relpath = '/';
                   11125:                         $newpath = $item;
                   11126:                     }
                   11127:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11128:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11129:                 } elsif ($savefile) {
                   11130:                     if ($context eq 'priv') {
                   11131:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11132:                             $filehashref->{$relpath}{$item} = 1;
                   11133:                         }
                   11134:                     } else {
                   11135:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11136:                             $filehashref->{$relpath}{$item} = 1;
                   11137:                         }
                   11138:                     }
                   11139:                 }
                   11140:             }
                   11141:         }
                   11142:     }
                   11143:     return;
                   11144: }
                   11145: 
1.26      www      11146: # -------------------------------------------------------- Value of a Condition
                   11147: 
1.713     albertel 11148: # gets the value of a specific preevaluated condition
                   11149: #    stored in the string  $env{user.state.<cid>}
                   11150: # or looks up a condition reference in the bighash and if if hasn't
                   11151: # already been evaluated recurses into docondval to get the value of
                   11152: # the condition, then memoizing it to 
                   11153: #   $env{user.state.<cid>.<condition>}
1.40      www      11154: sub directcondval {
                   11155:     my $number=shift;
1.620     albertel 11156:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11157: 	&Apache::lonuserstate::evalstate();
                   11158:     }
1.713     albertel 11159:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11160: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11161:     } elsif ($number =~ /^_/) {
                   11162: 	my $sub_condition;
                   11163: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11164: 		&GDBM_READER(),0640)) {
                   11165: 	    $sub_condition=$bighash{'conditions'.$number};
                   11166: 	    untie(%bighash);
                   11167: 	}
                   11168: 	my $value = &docondval($sub_condition);
1.949     raeburn  11169: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11170: 	return $value;
                   11171:     }
1.620     albertel 11172:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11173:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11174:     } else {
                   11175:        return 2;
                   11176:     }
                   11177: }
                   11178: 
1.713     albertel 11179: # get the collection of conditions for this resource
1.26      www      11180: sub condval {
                   11181:     my $condidx=shift;
1.54      www      11182:     my $allpathcond='';
1.713     albertel 11183:     foreach my $cond (split(/\|/,$condidx)) {
                   11184: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11185: 	    $allpathcond.=
                   11186: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11187: 	}
1.191     harris41 11188:     }
1.54      www      11189:     $allpathcond=~s/\|$//;
1.713     albertel 11190:     return &docondval($allpathcond);
                   11191: }
                   11192: 
                   11193: #evaluates an expression of conditions
                   11194: sub docondval {
                   11195:     my ($allpathcond) = @_;
                   11196:     my $result=0;
                   11197:     if ($env{'request.course.id'}
                   11198: 	&& defined($allpathcond)) {
                   11199: 	my $operand='|';
                   11200: 	my @stack;
                   11201: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11202: 	    if ($chunk eq '(') {
                   11203: 		push @stack,($operand,$result);
                   11204: 	    } elsif ($chunk eq ')') {
                   11205: 		my $before=pop @stack;
                   11206: 		if (pop @stack eq '&') {
                   11207: 		    $result=$result>$before?$before:$result;
                   11208: 		} else {
                   11209: 		    $result=$result>$before?$result:$before;
                   11210: 		}
                   11211: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11212: 		$operand=$chunk;
                   11213: 	    } else {
                   11214: 		my $new=directcondval($chunk);
                   11215: 		if ($operand eq '&') {
                   11216: 		    $result=$result>$new?$new:$result;
                   11217: 		} else {
                   11218: 		    $result=$result>$new?$result:$new;
                   11219: 		}
                   11220: 	    }
                   11221: 	}
1.26      www      11222:     }
                   11223:     return $result;
1.421     albertel 11224: }
                   11225: 
                   11226: # ---------------------------------------------------- Devalidate courseresdata
                   11227: 
                   11228: sub devalidatecourseresdata {
                   11229:     my ($coursenum,$coursedomain)=@_;
                   11230:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11231:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11232: }
                   11233: 
1.763     www      11234: 
1.200     www      11235: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11236: #
                   11237: #  Parameters:
                   11238: #      $coursenum    - Number of the course.
                   11239: #      $coursedomain - Domain at which the course was created.
                   11240: #  Returns:
                   11241: #     A hash of the course parameters along (I think) with timestamps
                   11242: #     and version info.
1.877     foxr     11243: 
1.624     albertel 11244: sub get_courseresdata {
                   11245:     my ($coursenum,$coursedomain)=@_;
1.200     www      11246:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11247:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11248:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11249:     my %dumpreply;
1.417     albertel 11250:     unless (defined($cached)) {
1.624     albertel 11251: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11252: 	$result=\%dumpreply;
1.251     albertel 11253: 	my ($tmp) = keys(%dumpreply);
                   11254: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11255: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11256: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11257: 	    return $tmp;
1.416     albertel 11258: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11259: 	    $result=undef;
1.599     albertel 11260: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11261: 	}
                   11262:     }
1.624     albertel 11263:     return $result;
                   11264: }
                   11265: 
1.633     albertel 11266: sub devalidateuserresdata {
                   11267:     my ($uname,$udom)=@_;
                   11268:     my $hashid="$udom:$uname";
                   11269:     &devalidate_cache_new('userres',$hashid);
                   11270: }
                   11271: 
1.624     albertel 11272: sub get_userresdata {
                   11273:     my ($uname,$udom)=@_;
                   11274:     #most student don\'t have any data set, check if there is some data
                   11275:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11276: 
                   11277:     my $hashid="$udom:$uname";
                   11278:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11279:     if (!defined($cached)) {
                   11280: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11281: 	$result=\%resourcedata;
                   11282: 	&do_cache_new('userres',$hashid,$result,600);
                   11283:     }
                   11284:     my ($tmp)=keys(%$result);
                   11285:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11286: 	return $result;
                   11287:     }
                   11288:     #error 2 occurs when the .db doesn't exist
                   11289:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11290:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11291: 	    &logthis("<font color=\"blue\">WARNING:".
                   11292: 		     " Trying to get resource data for ".
                   11293: 		     $uname." at ".$udom.": ".
                   11294: 		     $tmp."</font>");
                   11295:         }
1.624     albertel 11296:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11297: 	#&EXT_cache_set($udom,$uname);
                   11298: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11299: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11300:     }
                   11301:     return $tmp;
                   11302: }
1.879     foxr     11303: #----------------------------------------------- resdata - return resource data
                   11304: #  Purpose:
                   11305: #    Return resource data for either users or for a course.
                   11306: #  Parameters:
                   11307: #     $name      - Course/user name.
                   11308: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11309: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11310: #     $mapp      - decluttered URL of enclosing map  
                   11311: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11312: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11313: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11314: #     $courseid  - CourseID (first part of param identifier).
                   11315: #     $modifier  - Middle part of param identifier.
                   11316: #     $what      - Last part of param identifier.
1.879     foxr     11317: #     @which     - Array of names of resources desired.
                   11318: #  Returns:
                   11319: #     The value of the first reasource in @which that is found in the
                   11320: #     resource hash.
                   11321: #  Exceptional Conditions:
                   11322: #     If the $type passed in is not valid (not the string 'course' or 
                   11323: #     'user', an undefined  reference is returned.
                   11324: #     If none of the resources are found, an undef is returned
1.624     albertel 11325: sub resdata {
1.1301    raeburn  11326:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11327:         $modifier,$what,@which)=@_;
1.624     albertel 11328:     my $result;
                   11329:     if ($type eq 'course') {
                   11330: 	$result=&get_courseresdata($name,$domain);
                   11331:     } elsif ($type eq 'user') {
                   11332: 	$result=&get_userresdata($name,$domain);
                   11333:     }
                   11334:     if (!ref($result)) { return $result; }    
1.251     albertel 11335:     foreach my $item (@which) {
1.1301    raeburn  11336:         if ($item->[1] eq 'course') {
                   11337:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11338:                 unless ($$recursed) {
1.1302    raeburn  11339:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11340:                     $$recursed = 1;
                   11341:                 }
                   11342:                 foreach my $item (@${recurseup}) {
                   11343:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11344:                     last if (defined($result->{$norecursechk}));
                   11345:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11346:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11347:                 }
                   11348:             }
                   11349:         }
                   11350:         if (defined($result->{$item->[0]})) {
1.927     albertel 11351: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11352: 	}
1.250     albertel 11353:     }
1.291     albertel 11354:     return undef;
1.200     www      11355: }
                   11356: 
1.1360    raeburn  11357: sub get_domain_lti {
                   11358:     my ($cdom,$context) = @_;
                   11359:     my ($name,%lti);
                   11360:     if ($context eq 'consumer') {
                   11361:         $name = 'ltitools';
                   11362:     } elsif ($context eq 'provider') {
                   11363:         $name = 'lti';
                   11364:     } else {
                   11365:         return %lti;
                   11366:     }
                   11367:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11368:     if (defined($cached)) {
                   11369:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11370:             %lti = %{$result};
1.1298    raeburn  11371:         }
                   11372:     } else {
1.1360    raeburn  11373:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11374:         if (ref($domconfig{$name}) eq 'HASH') {
                   11375:             %lti = %{$domconfig{$name}};
                   11376:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11377:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11378:                 foreach my $id (keys(%lti)) {
                   11379:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11380:                         foreach my $item ('key','secret') {
1.1360    raeburn  11381:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11382:                         }
                   11383:                     }
                   11384:                 }
                   11385:             }
1.1298    raeburn  11386:         }
                   11387:         my $cachetime = 24*60*60;
1.1360    raeburn  11388:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11389:     }
1.1360    raeburn  11390:     return %lti;
1.1298    raeburn  11391: }
                   11392: 
1.1236    raeburn  11393: sub get_numsuppfiles {
                   11394:     my ($cnum,$cdom,$ignorecache)=@_;
                   11395:     my $hashid=$cnum.':'.$cdom;
                   11396:     my ($suppcount,$cached);
                   11397:     unless ($ignorecache) {
                   11398:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11399:     }
                   11400:     unless (defined($cached)) {
                   11401:         my $chome=&homeserver($cnum,$cdom);
                   11402:         unless ($chome eq 'no_host') {
1.1366    raeburn  11403:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11404:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11405:             ($suppcount,$supptools,$errors) =
                   11406:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11407:                                                          $supptools,$errors);
1.1236    raeburn  11408:         }
                   11409:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11410:     }
                   11411:     return $suppcount;
                   11412: }
                   11413: 
1.379     matthew  11414: #
                   11415: # EXT resource caching routines
                   11416: #
                   11417: 
1.1302    raeburn  11418: {
                   11419: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11420: #
                   11421: # The course for which we cache
                   11422: my $cachedmapkey='';
                   11423: # The cached recursive maps for this course
                   11424: my %cachedmaps=();
                   11425: # When this was last done
                   11426: my $cachedmaptime='';
                   11427: 
1.379     matthew  11428: sub clear_EXT_cache_status {
1.383     albertel 11429:     &delenv('cache.EXT.');
1.379     matthew  11430: }
                   11431: 
                   11432: sub EXT_cache_status {
                   11433:     my ($target_domain,$target_user) = @_;
1.383     albertel 11434:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11435:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11436:         # We know already the user has no data
                   11437:         return 1;
                   11438:     } else {
                   11439:         return 0;
                   11440:     }
                   11441: }
                   11442: 
                   11443: sub EXT_cache_set {
                   11444:     my ($target_domain,$target_user) = @_;
1.383     albertel 11445:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11446:     #&appenv({$cachename => time});
1.379     matthew  11447: }
                   11448: 
1.28      www      11449: # --------------------------------------------------------- Value of a Variable
1.58      www      11450: sub EXT {
1.715     albertel 11451: 
1.1228    raeburn  11452:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11453:     unless ($varname) { return ''; }
1.218     albertel 11454:     #get real user name/domain, courseid and symb
                   11455:     my $courseid;
1.359     albertel 11456:     my $publicuser;
1.427     www      11457:     if ($symbparm) {
                   11458: 	$symbparm=&get_symb_from_alias($symbparm);
                   11459:     }
1.218     albertel 11460:     if (!($uname && $udom)) {
1.790     albertel 11461:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11462:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11463:     } else {
1.620     albertel 11464: 	$courseid=$env{'request.course.id'};
1.218     albertel 11465:     }
1.48      www      11466:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11467:     my $rest;
1.320     albertel 11468:     if (defined($therest[0])) {
1.48      www      11469:        $rest=join('.',@therest);
                   11470:     } else {
                   11471:        $rest='';
                   11472:     }
1.320     albertel 11473: 
1.57      www      11474:     my $qualifierrest=$qualifier;
                   11475:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11476:     my $spacequalifierrest=$space;
                   11477:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11478:     if ($realm eq 'user') {
1.48      www      11479: # --------------------------------------------------------------- user.resource
                   11480: 	if ($space eq 'resource') {
1.651     albertel 11481: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11482: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11483: 		 &&
1.744     albertel 11484: 		 ($symbparm eq &symbread()) ) {	
                   11485: 		# if we are in the middle of processing the resource the
                   11486: 		# get the value we are planning on committing
                   11487:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11488:                     return $Apache::lonhomework::results{$qualifierrest};
                   11489:                 } else {
                   11490:                     return $Apache::lonhomework::history{$qualifierrest};
                   11491:                 }
1.335     albertel 11492: 	    } else {
1.359     albertel 11493: 		my %restored;
1.620     albertel 11494: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11495: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11496: 		} else {
                   11497: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11498: 		}
1.335     albertel 11499: 		return $restored{$qualifierrest};
                   11500: 	    }
1.48      www      11501: # ----------------------------------------------------------------- user.access
                   11502:         } elsif ($space eq 'access') {
1.218     albertel 11503: 	    # FIXME - not supporting calls for a specific user
1.48      www      11504:             return &allowed($qualifier,$rest);
                   11505: # ------------------------------------------ user.preferences, user.environment
                   11506:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11507: 	    if (($uname eq $env{'user.name'}) &&
                   11508: 		($udom eq $env{'user.domain'})) {
                   11509: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11510: 	    } else {
1.359     albertel 11511: 		my %returnhash;
                   11512: 		if (!$publicuser) {
                   11513: 		    %returnhash=&userenvironment($udom,$uname,
                   11514: 						 $qualifierrest);
                   11515: 		}
1.218     albertel 11516: 		return $returnhash{$qualifierrest};
                   11517: 	    }
1.48      www      11518: # ----------------------------------------------------------------- user.course
                   11519:         } elsif ($space eq 'course') {
1.218     albertel 11520: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11521:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11522: # ------------------------------------------------------------------- user.role
                   11523:         } elsif ($space eq 'role') {
1.218     albertel 11524: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11525:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11526:             if ($qualifier eq 'value') {
                   11527: 		return $role;
                   11528:             } elsif ($qualifier eq 'extent') {
                   11529:                 return $where;
                   11530:             }
                   11531: # ----------------------------------------------------------------- user.domain
                   11532:         } elsif ($space eq 'domain') {
1.218     albertel 11533:             return $udom;
1.48      www      11534: # ------------------------------------------------------------------- user.name
                   11535:         } elsif ($space eq 'name') {
1.218     albertel 11536:             return $uname;
1.48      www      11537: # ---------------------------------------------------- Any other user namespace
1.29      www      11538:         } else {
1.359     albertel 11539: 	    my %reply;
                   11540: 	    if (!$publicuser) {
                   11541: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11542: 	    }
                   11543: 	    return $reply{$qualifierrest};
1.48      www      11544:         }
1.236     www      11545:     } elsif ($realm eq 'query') {
                   11546: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11547:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11548: 						[$spacequalifierrest]);
1.620     albertel 11549: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11550:    } elsif ($realm eq 'request') {
1.48      www      11551: # ------------------------------------------------------------- request.browser
                   11552:         if ($space eq 'browser') {
1.1145    bisitz   11553:             return $env{'browser.'.$qualifier};
1.57      www      11554: # ------------------------------------------------------------ request.filename
                   11555:         } else {
1.620     albertel 11556:             return $env{'request.'.$spacequalifierrest};
1.29      www      11557:         }
1.28      www      11558:     } elsif ($realm eq 'course') {
1.48      www      11559: # ---------------------------------------------------------- course.description
1.620     albertel 11560:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11561:     } elsif ($realm eq 'resource') {
1.165     www      11562: 
1.620     albertel 11563: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11564: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11565: 	}
1.693     albertel 11566: 
1.1232    raeburn  11567:         if ($qualifier eq '') {
                   11568: 	    if ($space eq 'title') {
                   11569: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11570: 	        return &gettitle($symbparm);
                   11571: 	    }
1.693     albertel 11572: 	
1.1232    raeburn  11573: 	    if ($space eq 'map') {
                   11574: 	        my ($map) = &decode_symb($symbparm);
                   11575: 	        return &symbread($map);
                   11576: 	    }
                   11577:             if ($space eq 'maptitle') {
                   11578:                 my ($map) = &decode_symb($symbparm);
                   11579:                 return &gettitle($map);
                   11580:             }
                   11581: 	    if ($space eq 'filename') {
                   11582: 	        if ($symbparm) {
                   11583: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11584: 	        }
                   11585: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11586: 	    }
1.1232    raeburn  11587: 
1.1233    raeburn  11588:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11589:                 if ($space eq 'visibleparts') {
                   11590:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11591:                     my $item;
                   11592:                     if (ref($navmap)) {
                   11593:                         my $res = $navmap->getBySymb($symbparm);
                   11594:                         my $parts = $res->parts();
                   11595:                         if (ref($parts) eq 'ARRAY') {
                   11596:                             $item = join(',',@{$parts});
                   11597:                         }
                   11598:                         undef($navmap);
1.1232    raeburn  11599:                     }
1.1233    raeburn  11600:                     return $item;
1.1232    raeburn  11601:                 }
                   11602:             }
                   11603:         }
1.693     albertel 11604: 
1.1301    raeburn  11605: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11606: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11607:         if (($courseid eq '') && ($cid)) {
                   11608:             $courseid = $cid;
                   11609:         }
                   11610: 	if (($symbparm && $courseid) && 
                   11611: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11612: 
1.218     albertel 11613: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11614: 
1.60      www      11615: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11616: 	    my $symbp=$symbparm;
1.1301    raeburn  11617: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11618: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11619:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11620: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11621: 	    if (($env{'user.name'} eq $uname) &&
                   11622: 		($env{'user.domain'} eq $udom)) {
                   11623: 		$section=$env{'request.course.sec'};
1.733     raeburn  11624:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11625:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11626: 	    } else {
1.539     albertel 11627: 		if (! defined($usection)) {
1.551     albertel 11628: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11629: 		} else {
                   11630: 		    $section = $usection;
                   11631: 		}
1.733     raeburn  11632:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11633: 	    }
                   11634: 
                   11635: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11636: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11637:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11638: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11639: 
1.593     albertel 11640: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11641: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11642:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11643: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11644: 
1.60      www      11645: # ----------------------------------------------------------- first, check user
1.624     albertel 11646: 
1.1301    raeburn  11647: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11648:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11649: 				       ([$courselevelr,'resource'],
                   11650: 					[$courselevelm,'map'     ],
1.1301    raeburn  11651:                                         [$courseleveli,'map'     ],
1.927     albertel 11652: 					[$courselevel, 'course'  ]));
1.931     albertel 11653: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11654: 
1.594     albertel 11655: # ------------------------------------------------ second, check some of course
1.684     raeburn  11656:             my $coursereply;
1.691     raeburn  11657:             if (@groups > 0) {
                   11658:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11659:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11660:                                        $mapp,\$recursed,\@recurseup);
                   11661:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11662:             }
1.96      www      11663: 
1.684     raeburn  11664: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11665: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11666: 				  'course',$mapp,\$recursed,\@recurseup,
                   11667:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11668: 				  ([$seclevelr,   'resource'],
                   11669: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11670:                                    [$secleveli,   'map'     ],
1.927     albertel 11671: 				   [$seclevel,    'course'  ],
                   11672: 				   [$courselevelr,'resource']));
                   11673: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11674: 
1.60      www      11675: # ------------------------------------------------------ third, check map parms
1.218     albertel 11676: 	    my %parmhash=();
                   11677: 	    my $thisparm='';
                   11678: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11679: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11680: 		    &GDBM_READER(),0640)) {
1.218     albertel 11681: 		$thisparm=$parmhash{$symbparm};
                   11682: 		untie(%parmhash);
                   11683: 	    }
1.927     albertel 11684: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11685: 	}
1.594     albertel 11686: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11687:  
                   11688:         my $what = $spacequalifierrest;
                   11689: 	$what=~s/\./\_/;
1.282     albertel 11690: 	my $filename;
                   11691: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11692: 	if ($symbparm) {
1.409     www      11693: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11694: 	} else {
1.620     albertel 11695: 	    $filename=$env{'request.filename'};
1.282     albertel 11696: 	}
1.1362    raeburn  11697:         my $toolsymb;
                   11698:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11699:             $toolsymb = $symbparm;
                   11700:         }
                   11701: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11702: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11703: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11704: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11705: 
1.1301    raeburn  11706: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11707: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11708: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11709: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11710: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11711: 				     'course',$mapp,\$recursed,\@recurseup,
                   11712:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11713: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11714:                                       [$courseleveli,'map'   ],
1.927     albertel 11715: 				      [$courselevel, 'course']));
                   11716: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11717: 	}
1.145     www      11718: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11719: 	unless ($space eq '0') {
1.336     albertel 11720: 	    my @parts=split(/_/,$space);
                   11721: 	    my $id=pop(@parts);
                   11722: 	    my $part=join('_',@parts);
                   11723: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11724: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11725: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11726: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11727: 	}
1.395     albertel 11728: 	if ($recurse) { return undef; }
1.1362    raeburn  11729: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11730: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11731: # ---------------------------------------------------- Any other user namespace
                   11732:     } elsif ($realm eq 'environment') {
                   11733: # ----------------------------------------------------------------- environment
1.620     albertel 11734: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11735: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11736: 	} else {
1.770     albertel 11737: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11738: 		return '';
                   11739: 	    }
1.219     albertel 11740: 	    my %returnhash=&userenvironment($udom,$uname,
                   11741: 					    $spacequalifierrest);
                   11742: 	    return $returnhash{$spacequalifierrest};
                   11743: 	}
1.28      www      11744:     } elsif ($realm eq 'system') {
1.48      www      11745: # ----------------------------------------------------------------- system.time
                   11746: 	if ($space eq 'time') {
                   11747: 	    return time;
                   11748:         }
1.696     albertel 11749:     } elsif ($realm eq 'server') {
                   11750: # ----------------------------------------------------------------- system.time
                   11751: 	if ($space eq 'name') {
                   11752: 	    return $ENV{'SERVER_NAME'};
                   11753:         }
1.28      www      11754:     }
1.48      www      11755:     return '';
1.61      www      11756: }
                   11757: 
1.927     albertel 11758: sub get_reply {
                   11759:     my ($reply_value) = @_;
1.940     raeburn  11760:     if (ref($reply_value) eq 'ARRAY') {
                   11761:         if (wantarray) {
                   11762: 	    return @$reply_value;
                   11763:         }
                   11764:         return $reply_value->[0];
                   11765:     } else {
                   11766:         return $reply_value;
1.927     albertel 11767:     }
                   11768: }
                   11769: 
1.691     raeburn  11770: sub check_group_parms {
1.1301    raeburn  11771:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11772:         $recursed,$recurseupref) = @_;
                   11773:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11774:                   [$what,'course']);
                   11775:     my $coursereply;
1.691     raeburn  11776:     foreach my $group (@{$groups}) {
1.1301    raeburn  11777:         my @groupitems = ();
1.691     raeburn  11778:         foreach my $level (@levels) {
1.927     albertel 11779:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11780:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11781:         }
1.1301    raeburn  11782:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11783:                                    $env{'course.'.$courseid.'.domain'},
                   11784:                                    'course',$mapp,$recursed,$recurseupref,
                   11785:                                    $courseid,'.['.$group.'].',$what,
                   11786:                                    @groupitems);
                   11787:         last if (defined($coursereply));
1.691     raeburn  11788:     }
                   11789:     return $coursereply;
                   11790: }
                   11791: 
1.1301    raeburn  11792: sub get_map_hierarchy {
1.1302    raeburn  11793:     my ($mapname,$courseid) = @_;
                   11794:     my @recurseup = ();
1.1301    raeburn  11795:     if ($mapname) {
1.1302    raeburn  11796:         if (($cachedmapkey eq $courseid) &&
                   11797:             (abs($cachedmaptime-time)<5)) {
                   11798:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11799:                 return @{$cachedmaps{$mapname}};
                   11800:             }
                   11801:         }
1.1301    raeburn  11802:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11803:         if (ref($navmap)) {
                   11804:             @recurseup = $navmap->recurseup_maps($mapname);
                   11805:             undef($navmap);
1.1302    raeburn  11806:             $cachedmaps{$mapname} = \@recurseup;
                   11807:             $cachedmaptime=time;
                   11808:             $cachedmapkey=$courseid;
1.1301    raeburn  11809:         }
                   11810:     }
                   11811:     return @recurseup;
                   11812: }
                   11813: 
1.1302    raeburn  11814: }
                   11815: 
1.691     raeburn  11816: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11817:     my ($courseid,@groups) = @_;
                   11818:     @groups = sort(@groups);
1.691     raeburn  11819:     return @groups;
                   11820: }
                   11821: 
1.395     albertel 11822: sub packages_tab_default {
1.1362    raeburn  11823:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11824:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11825: 
                   11826:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11827:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11828: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11829: 	if ($pack_type eq 'default') {
                   11830: 	    $do_default=1;
                   11831: 	} elsif ($pack_type eq 'extension') {
                   11832: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11833: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11834: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11835: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11836: 	}
                   11837:     }
                   11838:     # first look for a package that matches the requested part id
                   11839:     foreach my $package (@specifics) {
                   11840: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11841: 	next if ($pack_part ne $part);
                   11842: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11843: 	    return $packagetab{"$pack_type&$name&default"};
                   11844: 	}
                   11845:     }
                   11846:     # look for any possible matching non extension_ package
                   11847:     foreach my $package (@specifics) {
                   11848: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11849: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11850: 	    return $packagetab{"$pack_type&$name&default"};
                   11851: 	}
1.585     albertel 11852: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11853: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11854: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11855: 	}
                   11856:     }
1.738     albertel 11857:     # look for any posible extension_ match
                   11858:     foreach my $package (@extension) {
                   11859: 	my ($package,$pack_type)=@{$package};
                   11860: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11861: 	    return $packagetab{"$pack_type&$name&default"};
                   11862: 	}
                   11863: 	if (defined($packagetab{$package."&$name&default"})) {
                   11864: 	    return $packagetab{$package."&$name&default"};
                   11865: 	}
                   11866:     }
                   11867:     # look for a global default setting
                   11868:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11869: 	return $packagetab{"default&$name&default"};
                   11870:     }
1.395     albertel 11871:     return undef;
                   11872: }
                   11873: 
1.334     albertel 11874: sub add_prefix_and_part {
                   11875:     my ($prefix,$part)=@_;
                   11876:     my $keyroot;
                   11877:     if (defined($prefix) && $prefix !~ /^__/) {
                   11878: 	# prefix that has a part already
                   11879: 	$keyroot=$prefix;
                   11880:     } elsif (defined($prefix)) {
                   11881: 	# prefix that is missing a part
                   11882: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11883:     } else {
                   11884: 	# no prefix at all
                   11885: 	if (defined($part)) { $keyroot='_'.$part; }
                   11886:     }
                   11887:     return $keyroot;
                   11888: }
                   11889: 
1.71      www      11890: # ---------------------------------------------------------------- Get metadata
                   11891: 
1.599     albertel 11892: my %metaentry;
1.1070    www      11893: my %importedpartids;
1.1369    raeburn  11894: my %importedrespids;
1.71      www      11895: sub metadata {
1.1362    raeburn  11896:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11897:     $uri=&declutter($uri);
1.288     albertel 11898:     # if it is a non metadata possible uri return quickly
1.529     albertel 11899:     if (($uri eq '') || 
                   11900: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11901: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11902:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11903: 	return undef;
                   11904:     }
1.1261    raeburn  11905:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11906: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11907: 	return undef;
1.288     albertel 11908:     }
1.73      www      11909:     my $filename=$uri;
                   11910:     $uri=~s/\.meta$//;
1.172     www      11911: #
                   11912: # Is the metadata already cached?
1.177     www      11913: # Look at timestamp of caching
1.172     www      11914: # Everything is cached by the main uri, libraries are never directly cached
                   11915: #
1.428     albertel 11916:     if (!defined($liburi)) {
1.599     albertel 11917: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11918: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11919:     }
1.1362    raeburn  11920: 
                   11921: #
                   11922: # If the uri is for an external tool the file from
                   11923: # which metadata should be retrieved depends on whether
                   11924: # the tool had been configured to be gradable (set in the Course
                   11925: # Editor or Resource Editor).
                   11926: #
                   11927: # If a valid symb has been included as the third arg in the call
                   11928: # to &metadata() that can be used to retrieve the value of
                   11929: # parameter_0_gradable set for the resource, and included in the
                   11930: # uploaded map containing the tool. The value is retrieved via
                   11931: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11932: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11933: # is retrieved via &get().
                   11934: #
                   11935: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11936: # hiddenresource and encrypturl (during course initialization)
                   11937: # the map-level parameter for resource.0.gradable included in the 
                   11938: # uploaded map containing the tool will not yet have been stored
                   11939: # in the user_course_parms.db file for the user's session, so in 
                   11940: # this case fall back to retrieving gradable status from the
                   11941: # exttool_$marker.db file.
1.1362    raeburn  11942: #
                   11943: # In order to avoid an infinite loop, &metadata() will return
                   11944: # before a call to &EXT(), if the uri is for an external tool
                   11945: # and the $what for which metadata is being requested is
                   11946: # parameter_0_gradable or 0_gradable.
                   11947: #
                   11948: 
                   11949:     if ($uri =~ /ext\.tool$/) {
                   11950:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11951:             return;
                   11952:         } else {
                   11953:             my ($checked,$use_passback);
                   11954:             if ($toolsymb ne '') {
                   11955:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11956:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11957:                     $checked = 1;
                   11958:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11959:                         $use_passback = 1;
                   11960:                     }
                   11961:                 }
                   11962:             }
                   11963:             unless ($checked) {
                   11964:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11965:                 $marker=~s/\D//g;
1.1363    raeburn  11966:                 if ($marker) {
1.1362    raeburn  11967:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11968:                     $use_passback = $toolsettings{'gradable'};
                   11969:                 }
                   11970:             }
                   11971:             if ($use_passback) {
                   11972:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11973:             } else {
                   11974:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11975:             }
                   11976:         }
                   11977:     }
                   11978: 
1.428     albertel 11979:     {
1.1069    www      11980: # Imported parts would go here
1.1369    raeburn  11981:         my @origfiletagids=();
1.1069    www      11982:         my $importedparts=0;
1.1369    raeburn  11983: 
                   11984: # Imported responseids would go here
                   11985:         my $importedresponses=0;
1.172     www      11986: #
                   11987: # Is this a recursive call for a library?
                   11988: #
1.599     albertel 11989: #	if (! exists($metacache{$uri})) {
                   11990: #	    $metacache{$uri}={};
                   11991: #	}
1.924     albertel 11992: 	my $cachetime = 60*60;
1.171     www      11993:         if ($liburi) {
                   11994: 	    $liburi=&declutter($liburi);
                   11995:             $filename=$liburi;
1.401     bowersj2 11996:         } else {
1.599     albertel 11997: 	    &devalidate_cache_new('meta',$uri);
                   11998: 	    undef(%metaentry);
1.401     bowersj2 11999: 	}
1.140     www      12000:         my %metathesekeys=();
1.73      www      12001:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12002: 	my $metastring;
1.1140    www      12003: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12004: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12005: 	    $metastring = 
1.929     albertel 12006: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12007: 					  ('grade_target' => 'meta'));
                   12008: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12009: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12010:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12011: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12012: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12013: 	    $metastring=&getfile($file);
1.489     albertel 12014: 	}
1.208     albertel 12015:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12016:         my $token;
1.140     www      12017:         undef %metathesekeys;
1.71      www      12018:         while ($token=$parser->get_token) {
1.339     albertel 12019: 	    if ($token->[0] eq 'S') {
                   12020: 		if (defined($token->[2]->{'package'})) {
1.172     www      12021: #
                   12022: # This is a package - get package info
                   12023: #
1.339     albertel 12024: 		    my $package=$token->[2]->{'package'};
                   12025: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12026: 		    if (defined($token->[2]->{'id'})) { 
                   12027: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12028: 		    }
1.599     albertel 12029: 		    if ($metaentry{':packages'}) {
                   12030: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12031: 		    } else {
1.599     albertel 12032: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12033: 		    }
1.736     albertel 12034: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12035: 			my $part=$keyroot;
                   12036: 			$part=~s/^\_//;
1.736     albertel 12037: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12038: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12039: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12040: 			    # ignore package.tab specified default values
                   12041:                             # here &package_tab_default() will fetch those
                   12042: 			    if ($subp eq 'default') { next; }
1.736     albertel 12043: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12044: 			    my $unikey;
                   12045: 			    if ($pack =~ /_0$/) {
                   12046: 				$unikey='parameter_0_'.$name;
                   12047: 				$part=0;
                   12048: 			    } else {
                   12049: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12050: 			    }
1.339     albertel 12051: 			    if ($subp eq 'display') {
                   12052: 				$value.=' [Part: '.$part.']';
                   12053: 			    }
1.599     albertel 12054: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12055: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12056: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12057: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12058: 			    }
1.599     albertel 12059: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12060: 				$metaentry{':'.$unikey}=
                   12061: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12062: 			    }
1.339     albertel 12063: 			}
                   12064: 		    }
                   12065: 		} else {
1.172     www      12066: #
                   12067: # This is not a package - some other kind of start tag
1.339     albertel 12068: #
                   12069: 		    my $entry=$token->[1];
1.1068    www      12070: 		    my $unikey='';
1.175     www      12071: 
1.339     albertel 12072: 		    if ($entry eq 'import') {
1.175     www      12073: #
                   12074: # Importing a library here
1.339     albertel 12075: #
1.1067    www      12076:                         my $location=$parser->get_text('/import');
                   12077:                         my $dir=$filename;
                   12078:                         $dir=~s|[^/]*$||;
                   12079:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12080: 
                   12081:                         my $importid=$token->[2]->{'id'};
1.1068    www      12082:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12083: #
                   12084: # Check metadata for imported file to
                   12085: # see if it contained response items
                   12086: #
1.1372    raeburn  12087:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12088:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12089:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12090:                                                            $depthcount+1));
                   12091:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12092:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12093:                                                              undef,$depthcount+1);
                   12094:                             if ($libresponseorder ne '') {
                   12095:                                 if ($#origfiletagids<0) {
                   12096:                                     undef(%importedrespids);
                   12097:                                     undef(%importedpartids);
                   12098:                                 }
1.1373    raeburn  12099:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12100:                                 if (@respids) {
                   12101:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12102:                                 }
                   12103:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12104:                                     $importedresponses = 1;
1.1369    raeburn  12105: # We need to get the original file and the imported file to get the response order correct
                   12106: # Load and inspect original file
1.1372    raeburn  12107:                                     if ($#origfiletagids<0) {
                   12108:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12109:                                         $origfile=&getfile($origfilelocation);
                   12110:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12111:                                     }
1.1369    raeburn  12112:                                 }
                   12113:                             }
                   12114:                         }
1.1370    raeburn  12115: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12116: # hash populated for imported library file
                   12117:                         %metaentry = %currmetaentry;
                   12118:                         undef(%currmetaentry);
1.1374    raeburn  12119:                         if ($importmode eq 'part') {
1.1068    www      12120: # Import as part(s)
1.1069    www      12121:                            $importedparts=1;
                   12122: # We need to get the original file and the imported file to get the part order correct
                   12123: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12124: # Load and inspect original file if we didn't do that already
                   12125:                            if ($#origfiletagids<0) {
                   12126:                                undef(%importedrespids);
                   12127:                                undef(%importedpartids);
                   12128:                                if ($origfile eq '') {
                   12129:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12130:                                    $origfile=&getfile($origfilelocation);
                   12131:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12132:                                }
1.1070    www      12133:                            }
1.1372    raeburn  12134:                            my @impfilepartids;
                   12135: # If <partorder> tag is included in metadata for the imported file
                   12136: # get the parts in the imported file from that.
                   12137:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12138:                                %currmetaentry = %metaentry;
                   12139:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12140:                                                             $depthcount+1);
                   12141:                                %metaentry = %currmetaentry;
                   12142:                                undef(%currmetaentry);
                   12143:                                if ($libpartorder ne '') {
                   12144:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12145:                                }
                   12146:                            } else {
                   12147: # If no <partorder> tag available, load and inspect imported file
                   12148:                                my $impfile=&getfile($location);
                   12149:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12150:                            }
1.1069    www      12151:                            if ($#impfilepartids>=0) {
                   12152: # This problem had parts
1.1070    www      12153:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12154:                            } else {
                   12155: # Importing by turning a single problem into a problem part
                   12156: # It gets the import-tags ID as part-ID
                   12157:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12158:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12159:                            }
1.1068    www      12160:                         } else {
1.1374    raeburn  12161: # Import as problem or as normal import
                   12162:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12163:                             unless ($importmode eq 'problem') {
1.1068    www      12164: # Normal import
1.1374    raeburn  12165:                                 if (defined($token->[2]->{'id'})) {
                   12166:                                     $unikey.='_'.$token->[2]->{'id'};
                   12167:                                 }
                   12168:                             }
                   12169: # Check metadata for imported file to
                   12170: # see if it contained parts
                   12171:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12172:                                 %currmetaentry = %metaentry;
                   12173:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12174:                                                              $depthcount+1);
                   12175:                                 %metaentry = %currmetaentry;
                   12176:                                 undef(%currmetaentry);
                   12177:                                 if ($libpartorder ne '') {
                   12178:                                     $importedparts = 1;
                   12179:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12180:                                 }
                   12181:                             }
1.1067    www      12182:                         }
1.339     albertel 12183: 			if ($depthcount<20) {
1.736     albertel 12184: 			    my $metadata = 
1.1362    raeburn  12185: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12186: 					  $depthcount+1);
                   12187: 			    foreach my $meta (split(',',$metadata)) {
                   12188: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12189: 				$metathesekeys{$meta}=1;
1.339     albertel 12190: 			    }
1.1068    www      12191:                         }
1.1067    www      12192: 		    } else {
                   12193: #
                   12194: # Not importing, some other kind of non-package, non-library start tag
                   12195: # 
                   12196:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12197:                         if (defined($token->[2]->{'id'})) {
                   12198:                             $unikey.='_'.$token->[2]->{'id'};
                   12199:                         }
1.339     albertel 12200: 			if (defined($token->[2]->{'name'})) { 
                   12201: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12202: 			}
                   12203: 			$metathesekeys{$unikey}=1;
1.736     albertel 12204: 			foreach my $param (@{$token->[3]}) {
                   12205: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12206: 				$token->[2]->{$param};
1.339     albertel 12207: 			}
                   12208: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12209: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12210: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12211: 		 # only ws inside the tag, and not in default, so use default
                   12212: 		 # as value
1.599     albertel 12213: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12214: 			} elsif ( $internaltext =~ /\S/ ) {
                   12215: 		  # something interesting inside the tag
                   12216: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12217: 			} else {
1.908     albertel 12218: 		  # no interesting values, don't set a default
1.339     albertel 12219: 			}
1.172     www      12220: # end of not-a-package not-a-library import
1.339     albertel 12221: 		    }
1.172     www      12222: # end of not-a-package start tag
1.339     albertel 12223: 		}
1.172     www      12224: # the next is the end of "start tag"
1.339     albertel 12225: 	    }
                   12226: 	}
1.483     albertel 12227: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12228: 	$extension = lc($extension);
                   12229: 	if ($extension eq 'htm') { $extension='html'; }
                   12230: 
1.737     albertel 12231: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12232: 	    #no specific packages #how's our extension
                   12233: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12234: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12235: 					 \%metathesekeys);
                   12236: 	}
1.883     albertel 12237: 
                   12238: 	if (!exists($metaentry{':packages'})
                   12239: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12240: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12241: 		#no specific packages well let's get default then
                   12242: 		if ($key!~/^default&/) { next; }
1.488     albertel 12243: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12244: 					     \%metathesekeys);
                   12245: 	    }
                   12246: 	}
1.338     www      12247: # are there custom rights to evaluate
1.599     albertel 12248: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12249: 
1.338     www      12250:     #
                   12251:     # Importing a rights file here
1.339     albertel 12252:     #
                   12253: 	    unless ($depthcount) {
1.599     albertel 12254: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12255: 		my $dir=$filename;
                   12256: 		$dir=~s|[^/]*$||;
                   12257: 		$location=&filelocation($dir,$location);
1.736     albertel 12258: 		my $rights_metadata =
1.1362    raeburn  12259: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12260: 			      $depthcount+1);
                   12261: 		foreach my $rights (split(',',$rights_metadata)) {
                   12262: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12263: 		    $metathesekeys{$rights}=1;
1.339     albertel 12264: 		}
                   12265: 	    }
                   12266: 	}
1.737     albertel 12267: 	# uniqifiy package listing
                   12268: 	my %seen;
                   12269: 	my @uniq_packages =
                   12270: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12271: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12272: 
1.1369    raeburn  12273:         if (($importedresponses) || ($importedparts)) {
                   12274:             if ($importedparts) {
1.1070    www      12275: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12276:                 $metaentry{':partorder'}='';
                   12277:                 $metathesekeys{'partorder'}=1;
                   12278:             }
                   12279:             if ($importedresponses) {
                   12280: # We had imported responses and need to rebuil responseorder
                   12281:                 $metaentry{':responseorder'}='';
                   12282:                 $metathesekeys{'responseorder'}=1;
                   12283:             }
                   12284:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12285:                 my $origid = $origfiletagids[$index+1];
                   12286:                 if ($origfiletagids[$index] eq 'part') {
                   12287: # Original part, part of the problem
                   12288:                     if ($importedparts) {
                   12289:                         $metaentry{':partorder'}.=','.$origid;
                   12290:                     }
                   12291:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12292:                     if ($importedparts) {
                   12293: # We have imported parts at this position
1.1373    raeburn  12294:                         if ($importedpartids{$origid} ne '') {
                   12295:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12296:                         }
1.1369    raeburn  12297:                     }
                   12298:                     if ($importedresponses) {
                   12299: # We have imported responses at this position
1.1373    raeburn  12300:                         if ($importedrespids{$origid} ne '') {
                   12301:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12302:                         }
                   12303:                     }
                   12304:                 } else {
                   12305: # Original response item, part of the problem
                   12306:                     if ($importedresponses) {
                   12307:                         $metaentry{':responseorder'}.=','.$origid;
                   12308:                     }
                   12309:                 }
                   12310:             }
                   12311:             if ($importedparts) {
                   12312:                 $metaentry{':partorder'}=~s/^\,//;
                   12313:             }
                   12314:             if ($importedresponses) {
                   12315:                 $metaentry{':responseorder'}=~s/^\,//;
                   12316:             }
1.1070    www      12317:         }
1.737     albertel 12318: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12319: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12320: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12321:         unless ($liburi) {
                   12322: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12323:         }
1.177     www      12324: # this is the end of "was not already recently cached
1.71      www      12325:     }
1.599     albertel 12326:     return $metaentry{':'.$what};
1.261     albertel 12327: }
                   12328: 
1.488     albertel 12329: sub metadata_create_package_def {
1.483     albertel 12330:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12331:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12332:     if ($subp eq 'default') { next; }
                   12333:     
1.599     albertel 12334:     if (defined($metaentry{':packages'})) {
                   12335: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12336:     } else {
1.599     albertel 12337: 	$metaentry{':packages'}=$package;
1.483     albertel 12338:     }
                   12339:     my $value=$packagetab{$key};
                   12340:     my $unikey;
                   12341:     $unikey='parameter_0_'.$name;
1.599     albertel 12342:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12343:     $$metathesekeys{$unikey}=1;
1.599     albertel 12344:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12345: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12346:     }
1.599     albertel 12347:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12348: 	$metaentry{':'.$unikey}=
                   12349: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12350:     }
                   12351: }
                   12352: 
1.261     albertel 12353: sub metadata_generate_part0 {
                   12354:     my ($metadata,$metacache,$uri) = @_;
                   12355:     my %allnames;
1.737     albertel 12356:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12357: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12358: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12359: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12360: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12361: 	    $allnames{$name}=$part;
                   12362: 	  }
                   12363: 	}
                   12364:     }
                   12365:     foreach my $name (keys(%allnames)) {
                   12366:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12367:       my $key=":parameter_0_$name";
1.261     albertel 12368:       $$metacache{"$key.part"}='0';
                   12369:       $$metacache{"$key.name"}=$name;
1.428     albertel 12370:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12371: 					   $allnames{$name}.'_'.$name.
                   12372: 					   '.type'};
1.428     albertel 12373:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12374: 			     '.display'};
1.644     www      12375:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12376:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12377:       $$metacache{"$key.display"}=$olddis;
                   12378:     }
1.71      www      12379: }
                   12380: 
1.764     albertel 12381: # ------------------------------------------------------ Devalidate title cache
                   12382: 
                   12383: sub devalidate_title_cache {
                   12384:     my ($url)=@_;
                   12385:     if (!$env{'request.course.id'}) { return; }
                   12386:     my $symb=&symbread($url);
                   12387:     if (!$symb) { return; }
                   12388:     my $key=$env{'request.course.id'}."\0".$symb;
                   12389:     &devalidate_cache_new('title',$key);
                   12390: }
                   12391: 
1.1014    droeschl 12392: # ------------------------------------------------- Get the title of a course
                   12393: 
                   12394: sub current_course_title {
                   12395:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12396: }
1.301     www      12397: # ------------------------------------------------- Get the title of a resource
                   12398: 
                   12399: sub gettitle {
                   12400:     my $urlsymb=shift;
                   12401:     my $symb=&symbread($urlsymb);
1.534     albertel 12402:     if ($symb) {
1.620     albertel 12403: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12404: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12405: 	if (defined($cached)) { 
                   12406: 	    return $result;
                   12407: 	}
1.534     albertel 12408: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12409: 	my $title='';
1.907     albertel 12410: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12411: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12412: 	} else {
                   12413: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12414: 		    &GDBM_READER(),0640)) {
                   12415: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12416: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12417: 		untie(%bighash);
                   12418: 	    }
1.534     albertel 12419: 	}
                   12420: 	$title=~s/\&colon\;/\:/gs;
                   12421: 	if ($title) {
1.1159    www      12422: # Remember both $symb and $title for dynamic metadata
                   12423:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12424:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12425: # Cache this title and then return it
1.599     albertel 12426: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12427: 	}
                   12428: 	$urlsymb=$url;
                   12429:     }
                   12430:     my $title=&metadata($urlsymb,'title');
                   12431:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12432:     return $title;
1.301     www      12433: }
1.613     albertel 12434: 
1.614     albertel 12435: sub get_slot {
                   12436:     my ($which,$cnum,$cdom)=@_;
                   12437:     if (!$cnum || !$cdom) {
1.790     albertel 12438: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12439: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12440: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12441:     }
1.703     albertel 12442:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12443:     my %slotinfo;
                   12444:     if (exists($remembered{$key})) {
                   12445: 	$slotinfo{$which} = $remembered{$key};
                   12446:     } else {
                   12447: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12448: 	&Apache::lonhomework::showhash(%slotinfo);
                   12449: 	my ($tmp)=keys(%slotinfo);
                   12450: 	if ($tmp=~/^error:/) { return (); }
                   12451: 	$remembered{$key} = $slotinfo{$which};
                   12452:     }
1.616     albertel 12453:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12454: 	return %{$slotinfo{$which}};
                   12455:     }
                   12456:     return $slotinfo{$which};
1.614     albertel 12457: }
1.1150    raeburn  12458: 
                   12459: sub get_reservable_slots {
                   12460:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12461:     my $now = time;
                   12462:     my $reservable_info;
                   12463:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12464:     if (exists($remembered{$key})) {
                   12465:         $reservable_info = $remembered{$key};
                   12466:     } else {
                   12467:         my %resv;
                   12468:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12469:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12470:         $reservable_info = \%resv;
                   12471:         $remembered{$key} = $reservable_info;
                   12472:     }
                   12473:     return $reservable_info;
                   12474: }
                   12475: 
                   12476: sub get_course_slots {
                   12477:     my ($cnum,$cdom) = @_;
                   12478:     my $hashid=$cnum.':'.$cdom;
                   12479:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12480:     if (defined($cached)) {
                   12481:         if (ref($result) eq 'HASH') {
                   12482:             return %{$result};
                   12483:         }
                   12484:     } else {
                   12485:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12486:         my ($tmp) = keys(%slots);
                   12487:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12488:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12489:             return %slots;
                   12490:         }
                   12491:     }
                   12492:     return;
                   12493: }
                   12494: 
                   12495: sub devalidate_slots_cache {
                   12496:     my ($cnum,$cdom)=@_;
                   12497:     my $hashid=$cnum.':'.$cdom;
                   12498:     &devalidate_cache_new('allslots',$hashid);
                   12499: }
                   12500: 
1.1181    raeburn  12501: sub get_coursechange {
                   12502:     my ($cdom,$cnum) = @_;
                   12503:     if ($cdom eq '' || $cnum eq '') {
                   12504:         return unless ($env{'request.course.id'});
                   12505:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12506:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12507:     }
                   12508:     my $hashid=$cdom.'_'.$cnum;
                   12509:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12510:     if ((defined($cached)) && ($change ne '')) {
                   12511:         return $change;
                   12512:     } else {
                   12513:         my %crshash;
                   12514:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12515:         if ($crshash{'internal.contentchange'} eq '') {
                   12516:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12517:             if ($change eq '') {
                   12518:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12519:                 $change = $crshash{'internal.created'};
                   12520:             }
                   12521:         } else {
                   12522:             $change = $crshash{'internal.contentchange'};
                   12523:         }
                   12524:         my $cachetime = 600;
                   12525:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12526:     }
                   12527:     return $change;
                   12528: }
                   12529: 
                   12530: sub devalidate_coursechange_cache {
                   12531:     my ($cnum,$cdom)=@_;
                   12532:     my $hashid=$cnum.':'.$cdom;
                   12533:     &devalidate_cache_new('crschange',$hashid);
                   12534: }
                   12535: 
1.31      www      12536: # ------------------------------------------------- Update symbolic store links
                   12537: 
                   12538: sub symblist {
                   12539:     my ($mapname,%newhash)=@_;
1.438     www      12540:     $mapname=&deversion(&declutter($mapname));
1.31      www      12541:     my %hash;
1.620     albertel 12542:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12543:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12544:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12545: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12546: 		next if ($url eq 'last_known'
                   12547: 			 && $env{'form.no_update_last_known'});
                   12548: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12549: 						    $newhash{$url}->[1],
                   12550: 						    $newhash{$url}->[0]);
1.191     harris41 12551:             }
1.31      www      12552:             if (untie(%hash)) {
                   12553: 		return 'ok';
                   12554:             }
                   12555:         }
                   12556:     }
                   12557:     return 'error';
1.212     www      12558: }
                   12559: 
                   12560: # --------------------------------------------------------------- Verify a symb
                   12561: 
                   12562: sub symbverify {
1.1190    raeburn  12563:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12564:     my $thisfn=$thisurl;
1.439     www      12565:     $thisfn=&declutter($thisfn);
1.215     www      12566: # direct jump to resource in page or to a sequence - will construct own symbs
                   12567:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12568: # check URL part
1.409     www      12569:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12570: 
1.431     www      12571:     unless ($url eq $thisfn) { return 0; }
1.213     www      12572: 
1.216     www      12573:     $symb=&symbclean($symb);
1.510     www      12574:     $thisurl=&deversion($thisurl);
1.439     www      12575:     $thisfn=&deversion($thisfn);
1.213     www      12576: 
                   12577:     my %bighash;
                   12578:     my $okay=0;
1.431     www      12579: 
1.620     albertel 12580:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12581:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12582:         my $noclutter;
1.1032    raeburn  12583:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12584:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12585:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12586:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12587:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12588:                 $noclutter = 1;
                   12589:             }
                   12590:         }
                   12591:         my $ids;
                   12592:         if ($noclutter) {
                   12593:             $ids=$bighash{'ids_'.$thisurl};
                   12594:         } else {
                   12595:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12596:         }
1.1102    raeburn  12597:         unless ($ids) {
                   12598:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12599:             $ids=$bighash{$idkey};
1.216     www      12600:         }
                   12601:         if ($ids) {
                   12602: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12603:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12604:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12605:             }
1.800     albertel 12606: 	    foreach my $id (split(/\,/,$ids)) {
                   12607: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12608:                if (
                   12609:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12610:    eq $symb) {
                   12611:                    if (ref($encstate)) {
                   12612:                        $$encstate = $bighash{'encrypted_'.$id};
                   12613:                    }
1.620     albertel 12614: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12615: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12616:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12617: 		       $okay=1;
1.1202    raeburn  12618:                        last;
1.582     albertel 12619: 		   }
                   12620: 	       }
1.216     www      12621: 	   }
                   12622:         }
1.213     www      12623: 	untie(%bighash);
                   12624:     }
                   12625:     return $okay;
1.31      www      12626: }
                   12627: 
1.210     www      12628: # --------------------------------------------------------------- Clean-up symb
                   12629: 
                   12630: sub symbclean {
                   12631:     my $symb=shift;
1.568     albertel 12632:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12633: # remove version from map
                   12634:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12635: 
1.210     www      12636: # remove version from URL
                   12637:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12638: 
1.507     www      12639: # remove wrapper
                   12640: 
1.510     www      12641:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12642:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12643:     return $symb;
1.409     www      12644: }
                   12645: 
                   12646: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12647: 
                   12648: sub encode_symb {
                   12649:     my ($map,$resid,$url)=@_;
                   12650:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12651: }
1.409     www      12652: 
                   12653: sub decode_symb {
1.568     albertel 12654:     my $symb=shift;
                   12655:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12656:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12657:     return (&fixversion($map),$resid,&fixversion($url));
                   12658: }
                   12659: 
                   12660: sub fixversion {
                   12661:     my $fn=shift;
1.609     banghart 12662:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12663:     my %bighash;
                   12664:     my $uri=&clutter($fn);
1.620     albertel 12665:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12666: # is this cached?
1.599     albertel 12667:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12668:     if (defined($cached)) { return $result; }
                   12669: # unfortunately not cached, or expired
1.620     albertel 12670:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12671: 	    &GDBM_READER(),0640)) {
                   12672:  	if ($bighash{'version_'.$uri}) {
                   12673:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12674:  	    unless (($version eq 'mostrecent') || 
                   12675: 		    ($version==&getversion($uri))) {
1.440     www      12676:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12677:  	    }
                   12678:  	}
                   12679:  	untie %bighash;
1.413     www      12680:     }
1.599     albertel 12681:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12682: }
                   12683: 
                   12684: sub deversion {
                   12685:     my $url=shift;
                   12686:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12687:     return $url;
1.210     www      12688: }
                   12689: 
1.31      www      12690: # ------------------------------------------------------ Return symb list entry
                   12691: 
                   12692: sub symbread {
1.1282    raeburn  12693:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12694:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12695:     if (defined($env{$cache_str})) {
                   12696:         if ($ignorecachednull) {
                   12697:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12698:         } else {
                   12699:             return $env{$cache_str};
                   12700:         }
                   12701:     }
1.242     www      12702: # no filename provided? try from environment
1.1265    raeburn  12703:     unless ($thisfn) {
1.620     albertel 12704:         if ($env{'request.symb'}) {
                   12705: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12706: 	}
1.620     albertel 12707: 	$thisfn=$env{'request.filename'};
1.44      www      12708:     }
1.569     albertel 12709:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12710: # is that filename actually a symb? Verify, clean, and return
                   12711:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12712: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12713: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12714: 	}
1.242     www      12715:     }
1.44      www      12716:     $thisfn=declutter($thisfn);
1.31      www      12717:     my %hash;
1.37      www      12718:     my %bighash;
                   12719:     my $syval='';
1.620     albertel 12720:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12721:         my $targetfn = $thisfn;
1.609     banghart 12722:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12723:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12724:         }
1.687     albertel 12725: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12726: 	    $targetfn=$1;
                   12727: 	}
1.620     albertel 12728:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12729:                       &GDBM_READER(),0640)) {
1.481     raeburn  12730: 	    $syval=$hash{$targetfn};
1.37      www      12731:             untie(%hash);
                   12732:         }
                   12733: # ---------------------------------------------------------- There was an entry
                   12734:         if ($syval) {
1.601     albertel 12735: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12736: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12737: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12738: 		    #return $env{$cache_str}='';
1.601     albertel 12739: 		#}    
                   12740: 		#$syval.=$1;
                   12741: 	    #}
1.37      www      12742:         } else {
                   12743: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12744:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12745:                             &GDBM_READER(),0640)) {
1.37      www      12746: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12747:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12748:               unless ($ids) { 
                   12749:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12750:               }
                   12751:               unless ($ids) {
                   12752: # alias?
                   12753: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12754:               }
1.37      www      12755:               if ($ids) {
                   12756: # ------------------------------------------------------------------- Has ID(s)
                   12757:                  my @possibilities=split(/\,/,$ids);
1.39      www      12758:                  if ($#possibilities==0) {
                   12759: # ----------------------------------------------- There is only one possibility
1.37      www      12760: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12761: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12762: 						    $resid,$thisfn);
1.1282    raeburn  12763:                      if (ref($possibles) eq 'HASH') {
                   12764:                          $possibles->{$syval} = 1;    
                   12765:                      }
                   12766:                      if ($checkforblock) {
                   12767:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12768:                          if (@blockers) {
                   12769:                              $syval = '';
                   12770:                              return;
                   12771:                          }
                   12772:                      }
                   12773:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12774: # ------------------------------------------ There is more than one possibility
                   12775:                      my $realpossible=0;
1.800     albertel 12776:                      foreach my $id (@possibilities) {
                   12777: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12778:                          my $canaccess;
                   12779:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12780:                              $canaccess = 1;
                   12781:                          } else { 
                   12782:                              $canaccess = &allowed('bre',$file);
                   12783:                          }
                   12784:                          if ($canaccess) {
                   12785:          		     my ($mapid,$resid)=split(/\./,$id);
                   12786:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12787:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12788: 						             $resid,$thisfn);
                   12789:                                  if (ref($possibles) eq 'HASH') {
                   12790:                                      $possibles->{$syval} = 1;
                   12791:                                  }
                   12792:                                  if ($checkforblock) {
                   12793:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12794:                                      unless (@blockers > 0) {
                   12795:                                          $syval = $poss_syval;
                   12796:                                          $realpossible++;
                   12797:                                      }
                   12798:                                  } else {
                   12799:                                      $syval = $poss_syval;
                   12800:                                      $realpossible++;
                   12801:                                  }
                   12802:                              }
1.39      www      12803: 			 }
1.191     harris41 12804:                      }
1.39      www      12805: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12806:                  } else {
                   12807:                      $syval='';
1.37      www      12808:                  }
                   12809: 	      }
1.1282    raeburn  12810:               untie(%bighash);
1.481     raeburn  12811:            }
1.31      www      12812:         }
1.62      www      12813:         if ($syval) {
1.620     albertel 12814: 	    return $env{$cache_str}=$syval;
1.62      www      12815:         }
1.31      www      12816:     }
1.949     raeburn  12817:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12818:     return $env{$cache_str}='';
1.31      www      12819: }
                   12820: 
                   12821: # ---------------------------------------------------------- Return random seed
                   12822: 
1.32      www      12823: sub numval {
                   12824:     my $txt=shift;
                   12825:     $txt=~tr/A-J/0-9/;
                   12826:     $txt=~tr/a-j/0-9/;
                   12827:     $txt=~tr/K-T/0-9/;
                   12828:     $txt=~tr/k-t/0-9/;
                   12829:     $txt=~tr/U-Z/0-5/;
                   12830:     $txt=~tr/u-z/0-5/;
                   12831:     $txt=~s/\D//g;
1.564     albertel 12832:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12833:     return int($txt);
1.368     albertel 12834: }
                   12835: 
1.484     albertel 12836: sub numval2 {
                   12837:     my $txt=shift;
                   12838:     $txt=~tr/A-J/0-9/;
                   12839:     $txt=~tr/a-j/0-9/;
                   12840:     $txt=~tr/K-T/0-9/;
                   12841:     $txt=~tr/k-t/0-9/;
                   12842:     $txt=~tr/U-Z/0-5/;
                   12843:     $txt=~tr/u-z/0-5/;
                   12844:     $txt=~s/\D//g;
                   12845:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12846:     my $total;
                   12847:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12848:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12849:     return int($total);
                   12850: }
                   12851: 
1.575     albertel 12852: sub numval3 {
                   12853:     use integer;
                   12854:     my $txt=shift;
                   12855:     $txt=~tr/A-J/0-9/;
                   12856:     $txt=~tr/a-j/0-9/;
                   12857:     $txt=~tr/K-T/0-9/;
                   12858:     $txt=~tr/k-t/0-9/;
                   12859:     $txt=~tr/U-Z/0-5/;
                   12860:     $txt=~tr/u-z/0-5/;
                   12861:     $txt=~s/\D//g;
                   12862:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12863:     my $total;
                   12864:     foreach my $val (@txts) { $total+=$val; }
                   12865:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12866:     return $total;
                   12867: }
                   12868: 
1.675     albertel 12869: sub digest {
                   12870:     my ($data)=@_;
                   12871:     my $digest=&Digest::MD5::md5($data);
                   12872:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12873:     my ($e,$f);
                   12874:     {
                   12875:         use integer;
                   12876:         $e=($a+$b);
                   12877:         $f=($c+$d);
                   12878:         if ($_64bit) {
                   12879:             $e=(($e<<32)>>32);
                   12880:             $f=(($f<<32)>>32);
                   12881:         }
                   12882:     }
                   12883:     if (wantarray) {
                   12884: 	return ($e,$f);
                   12885:     } else {
                   12886: 	my $g;
                   12887: 	{
                   12888: 	    use integer;
                   12889: 	    $g=($e+$f);
                   12890: 	    if ($_64bit) {
                   12891: 		$g=(($g<<32)>>32);
                   12892: 	    }
                   12893: 	}
                   12894: 	return $g;
                   12895:     }
                   12896: }
                   12897: 
1.368     albertel 12898: sub latest_rnd_algorithm_id {
1.675     albertel 12899:     return '64bit5';
1.366     albertel 12900: }
1.32      www      12901: 
1.503     albertel 12902: sub get_rand_alg {
                   12903:     my ($courseid)=@_;
1.790     albertel 12904:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12905:     if ($courseid) {
1.620     albertel 12906: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12907:     }
                   12908:     return &latest_rnd_algorithm_id();
                   12909: }
                   12910: 
1.562     albertel 12911: sub validCODE {
                   12912:     my ($CODE)=@_;
                   12913:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12914:     return 0;
                   12915: }
                   12916: 
1.491     albertel 12917: sub getCODE {
1.620     albertel 12918:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12919:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12920: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12921: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12922: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12923:     }
                   12924:     return undef;
                   12925: }
1.1133    foxr     12926: #
                   12927: #  Determines the random seed for a specific context:
                   12928: #
                   12929: # parameters:
                   12930: #   symb      - in course context the symb for the seed.
                   12931: #   course_id - The course id of the form domain_coursenum.
                   12932: #   domain    - Domain for the user.
                   12933: #   course    - Course for the user.
                   12934: #   cenv      - environment of the course.
                   12935: #
                   12936: # NOTE:
                   12937: #   All parameters are picked out of the environment if missing
                   12938: #   or not defined.
                   12939: #   If a symb cannot be determined the current time is used instead.
                   12940: #
                   12941: #  For a given well defined symb, courside, domain, username,
                   12942: #  and course environment, the seed is reproducible.
                   12943: #
1.31      www      12944: sub rndseed {
1.1133    foxr     12945:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12946:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12947:     if (!defined($symb)) {
1.366     albertel 12948: 	unless ($symb=$wsymb) { return time; }
                   12949:     }
1.1146    foxr     12950:     if (!defined $courseid) { 
                   12951: 	$courseid=$wcourseid; 
                   12952:     }
                   12953:     if (!defined $domain) { $domain=$wdomain; }
                   12954:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12955: 
                   12956:     my $which;
                   12957:     if (defined($cenv->{'rndseed'})) {
                   12958: 	$which = $cenv->{'rndseed'};
                   12959:     } else {
                   12960: 	$which =&get_rand_alg($courseid);
                   12961:     }
1.491     albertel 12962:     if (defined(&getCODE())) {
1.1133    foxr     12963: 
1.675     albertel 12964: 	if ($which eq '64bit5') {
                   12965: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12966: 	} elsif ($which eq '64bit4') {
1.575     albertel 12967: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12968: 	} else {
                   12969: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12970: 	}
1.675     albertel 12971:     } elsif ($which eq '64bit5') {
                   12972: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12973:     } elsif ($which eq '64bit4') {
                   12974: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12975:     } elsif ($which eq '64bit3') {
                   12976: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12977:     } elsif ($which eq '64bit2') {
                   12978: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12979:     } elsif ($which eq '64bit') {
                   12980: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12981:     }
                   12982:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12983: }
                   12984: 
                   12985: sub rndseed_32bit {
                   12986:     my ($symb,$courseid,$domain,$username)=@_;
                   12987:     {
                   12988: 	use integer;
                   12989: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12990: 	my $symbseed=numval($symb) << 22;
                   12991: 	my $namechck=unpack("%32C*",$username) << 17;
                   12992: 	my $nameseed=numval($username) << 12;
                   12993: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12994: 	my $courseseed=unpack("%32C*",$courseid);
                   12995: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12996: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12997: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12998: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12999: 	return $num;
                   13000:     }
                   13001: }
                   13002: 
                   13003: sub rndseed_64bit {
                   13004:     my ($symb,$courseid,$domain,$username)=@_;
                   13005:     {
                   13006: 	use integer;
                   13007: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13008: 	my $symbseed=numval($symb) << 10;
                   13009: 	my $namechck=unpack("%32S*",$username);
                   13010: 	
                   13011: 	my $nameseed=numval($username) << 21;
                   13012: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13013: 	my $courseseed=unpack("%32S*",$courseid);
                   13014: 	
                   13015: 	my $num1=$symbchck+$symbseed+$namechck;
                   13016: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13017: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13018: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13019: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13020: 	return "$num1,$num2";
1.155     albertel 13021:     }
1.366     albertel 13022: }
                   13023: 
1.443     albertel 13024: sub rndseed_64bit2 {
                   13025:     my ($symb,$courseid,$domain,$username)=@_;
                   13026:     {
                   13027: 	use integer;
                   13028: 	# strings need to be an even # of cahracters long, it it is odd the
                   13029:         # last characters gets thrown away
                   13030: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13031: 	my $symbseed=numval($symb) << 10;
                   13032: 	my $namechck=unpack("%32S*",$username.' ');
                   13033: 	
                   13034: 	my $nameseed=numval($username) << 21;
1.501     albertel 13035: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13036: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13037: 	
                   13038: 	my $num1=$symbchck+$symbseed+$namechck;
                   13039: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13040: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13041: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13042: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13043: 	return "$num1,$num2";
                   13044:     }
                   13045: }
                   13046: 
                   13047: sub rndseed_64bit3 {
                   13048:     my ($symb,$courseid,$domain,$username)=@_;
                   13049:     {
                   13050: 	use integer;
                   13051: 	# strings need to be an even # of cahracters long, it it is odd the
                   13052:         # last characters gets thrown away
                   13053: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13054: 	my $symbseed=numval2($symb) << 10;
                   13055: 	my $namechck=unpack("%32S*",$username.' ');
                   13056: 	
                   13057: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13058: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13059: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13060: 	
                   13061: 	my $num1=$symbchck+$symbseed+$namechck;
                   13062: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13063: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13064: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13065: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13066: 	
1.503     albertel 13067: 	return "$num1:$num2";
1.443     albertel 13068:     }
                   13069: }
                   13070: 
1.575     albertel 13071: sub rndseed_64bit4 {
                   13072:     my ($symb,$courseid,$domain,$username)=@_;
                   13073:     {
                   13074: 	use integer;
                   13075: 	# strings need to be an even # of cahracters long, it it is odd the
                   13076:         # last characters gets thrown away
                   13077: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13078: 	my $symbseed=numval3($symb) << 10;
                   13079: 	my $namechck=unpack("%32S*",$username.' ');
                   13080: 	
                   13081: 	my $nameseed=numval3($username) << 21;
                   13082: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13083: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13084: 	
                   13085: 	my $num1=$symbchck+$symbseed+$namechck;
                   13086: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13087: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13088: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13089: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13090: 	
1.575     albertel 13091: 	return "$num1:$num2";
                   13092:     }
                   13093: }
                   13094: 
1.675     albertel 13095: sub rndseed_64bit5 {
                   13096:     my ($symb,$courseid,$domain,$username)=@_;
                   13097:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13098:     return "$num1:$num2";
                   13099: }
                   13100: 
1.366     albertel 13101: sub rndseed_CODE_64bit {
                   13102:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13103:     {
1.366     albertel 13104: 	use integer;
1.443     albertel 13105: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13106: 	my $symbseed=numval2($symb);
1.491     albertel 13107: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13108: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13109: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13110: 	my $num1=$symbseed+$CODEchck;
                   13111: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13112: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13113: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13114: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13115: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13116: 	return "$num1:$num2";
1.366     albertel 13117:     }
                   13118: }
                   13119: 
1.575     albertel 13120: sub rndseed_CODE_64bit4 {
                   13121:     my ($symb,$courseid,$domain,$username)=@_;
                   13122:     {
                   13123: 	use integer;
                   13124: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13125: 	my $symbseed=numval3($symb);
                   13126: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13127: 	my $CODEseed=numval3(&getCODE());
                   13128: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13129: 	my $num1=$symbseed+$CODEchck;
                   13130: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13131: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13132: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13133: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13134: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13135: 	return "$num1:$num2";
                   13136:     }
                   13137: }
                   13138: 
1.675     albertel 13139: sub rndseed_CODE_64bit5 {
                   13140:     my ($symb,$courseid,$domain,$username)=@_;
                   13141:     my $code = &getCODE();
                   13142:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13143:     return "$num1:$num2";
                   13144: }
                   13145: 
1.366     albertel 13146: sub setup_random_from_rndseed {
                   13147:     my ($rndseed)=@_;
1.503     albertel 13148:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13149:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13150:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13151:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13152:         } else {
                   13153:             &Math::Random::random_set_seed($num1,$num2);
                   13154:         }
1.366     albertel 13155:     } else {
                   13156: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13157:     }
1.36      albertel 13158: }
                   13159: 
1.474     albertel 13160: sub latest_receipt_algorithm_id {
1.835     albertel 13161:     return 'receipt3';
1.474     albertel 13162: }
                   13163: 
1.480     www      13164: sub recunique {
                   13165:     my $fucourseid=shift;
                   13166:     my $unique;
1.835     albertel 13167:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13168: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13169: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13170:     } else {
                   13171: 	$unique=$perlvar{'lonReceipt'};
                   13172:     }
                   13173:     return unpack("%32C*",$unique);
                   13174: }
                   13175: 
                   13176: sub recprefix {
                   13177:     my $fucourseid=shift;
                   13178:     my $prefix;
1.835     albertel 13179:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13180: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13181: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13182:     } else {
                   13183: 	$prefix=$perlvar{'lonHostID'};
                   13184:     }
                   13185:     return unpack("%32C*",$prefix);
                   13186: }
                   13187: 
1.76      www      13188: sub ireceipt {
1.474     albertel 13189:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13190: 
                   13191:     my $return =&recprefix($fucourseid).'-';
                   13192: 
                   13193:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13194: 	$env{'request.state'} eq 'construct') {
                   13195: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13196: 	return $return;
                   13197:     }
                   13198: 
1.76      www      13199:     my $cuname=unpack("%32C*",$funame);
                   13200:     my $cudom=unpack("%32C*",$fudom);
                   13201:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13202:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13203:     my $cunique=&recunique($fucourseid);
1.474     albertel 13204:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13205:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13206: 
1.790     albertel 13207: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13208: 			       
                   13209: 	$return.= ($cunique%$cuname+
                   13210: 		   $cunique%$cudom+
                   13211: 		   $cusymb%$cuname+
                   13212: 		   $cusymb%$cudom+
                   13213: 		   $cucourseid%$cuname+
                   13214: 		   $cucourseid%$cudom+
                   13215: 		   $cpart%$cuname+
                   13216: 		   $cpart%$cudom);
                   13217:     } else {
                   13218: 	$return.= ($cunique%$cuname+
                   13219: 		   $cunique%$cudom+
                   13220: 		   $cusymb%$cuname+
                   13221: 		   $cusymb%$cudom+
                   13222: 		   $cucourseid%$cuname+
                   13223: 		   $cucourseid%$cudom);
                   13224:     }
                   13225:     return $return;
1.76      www      13226: }
                   13227: 
                   13228: sub receipt {
1.474     albertel 13229:     my ($part)=@_;
1.790     albertel 13230:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13231:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13232: }
1.260     ng       13233: 
1.790     albertel 13234: sub whichuser {
                   13235:     my ($passedsymb)=@_;
                   13236:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13237:     if (defined($env{'form.grade_symb'})) {
                   13238: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13239: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13240: 	if (!$allowed &&
                   13241: 	    exists($env{'request.course.sec'}) &&
                   13242: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13243: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13244: 			      '/'.$env{'request.course.sec'});
                   13245: 	}
                   13246: 	if ($allowed) {
                   13247: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13248: 	    $courseid=$tmp_courseid;
                   13249: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13250: 	    ($name)=&get_env_multiple('form.grade_username');
                   13251: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13252: 	}
                   13253:     }
                   13254:     if (!$passedsymb) {
                   13255: 	$symb=&symbread();
                   13256:     } else {
                   13257: 	$symb=$passedsymb;
                   13258:     }
                   13259:     $courseid=$env{'request.course.id'};
                   13260:     $domain=$env{'user.domain'};
                   13261:     $name=$env{'user.name'};
                   13262:     if ($name eq 'public' && $domain eq 'public') {
                   13263: 	if (!defined($env{'form.username'})) {
                   13264: 	    $env{'form.username'}.=time.rand(10000000);
                   13265: 	}
                   13266: 	$name.=$env{'form.username'};
                   13267:     }
                   13268:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13269: 
                   13270: }
                   13271: 
1.36      albertel 13272: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13273: # returns either the contents of the file or 
                   13274: # -1 if the file doesn't exist
1.481     raeburn  13275: #
                   13276: # if the target is a file that was uploaded via DOCS, 
                   13277: # a check will be made to see if a current copy exists on the local server,
                   13278: # if it does this will be served, otherwise a copy will be retrieved from
                   13279: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13280: # the local server.   
1.472     albertel 13281: 
1.36      albertel 13282: sub getfile {
1.538     albertel 13283:     my ($file) = @_;
1.609     banghart 13284:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13285:     &repcopy($file);
                   13286:     return &readfile($file);
                   13287: }
                   13288: 
                   13289: sub repcopy_userfile {
                   13290:     my ($file)=@_;
1.1142    raeburn  13291:     my $londocroot = $perlvar{'lonDocRoot'};
                   13292:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13293:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13294:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13295: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13296:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13297:     if (-e "$file") {
1.828     www      13298: # we already have a local copy, check it out
1.538     albertel 13299: 	my @fileinfo = stat($file);
1.828     www      13300: 	my $rtncode;
                   13301: 	my $info;
1.538     albertel 13302: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13303: 	if ($lwpresp ne 'ok') {
1.828     www      13304: # there is no such file anymore, even though we had a local copy
1.482     albertel 13305: 	    if ($rtncode eq '404') {
1.538     albertel 13306: 		unlink($file);
1.482     albertel 13307: 	    }
                   13308: 	    return -1;
                   13309: 	}
                   13310: 	if ($info < $fileinfo[9]) {
1.828     www      13311: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13312: 	    return 'ok';
1.828     www      13313: 	} else {
                   13314: # the file is outdated, get rid of it
                   13315: 	    unlink($file);
1.482     albertel 13316: 	}
1.828     www      13317:     }
                   13318: # one way or the other, at this point, we don't have the file
                   13319: # construct the correct path for the file
                   13320:     my @parts = ($cdom,$cnum); 
                   13321:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13322: 	push @parts, split(/\//,$1);
                   13323:     }
                   13324:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13325:     foreach my $part (@parts) {
                   13326: 	$path .= '/'.$part;
                   13327: 	if (!-e $path) {
                   13328: 	    mkdir($path,0770);
1.482     albertel 13329: 	}
                   13330:     }
1.828     www      13331: # now the path exists for sure
                   13332: # get a user agent
                   13333:     my $transferfile=$file.'.in.transfer';
                   13334: # FIXME: this should flock
                   13335:     if (-e $transferfile) { return 'ok'; }
                   13336:     my $request;
                   13337:     $uri=~s/^\///;
1.980     raeburn  13338:     my $homeserver = &homeserver($cnum,$cdom);
                   13339:     my $protocol = $protocol{$homeserver};
                   13340:     $protocol = 'http' if ($protocol ne 'https');
                   13341:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13342:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13343: # did it work?
                   13344:     if ($response->is_error()) {
                   13345: 	unlink($transferfile);
                   13346: 	&logthis("Userfile repcopy failed for $uri");
                   13347: 	return -1;
                   13348:     }
                   13349: # worked, rename the transfer file
                   13350:     rename($transferfile,$file);
1.607     raeburn  13351:     return 'ok';
1.481     raeburn  13352: }
                   13353: 
1.517     albertel 13354: sub tokenwrapper {
                   13355:     my $uri=shift;
1.980     raeburn  13356:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13357:     $uri=~s|^/||;
1.620     albertel 13358:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13359:     my $token=$1;
1.552     albertel 13360:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13361:     if ($udom && $uname && $file) {
                   13362: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13363:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13364:         my $homeserver = &homeserver($uname,$udom);
                   13365:         my $protocol = $protocol{$homeserver};
                   13366:         $protocol = 'http' if ($protocol ne 'https');
                   13367:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13368:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13369:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13370:     } else {
                   13371:         return '/adm/notfound.html';
                   13372:     }
                   13373: }
                   13374: 
1.828     www      13375: # call with reqtype HEAD: get last modification time
                   13376: # call with reqtype GET: get the file contents
                   13377: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13378: #
1.481     raeburn  13379: sub getuploaded {
                   13380:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13381:     $uri=~s/^\///;
1.980     raeburn  13382:     my $homeserver = &homeserver($cnum,$cdom);
                   13383:     my $protocol = $protocol{$homeserver};
                   13384:     $protocol = 'http' if ($protocol ne 'https');
                   13385:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13386:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13387:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13388:     $$rtncode = $response->code;
1.482     albertel 13389:     if (! $response->is_success()) {
                   13390: 	return 'failed';
                   13391:     }      
                   13392:     if ($reqtype eq 'HEAD') {
1.486     www      13393: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13394:     } elsif ($reqtype eq 'GET') {
                   13395: 	$$info = $response->content;
1.472     albertel 13396:     }
1.482     albertel 13397:     return 'ok';
1.36      albertel 13398: }
                   13399: 
1.481     raeburn  13400: sub readfile {
                   13401:     my $file = shift;
                   13402:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13403:     my $fh;
1.1359    raeburn  13404:     open($fh,"<",$file);
1.481     raeburn  13405:     my $a='';
1.800     albertel 13406:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13407:     return $a;
                   13408: }
                   13409: 
1.36      albertel 13410: sub filelocation {
1.590     banghart 13411:     my ($dir,$file) = @_;
                   13412:     my $location;
                   13413:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13414: 
                   13415:     if ($file =~ m-^/adm/-) {
                   13416: 	$file=~s-^/adm/wrapper/-/-;
                   13417: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13418:     }
1.882     albertel 13419: 
1.1139    www      13420:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13421:         $location = $file;
1.609     banghart 13422:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13423:         my ($udom,$uname,$filename)=
1.811     albertel 13424:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13425:         my $home=&homeserver($uname,$udom);
                   13426:         my $is_me=0;
                   13427:         my @ids=&current_machine_ids();
                   13428:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13429:         if ($is_me) {
1.1117    foxr     13430:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13431:         } else {
                   13432:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13433:   	      $udom.'/'.$uname.'/'.$filename;
                   13434:         }
1.882     albertel 13435:     } elsif ($file =~ m-^/adm/-) {
                   13436: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13437:     } else {
                   13438:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13439:         $file=~s:^/(res|priv)/:/:;
                   13440:         my $space=$1;
1.590     banghart 13441:         if ( !( $file =~ m:^/:) ) {
                   13442:             $location = $dir. '/'.$file;
                   13443:         } else {
1.1142    raeburn  13444:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13445:         }
1.59      albertel 13446:     }
1.590     banghart 13447:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13448:     while ($location=~m{/\.\./}) {
                   13449: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13450: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13451: 	} else {
                   13452: 	    $location=~ s{/\.\./}{/}g;
                   13453: 	}
                   13454:     } #remove dir/..
1.590     banghart 13455:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13456:     return $location;
1.46      www      13457: }
1.36      albertel 13458: 
1.46      www      13459: sub hreflocation {
                   13460:     my ($dir,$file)=@_;
1.980     raeburn  13461:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13462: 	$file=filelocation($dir,$file);
1.700     albertel 13463:     } elsif ($file=~m-^/adm/-) {
                   13464: 	$file=~s-^/adm/wrapper/-/-;
                   13465: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13466:     }
                   13467:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13468: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13469:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13470: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13471: 	        {/uploaded/$1/$2/}x;
1.46      www      13472:     }
1.913     albertel 13473:     if ($file=~ m{^/userfiles/}) {
                   13474: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13475:     }
1.462     albertel 13476:     return $file;
1.465     albertel 13477: }
                   13478: 
1.1139    www      13479: 
                   13480: 
                   13481: 
                   13482: 
1.465     albertel 13483: sub current_machine_domains {
1.853     albertel 13484:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13485: }
                   13486: 
                   13487: sub machine_domains {
                   13488:     my ($hostname) = @_;
1.465     albertel 13489:     my @domains;
1.838     albertel 13490:     my %hostname = &all_hostnames();
1.465     albertel 13491:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13492: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13493: 	if ($hostname eq $name) {
1.844     albertel 13494: 	    push(@domains,&host_domain($id));
1.465     albertel 13495: 	}
                   13496:     }
                   13497:     return @domains;
                   13498: }
                   13499: 
                   13500: sub current_machine_ids {
1.853     albertel 13501:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13502: }
                   13503: 
                   13504: sub machine_ids {
                   13505:     my ($hostname) = @_;
                   13506:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13507:     my @ids;
1.888     albertel 13508:     my %name_to_host = &all_names();
1.889     albertel 13509:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13510: 	return @{ $name_to_host{$hostname} };
                   13511:     }
                   13512:     return;
1.31      www      13513: }
                   13514: 
1.824     raeburn  13515: sub additional_machine_domains {
                   13516:     my @domains;
1.1359    raeburn  13517:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13518:     while( my $line = <$fh>) {
                   13519:         $line =~ s/\s//g;
                   13520:         push(@domains,$line);
                   13521:     }
                   13522:     return @domains;
                   13523: }
                   13524: 
                   13525: sub default_login_domain {
                   13526:     my $domain = $perlvar{'lonDefDomain'};
                   13527:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13528:     foreach my $posdom (&current_machine_domains(),
                   13529:                         &additional_machine_domains()) {
                   13530:         if (lc($posdom) eq lc($testdomain)) {
                   13531:             $domain=$posdom;
                   13532:             last;
                   13533:         }
                   13534:     }
                   13535:     return $domain;
                   13536: }
                   13537: 
1.31      www      13538: # ------------------------------------------------------------- Declutters URLs
                   13539: 
                   13540: sub declutter {
                   13541:     my $thisfn=shift;
1.569     albertel 13542:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13543:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13544:         $thisfn=~s{^/home/httpd/html}{};
                   13545:     }
1.31      www      13546:     $thisfn=~s/^\///;
1.697     albertel 13547:     $thisfn=~s|^adm/wrapper/||;
                   13548:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13549:     $thisfn=~s/^res\///;
1.1172    bisitz   13550:     $thisfn=~s/^priv\///;
1.1032    raeburn  13551:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13552:         $thisfn=~s/\?.+$//;
                   13553:     }
1.268     www      13554:     return $thisfn;
                   13555: }
                   13556: 
                   13557: # ------------------------------------------------------------- Clutter up URLs
                   13558: 
                   13559: sub clutter {
                   13560:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13561:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13562: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13563:        $thisfn='/res'.$thisfn; 
                   13564:     }
1.1031    raeburn  13565:     if ($thisfn !~m|^/adm|) {
                   13566: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13567: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13568: 	} else {
                   13569: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13570: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13571: 	    if ($embstyle eq 'ssi'
                   13572: 		|| ($embstyle eq 'hdn')
                   13573: 		|| ($embstyle eq 'rat')
                   13574: 		|| ($embstyle eq 'prv')
                   13575: 		|| ($embstyle eq 'ign')) {
                   13576: 		#do nothing with these
                   13577: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13578: 		|| ($embstyle eq 'emb')
                   13579: 		|| ($embstyle eq 'wrp')) {
                   13580: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13581: 	    } elsif ($embstyle eq 'unk'
                   13582: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13583: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13584: 	    } else {
1.718     www      13585: #		&logthis("Got a blank emb style");
1.695     albertel 13586: 	    }
1.694     albertel 13587: 	}
1.1343    raeburn  13588:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13589:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13590:     }
1.31      www      13591:     return $thisfn;
1.12      www      13592: }
                   13593: 
1.787     albertel 13594: sub clutter_with_no_wrapper {
                   13595:     my $uri = &clutter(shift);
                   13596:     if ($uri =~ m-^/adm/-) {
                   13597: 	$uri =~ s-^/adm/wrapper/-/-;
                   13598: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13599:     }
                   13600:     return $uri;
                   13601: }
                   13602: 
1.557     albertel 13603: sub freeze_escape {
                   13604:     my ($value)=@_;
                   13605:     if (ref($value)) {
                   13606: 	$value=&nfreeze($value);
                   13607: 	return '__FROZEN__'.&escape($value);
                   13608:     }
                   13609:     return &escape($value);
                   13610: }
                   13611: 
1.11      www      13612: 
1.557     albertel 13613: sub thaw_unescape {
                   13614:     my ($value)=@_;
                   13615:     if ($value =~ /^__FROZEN__/) {
                   13616: 	substr($value,0,10,undef);
                   13617: 	$value=&unescape($value);
                   13618: 	return &thaw($value);
                   13619:     }
                   13620:     return &unescape($value);
                   13621: }
                   13622: 
1.436     albertel 13623: sub correct_line_ends {
                   13624:     my ($result)=@_;
                   13625:     $$result =~s/\r\n/\n/mg;
                   13626:     $$result =~s/\r/\n/mg;
1.415     albertel 13627: }
1.1       albertel 13628: # ================================================================ Main Program
                   13629: 
1.184     www      13630: sub goodbye {
1.204     albertel 13631:    &logthis("Starting Shut down");
1.443     albertel 13632: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13633:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13634: #converted
1.599     albertel 13635: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13636:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13637: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13638: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13639: #1.1 only
1.870     albertel 13640: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13641: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13642: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13643: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13644:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13645:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13646:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13647:    &flushcourselogs();
                   13648:    &logthis("Shutting down");
                   13649: }
                   13650: 
1.852     albertel 13651: sub get_dns {
1.1210    raeburn  13652:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13653:     if (!$ignore_cache) {
                   13654: 	my ($content,$cached)=
                   13655: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13656: 	if ($cached) {
1.1210    raeburn  13657: 	    &$func($content,$hashref);
1.869     albertel 13658: 	    return;
                   13659: 	}
                   13660:     }
                   13661: 
                   13662:     my %alldns;
1.1379    raeburn  13663:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13664:         foreach my $dns (<$config>) {
                   13665: 	    next if ($dns !~ /^\^(\S*)/x);
                   13666:             my $line = $1;
                   13667:             my ($host,$protocol) = split(/:/,$line);
                   13668:             if ($protocol ne 'https') {
                   13669:                 $protocol = 'http';
                   13670:             }
                   13671: 	    $alldns{$host} = $protocol;
1.979     raeburn  13672:         }
1.1379    raeburn  13673:         close($config);
1.869     albertel 13674:     }
                   13675:     while (%alldns) {
1.1263    raeburn  13676: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13677: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13678:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13679:         delete($alldns{$dns});
1.852     albertel 13680: 	next if ($response->is_error());
1.1379    raeburn  13681:         if ($url eq '/adm/dns/loncapaCRL') {
                   13682:             return &$func($response);
                   13683:         } else {
                   13684: 	    my @content = split("\n",$response->content);
                   13685: 	    unless ($nocache) {
                   13686: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   13687: 	    }
                   13688: 	    &$func(\@content,$hashref);
                   13689:             return;
                   13690:         }
                   13691:     }
                   13692:     my $which = (split('/',$url,4))[3];
                   13693:     if ($which eq 'loncapaCRL') {
                   13694:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   13695:         if (-e $diskfile) {
                   13696:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   13697:         } else {
                   13698:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   13699:         }
                   13700:     } else {
                   13701:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13702:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13703:             my @content = <$config>;
                   13704:             close($config);
                   13705:             &$func(\@content,$hashref);
                   13706:         }
1.852     albertel 13707:     }
1.1210    raeburn  13708:     return;
                   13709: }
                   13710: 
                   13711: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13712: sub parse_dns_checksums_tab {
1.1210    raeburn  13713:     my ($lines,$hashref) = @_;
1.1264    raeburn  13714:     my $lonhost = $perlvar{'lonHostID'};
                   13715:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13716:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13717:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13718:     my $webconfdir = '/etc/httpd/conf';
                   13719:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13720:         $webconfdir = '/etc/apache2';
                   13721:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13722:         if ($1 >= 10) {
                   13723:             $webconfdir = '/etc/apache2';
                   13724:         }
                   13725:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13726:         if ($1 >= 10.0) {
                   13727:             $webconfdir = '/etc/apache2';
                   13728:         }
                   13729:     }
1.1210    raeburn  13730:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13731:     my (%chksum,%revnum);
                   13732:     if (ref($lines) eq 'ARRAY') {
                   13733:         chomp(@{$lines});
1.1238    raeburn  13734:         my $version = shift(@{$lines});
                   13735:         if ($version eq $release) {  
1.1210    raeburn  13736:             foreach my $line (@{$lines}) {
1.1238    raeburn  13737:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13738:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13739:                     if ($webconfdir eq '/etc/apache2') {
                   13740:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13741:                     }
                   13742:                 }
1.1238    raeburn  13743:                 $chksum{$file} = $shasum;
                   13744:                 $revnum{$file} = $version;
1.1210    raeburn  13745:             }
                   13746:             if (ref($hashref) eq 'HASH') {
                   13747:                 %{$hashref} = (
                   13748:                                 sums     => \%chksum,
                   13749:                                 versions => \%revnum,
                   13750:                               );
                   13751:             }
                   13752:         }
                   13753:     }
1.869     albertel 13754:     return;
1.852     albertel 13755: }
1.1210    raeburn  13756: 
                   13757: sub fetch_dns_checksums {
1.1238    raeburn  13758:     my %checksums;
                   13759:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13760:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13761:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13762:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13763:              \%checksums);
1.1210    raeburn  13764:     return \%checksums;
                   13765: }
                   13766: 
1.1379    raeburn  13767: sub fetch_crl_pemfile {
                   13768:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   13769: }
                   13770: 
                   13771: sub save_crl_pem {
                   13772:     my ($response) = @_;
1.1380    raeburn  13773:     my ($msg,$hadchanges);
1.1379    raeburn  13774:     if (ref($response)) {
                   13775:         my $now = time;
                   13776:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   13777:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   13778:         if (open(my $fh,'>',"$tmpcrl")) {
                   13779:             print $fh $response->content;
                   13780:             close($fh);
                   13781:             if (-e $lonca) {
                   13782:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   13783:                     my $check = <PIPE>;
                   13784:                     close(PIPE);
                   13785:                     chomp($check);
                   13786:                     if ($check eq 'verify OK') {
                   13787:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  13788:                         my $backup;
1.1379    raeburn  13789:                         if (-e $dest) {
1.1380    raeburn  13790:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   13791:                                 $backup = 'ok';
                   13792:                             }
1.1379    raeburn  13793:                         }
                   13794:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   13795:                             $msg = 'ok';
1.1380    raeburn  13796:                             if ($backup) {
                   13797:                                 my (%oldnums,%newnums);
                   13798:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   13799:                                     while (<PIPE>) {
                   13800:                                         $oldnums{(split(/:/))[1]} = 1;
                   13801:                                     }
                   13802:                                     close(PIPE);
                   13803:                                 }
                   13804:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   13805:                                     while(<PIPE>) {
                   13806:                                         $newnums{(split(/:/))[1]} = 1;
                   13807:                                     }
                   13808:                                     close(PIPE);
                   13809:                                 }
                   13810:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   13811:                                     unless (exists($oldnums{$key})) {
                   13812:                                         $hadchanges = 1;
                   13813:                                         last;
                   13814:                                     }
                   13815:                                 }
                   13816:                                 unless ($hadchanges) {
                   13817:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   13818:                                         unless (exists($newnums{$key})) {
                   13819:                                             $hadchanges = 1;
                   13820:                                             last;
                   13821:                                         }
                   13822:                                     }
                   13823:                                 }
                   13824:                             }
1.1379    raeburn  13825:                         }
                   13826:                     } else {
                   13827:                         unlink($tmpcrl);
                   13828:                     }
                   13829:                 } else {
                   13830:                     unlink($tmpcrl);
                   13831:                 }
                   13832:             } else {
                   13833:                 unlink($tmpcrl);
                   13834:             }
                   13835:         }
                   13836:     }
1.1380    raeburn  13837:     return ($msg,$hadchanges);
1.1379    raeburn  13838: }
                   13839: 
1.327     albertel 13840: # ------------------------------------------------------------ Read domain file
                   13841: {
1.852     albertel 13842:     my $loaded;
1.846     albertel 13843:     my %domain;
                   13844: 
1.852     albertel 13845:     sub parse_domain_tab {
                   13846: 	my ($lines) = @_;
                   13847: 	foreach my $line (@$lines) {
                   13848: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13849: 
1.846     albertel 13850: 	    chomp($line);
1.852     albertel 13851: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13852: 	    my %this_domain;
                   13853: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13854: 			       'lang_def', 'city', 'longi', 'lati',
                   13855: 			       'primary') {
                   13856: 		$this_domain{$field} = shift(@elements);
                   13857: 	    }
                   13858: 	    $domain{$name} = \%this_domain;
1.852     albertel 13859: 	}
                   13860:     }
1.864     albertel 13861: 
                   13862:     sub reset_domain_info {
                   13863: 	undef($loaded);
                   13864: 	undef(%domain);
                   13865:     }
                   13866: 
1.852     albertel 13867:     sub load_domain_tab {
1.1293    raeburn  13868: 	my ($ignore_cache,$nocache) = @_;
                   13869: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13870: 	my $fh;
1.1359    raeburn  13871: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13872: 	    my @lines = <$fh>;
                   13873: 	    &parse_domain_tab(\@lines);
1.448     albertel 13874: 	}
1.852     albertel 13875: 	close($fh);
                   13876: 	$loaded = 1;
1.327     albertel 13877:     }
1.846     albertel 13878: 
                   13879:     sub domain {
1.852     albertel 13880: 	&load_domain_tab() if (!$loaded);
                   13881: 
1.846     albertel 13882: 	my ($name,$what) = @_;
                   13883: 	return if ( !exists($domain{$name}) );
                   13884: 
                   13885: 	if (!$what) {
                   13886: 	    return $domain{$name}{'description'};
                   13887: 	}
                   13888: 	return $domain{$name}{$what};
                   13889:     }
1.974     raeburn  13890: 
                   13891:     sub domain_info {
                   13892:         &load_domain_tab() if (!$loaded);
                   13893:         return %domain;
                   13894:     }
                   13895: 
1.327     albertel 13896: }
                   13897: 
                   13898: 
1.1       albertel 13899: # ------------------------------------------------------------- Read hosts file
                   13900: {
1.838     albertel 13901:     my %hostname;
1.844     albertel 13902:     my %hostdom;
1.845     albertel 13903:     my %libserv;
1.852     albertel 13904:     my $loaded;
1.888     albertel 13905:     my %name_to_host;
1.1074    raeburn  13906:     my %internetdom;
1.1107    raeburn  13907:     my %LC_dns_serv;
1.852     albertel 13908: 
                   13909:     sub parse_hosts_tab {
                   13910: 	my ($file) = @_;
                   13911: 	foreach my $configline (@$file) {
                   13912: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13913:             chomp($configline);
                   13914: 	    if ($configline =~ /^\^/) {
                   13915:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13916:                     $LC_dns_serv{$1} = 1;
                   13917:                 }
                   13918:                 next;
                   13919:             }
1.1074    raeburn  13920: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13921: 	    $name=~s/\s//g;
                   13922: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13923:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13924:                     my $curr = $hostname{$id};
                   13925:                     my $skip;
                   13926:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13927:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13928:                             $skip = 1;
                   13929:                         } else {
                   13930:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13931:                         }
                   13932:                     }
                   13933:                     unless ($skip) {
                   13934:                         push(@{$name_to_host{$name}},$id);
                   13935:                     }
                   13936:                 } else {
                   13937:                     push(@{$name_to_host{$name}},$id);
                   13938:                 }
1.852     albertel 13939: 		$hostname{$id}=$name;
                   13940: 		$hostdom{$id}=$domain;
                   13941: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13942:                 if (defined($protocol)) {
                   13943:                     if ($protocol eq 'https') {
                   13944:                         $protocol{$id} = $protocol;
                   13945:                     } else {
                   13946:                         $protocol{$id} = 'http'; 
                   13947:                     }
1.968     raeburn  13948:                 } else {
1.969     raeburn  13949:                     $protocol{$id} = 'http';
1.968     raeburn  13950:                 }
1.1074    raeburn  13951:                 if (defined($intdom)) {
                   13952:                     $internetdom{$id} = $intdom;
                   13953:                 }
1.852     albertel 13954: 	    }
                   13955: 	}
                   13956:     }
1.864     albertel 13957:     
                   13958:     sub reset_hosts_info {
1.897     albertel 13959: 	&purge_remembered();
1.864     albertel 13960: 	&reset_domain_info();
                   13961: 	&reset_hosts_ip_info();
1.1339    raeburn  13962:         undef(%internetdom);
1.892     albertel 13963: 	undef(%name_to_host);
1.864     albertel 13964: 	undef(%hostname);
                   13965: 	undef(%hostdom);
                   13966: 	undef(%libserv);
                   13967: 	undef($loaded);
                   13968:     }
1.1       albertel 13969: 
1.852     albertel 13970:     sub load_hosts_tab {
1.1293    raeburn  13971: 	my ($ignore_cache,$nocache) = @_;
                   13972: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13973: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13974: 	my @config = <$config>;
                   13975: 	&parse_hosts_tab(\@config);
                   13976: 	close($config);
                   13977: 	$loaded=1;
1.1       albertel 13978:     }
1.852     albertel 13979: 
1.838     albertel 13980:     sub hostname {
1.852     albertel 13981: 	&load_hosts_tab() if (!$loaded);
                   13982: 
1.838     albertel 13983: 	my ($lonid) = @_;
                   13984: 	return $hostname{$lonid};
                   13985:     }
1.845     albertel 13986: 
1.838     albertel 13987:     sub all_hostnames {
1.852     albertel 13988: 	&load_hosts_tab() if (!$loaded);
                   13989: 
1.838     albertel 13990: 	return %hostname;
                   13991:     }
1.845     albertel 13992: 
1.888     albertel 13993:     sub all_names {
1.1293    raeburn  13994:         my ($ignore_cache,$nocache) = @_;
                   13995: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13996: 
                   13997: 	return %name_to_host;
                   13998:     }
                   13999: 
1.974     raeburn  14000:     sub all_host_domain {
                   14001:         &load_hosts_tab() if (!$loaded);
                   14002:         return %hostdom;
                   14003:     }
                   14004: 
1.1339    raeburn  14005:     sub all_host_intdom {
                   14006:         &load_hosts_tab() if (!$loaded);
                   14007:         return %internetdom;
                   14008:     }
                   14009: 
1.845     albertel 14010:     sub is_library {
1.852     albertel 14011: 	&load_hosts_tab() if (!$loaded);
                   14012: 
1.845     albertel 14013: 	return exists($libserv{$_[0]});
                   14014:     }
                   14015: 
                   14016:     sub all_library {
1.852     albertel 14017: 	&load_hosts_tab() if (!$loaded);
                   14018: 
1.845     albertel 14019: 	return %libserv;
                   14020:     }
                   14021: 
1.1062    droeschl 14022:     sub unique_library {
                   14023: 	#2x reverse removes all hostnames that appear more than once
                   14024:         my %unique = reverse &all_library();
                   14025:         return reverse %unique;
                   14026:     }
                   14027: 
1.841     albertel 14028:     sub get_servers {
1.852     albertel 14029: 	&load_hosts_tab() if (!$loaded);
                   14030: 
1.841     albertel 14031: 	my ($domain,$type) = @_;
                   14032: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14033: 	                                          : %hostname;
                   14034: 	my %result;
1.842     albertel 14035: 	if (ref($domain) eq 'ARRAY') {
                   14036: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14037: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14038: 		    $result{$host} = $hostname;
                   14039: 		}
                   14040: 	    }
                   14041: 	} else {
                   14042: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14043: 		if ($hostdom{$host} eq $domain) {
                   14044: 		    $result{$host} = $hostname;
                   14045: 		}
1.841     albertel 14046: 	    }
                   14047: 	}
                   14048: 	return %result;
                   14049:     }
1.845     albertel 14050: 
1.1062    droeschl 14051:     sub get_unique_servers {
                   14052:         my %unique = reverse &get_servers(@_);
                   14053: 	return reverse %unique;
                   14054:     }
                   14055: 
1.844     albertel 14056:     sub host_domain {
1.852     albertel 14057: 	&load_hosts_tab() if (!$loaded);
                   14058: 
1.844     albertel 14059: 	my ($lonid) = @_;
                   14060: 	return $hostdom{$lonid};
                   14061:     }
                   14062: 
1.841     albertel 14063:     sub all_domains {
1.852     albertel 14064: 	&load_hosts_tab() if (!$loaded);
                   14065: 
1.841     albertel 14066: 	my %seen;
                   14067: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14068: 	return @uniq;
                   14069:     }
1.1074    raeburn  14070: 
                   14071:     sub internet_dom {
                   14072:         &load_hosts_tab() if (!$loaded);
                   14073: 
                   14074:         my ($lonid) = @_;
                   14075:         return $internetdom{$lonid};
                   14076:     }
1.1107    raeburn  14077: 
                   14078:     sub is_LC_dns {
                   14079:         &load_hosts_tab() if (!$loaded);
                   14080: 
                   14081:         my ($hostname) = @_;
                   14082:         return exists($LC_dns_serv{$hostname});
                   14083:     }
                   14084: 
1.1       albertel 14085: }
                   14086: 
1.847     albertel 14087: { 
                   14088:     my %iphost;
1.856     albertel 14089:     my %name_to_ip;
                   14090:     my %lonid_to_ip;
1.869     albertel 14091: 
1.847     albertel 14092:     sub get_hosts_from_ip {
                   14093: 	my ($ip) = @_;
                   14094: 	my %iphosts = &get_iphost();
                   14095: 	if (ref($iphosts{$ip})) {
                   14096: 	    return @{$iphosts{$ip}};
                   14097: 	}
                   14098: 	return;
1.839     albertel 14099:     }
1.864     albertel 14100:     
                   14101:     sub reset_hosts_ip_info {
                   14102: 	undef(%iphost);
                   14103: 	undef(%name_to_ip);
                   14104: 	undef(%lonid_to_ip);
                   14105:     }
1.856     albertel 14106: 
                   14107:     sub get_host_ip {
                   14108: 	my ($lonid) = @_;
                   14109: 	if (exists($lonid_to_ip{$lonid})) {
                   14110: 	    return $lonid_to_ip{$lonid};
                   14111: 	}
                   14112: 	my $name=&hostname($lonid);
                   14113:    	my $ip = gethostbyname($name);
                   14114: 	return if (!$ip || length($ip) ne 4);
                   14115: 	$ip=inet_ntoa($ip);
                   14116: 	$name_to_ip{$name}   = $ip;
                   14117: 	$lonid_to_ip{$lonid} = $ip;
                   14118: 	return $ip;
                   14119:     }
1.847     albertel 14120:     
                   14121:     sub get_iphost {
1.1293    raeburn  14122: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14123: 
1.869     albertel 14124: 	if (!$ignore_cache) {
                   14125: 	    if (%iphost) {
                   14126: 		return %iphost;
                   14127: 	    }
                   14128: 	    my ($ip_info,$cached)=
                   14129: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14130: 	    if ($cached) {
                   14131: 		%iphost      = %{$ip_info->[0]};
                   14132: 		%name_to_ip  = %{$ip_info->[1]};
                   14133: 		%lonid_to_ip = %{$ip_info->[2]};
                   14134: 		return %iphost;
                   14135: 	    }
                   14136: 	}
1.894     albertel 14137: 
                   14138: 	# get yesterday's info for fallback
                   14139: 	my %old_name_to_ip;
                   14140: 	my ($ip_info,$cached)=
                   14141: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14142: 	if ($cached) {
                   14143: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14144: 	}
                   14145: 
1.1293    raeburn  14146: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14147: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14148: 	    my $ip;
                   14149: 	    if (!exists($name_to_ip{$name})) {
                   14150: 		$ip = gethostbyname($name);
                   14151: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14152: 		    if (defined($old_name_to_ip{$name})) {
                   14153: 			$ip = $old_name_to_ip{$name};
                   14154: 			&logthis("Can't find $name defaulting to old $ip");
                   14155: 		    } else {
                   14156: 			&logthis("Name $name no IP found");
                   14157: 			next;
                   14158: 		    }
                   14159: 		} else {
                   14160: 		    $ip=inet_ntoa($ip);
1.847     albertel 14161: 		}
                   14162: 		$name_to_ip{$name} = $ip;
                   14163: 	    } else {
                   14164: 		$ip = $name_to_ip{$name};
1.653     albertel 14165: 	    }
1.888     albertel 14166: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14167: 		$lonid_to_ip{$id} = $ip;
                   14168: 	    }
                   14169: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14170: 	}
1.1293    raeburn  14171:         unless ($nocache) {
                   14172: 	    &do_cache_new('iphost','iphost',
                   14173: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14174: 		          48*60*60);
                   14175:         }
1.869     albertel 14176: 
1.847     albertel 14177: 	return %iphost;
1.598     albertel 14178:     }
                   14179: 
1.992     raeburn  14180:     #
                   14181:     #  Given a DNS returns the loncapa host name for that DNS 
                   14182:     # 
                   14183:     sub host_from_dns {
                   14184:         my ($dns) = @_;
                   14185:         my @hosts;
                   14186:         my $ip;
                   14187: 
1.993     raeburn  14188:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14189:             $ip = $name_to_ip{$dns};
                   14190:         }
                   14191:         if (!$ip) {
                   14192:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14193:             if (length($ip) == 4) { 
                   14194: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14195:             }
                   14196:         }
                   14197:         if ($ip) {
                   14198: 	    @hosts = get_hosts_from_ip($ip);
                   14199: 	    return $hosts[0];
                   14200:         }
                   14201:         return undef;
1.986     foxr     14202:     }
1.992     raeburn  14203: 
1.1074    raeburn  14204:     sub get_internet_names {
                   14205:         my ($lonid) = @_;
                   14206:         return if ($lonid eq '');
                   14207:         my ($idnref,$cached)=
                   14208:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14209:         if ($cached) {
                   14210:             return $idnref;
                   14211:         }
                   14212:         my $ip = &get_host_ip($lonid);
                   14213:         my @hosts = &get_hosts_from_ip($ip);
                   14214:         my %iphost = &get_iphost();
                   14215:         my (@idns,%seen);
                   14216:         foreach my $id (@hosts) {
                   14217:             my $dom = &host_domain($id);
                   14218:             my $prim_id = &domain($dom,'primary');
                   14219:             my $prim_ip = &get_host_ip($prim_id);
                   14220:             next if ($seen{$prim_ip});
                   14221:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14222:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14223:                     my $intdom = &internet_dom($id);
                   14224:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14225:                         push(@idns,$intdom);
                   14226:                     }
                   14227:                 }
                   14228:             }
                   14229:             $seen{$prim_ip} = 1;
                   14230:         }
1.1219    raeburn  14231:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14232:     }
                   14233: 
1.986     foxr     14234: }
                   14235: 
1.1079    raeburn  14236: sub all_loncaparevs {
1.1249    raeburn  14237:     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  14238: }
                   14239: 
1.1227    raeburn  14240: # ---------------------------------------------------------- Read loncaparev table
                   14241: {
                   14242:     sub load_loncaparevs { 
                   14243:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14244:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14245:                 while (my $configline=<$config>) {
                   14246:                     chomp($configline);
                   14247:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14248:                     $loncaparevs{$hostid}=$loncaparev;
                   14249:                 }
                   14250:                 close($config);
                   14251:             }
                   14252:         }
                   14253:     }
                   14254: }
                   14255: 
                   14256: # ---------------------------------------------------------- Read serverhostID table
                   14257: {
                   14258:     sub load_serverhomeIDs {
                   14259:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14260:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14261:                 while (my $configline=<$config>) {
                   14262:                     chomp($configline);
                   14263:                     my ($name,$id)=split(/:/,$configline);
                   14264:                     $serverhomeIDs{$name}=$id;
                   14265:                 }
                   14266:                 close($config);
                   14267:             }
                   14268:         }
                   14269:     }
                   14270: }
                   14271: 
                   14272: 
1.862     albertel 14273: BEGIN {
                   14274: 
                   14275: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14276:     unless ($readit) {
                   14277: {
                   14278:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14279:     %perlvar = (%perlvar,%{$configvars});
                   14280: }
                   14281: 
                   14282: 
1.1       albertel 14283: # ------------------------------------------------------ Read spare server file
                   14284: {
1.1359    raeburn  14285:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14286: 
                   14287:     while (my $configline=<$config>) {
                   14288:        chomp($configline);
1.284     matthew  14289:        if ($configline) {
1.784     albertel 14290: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14291: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14292: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14293:        }
                   14294:     }
1.448     albertel 14295:     close($config);
1.1       albertel 14296: }
1.11      www      14297: # ------------------------------------------------------------ Read permissions
                   14298: {
1.1359    raeburn  14299:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14300: 
                   14301:     while (my $configline=<$config>) {
1.448     albertel 14302: 	chomp($configline);
                   14303: 	if ($configline) {
                   14304: 	    my ($role,$perm)=split(/ /,$configline);
                   14305: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14306: 	}
1.11      www      14307:     }
1.448     albertel 14308:     close($config);
1.11      www      14309: }
                   14310: 
                   14311: # -------------------------------------------- Read plain texts for permissions
                   14312: {
1.1359    raeburn  14313:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14314: 
                   14315:     while (my $configline=<$config>) {
1.448     albertel 14316: 	chomp($configline);
                   14317: 	if ($configline) {
1.742     raeburn  14318: 	    my ($short,@plain)=split(/:/,$configline);
                   14319:             %{$prp{$short}} = ();
                   14320: 	    if (@plain > 0) {
                   14321:                 $prp{$short}{'std'} = $plain[0];
                   14322:                 for (my $i=1; $i<@plain; $i++) {
                   14323:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14324:                 }
                   14325:             }
1.448     albertel 14326: 	}
1.135     www      14327:     }
1.448     albertel 14328:     close($config);
1.135     www      14329: }
                   14330: 
                   14331: # ---------------------------------------------------------- Read package table
                   14332: {
1.1359    raeburn  14333:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14334: 
                   14335:     while (my $configline=<$config>) {
1.483     albertel 14336: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14337: 	chomp($configline);
                   14338: 	my ($short,$plain)=split(/:/,$configline);
                   14339: 	my ($pack,$name)=split(/\&/,$short);
                   14340: 	if ($plain ne '') {
                   14341: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14342: 	    $packagetab{$short}=$plain; 
                   14343: 	}
1.11      www      14344:     }
1.448     albertel 14345:     close($config);
1.329     matthew  14346: }
                   14347: 
1.1073    raeburn  14348: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14349: 
                   14350: &load_loncaparevs();
1.1073    raeburn  14351: 
1.1074    raeburn  14352: # ---------------------------------------------------------- Read serverhostID table
                   14353: 
1.1227    raeburn  14354: &load_serverhomeIDs();
                   14355: 
                   14356: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14357: {
                   14358:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14359:     if (-e $file) {
                   14360:         my $parser = HTML::LCParser->new($file);
                   14361:         while (my $token = $parser->get_token()) {
                   14362:             if ($token->[0] eq 'S') {
                   14363:                 my $item = $token->[1];
                   14364:                 my $name = $token->[2]{'name'};
                   14365:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14366:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14367:                 my $namematch = $token->[2]{'namematch'};
                   14368:                 if ($item eq 'parameter') {
                   14369:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14370:                         my $release = $parser->get_text();
                   14371:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14372:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14373:                     }
                   14374:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14375:                     my $release = $parser->get_text();
                   14376:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14377:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14378:                 }
                   14379:             }
                   14380:         }
                   14381:     }
1.1073    raeburn  14382: }
                   14383: 
1.1138    raeburn  14384: # ---------------------------------------------------------- Read managers table
                   14385: {
                   14386:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14387:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14388:             while (my $configline=<$config>) {
                   14389:                 chomp($configline);
                   14390:                 next if ($configline =~ /^\#/);
                   14391:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14392:                     $managerstab{$configline} = 1;
                   14393:                 }
                   14394:             }
                   14395:             close($config);
                   14396:         }
                   14397:     }
                   14398: }
                   14399: 
1.329     matthew  14400: # ------------- set up temporary directory
                   14401: {
1.1117    foxr     14402:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14403: 
1.11      www      14404: }
                   14405: 
1.794     albertel 14406: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14407: 				'compress_threshold'=> 20_000,
                   14408:  			        });
1.185     www      14409: 
1.281     www      14410: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14411: $dumpcount=0;
1.958     www      14412: $locknum=0;
1.22      www      14413: 
1.163     harris41 14414: &logtouch();
1.672     albertel 14415: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14416: $readit=1;
1.564     albertel 14417:     {
                   14418: 	use integer;
                   14419: 	my $test=(2**32)+1;
1.568     albertel 14420: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14421: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14422:     }
1.195     www      14423: }
1.1       albertel 14424: }
1.179     www      14425: 
1.1       albertel 14426: 1;
1.191     harris41 14427: __END__
                   14428: 
1.243     albertel 14429: =pod
                   14430: 
1.191     harris41 14431: =head1 NAME
                   14432: 
1.243     albertel 14433: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14434: 
                   14435: =head1 SYNOPSIS
                   14436: 
1.243     albertel 14437: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14438: 
                   14439:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14440: 
1.243     albertel 14441: Common parameters:
                   14442: 
                   14443: =over 4
                   14444: 
                   14445: =item *
                   14446: 
                   14447: $uname : an internal username (if $cname expecting a course Id specifically)
                   14448: 
                   14449: =item *
                   14450: 
                   14451: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14452: 
                   14453: =item *
                   14454: 
                   14455: $symb : a resource instance identifier
                   14456: 
                   14457: =item *
                   14458: 
                   14459: $namespace : the name of a .db file that contains the data needed or
                   14460: being set.
                   14461: 
                   14462: =back
                   14463: 
1.394     bowersj2 14464: =head1 OVERVIEW
1.191     harris41 14465: 
1.394     bowersj2 14466: lonnet provides subroutines which interact with the
                   14467: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14468: about classes, users, and resources.
1.243     albertel 14469: 
                   14470: For many of these objects you can also use this to store data about
                   14471: them or modify them in various ways.
1.191     harris41 14472: 
1.394     bowersj2 14473: =head2 Symbs
1.191     harris41 14474: 
1.394     bowersj2 14475: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14476: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14477: map, the resource number of the resource in the map, and the URL of
                   14478: the resource itself. The latter is somewhat redundant, but might help
                   14479: if maps change.
                   14480: 
                   14481: An example is
                   14482: 
                   14483:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14484: 
                   14485: The respective map entry is
                   14486: 
                   14487:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14488:   title="Problem 2">
                   14489:  </resource>
                   14490: 
                   14491: Symbs are used by the random number generator, as well as to store and
                   14492: restore data specific to a certain instance of for example a problem.
                   14493: 
                   14494: =head2 Storing And Retrieving Data
                   14495: 
                   14496: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14497: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14498: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14499: is is the non-critical message twin of cstore. These functions are for
                   14500: handlers to store a perl hash to a user's permanent data space in an
                   14501: easy manner, and to retrieve it again on another call. It is expected
                   14502: that a handler would use this once at the beginning to retrieve data,
                   14503: and then again once at the end to send only the new data back.
                   14504: 
                   14505: The data is stored in the user's data directory on the user's
                   14506: homeserver under the ID of the course.
                   14507: 
                   14508: The hash that is returned by restore will have all of the previous
                   14509: value for all of the elements of the hash.
                   14510: 
                   14511: Example:
                   14512: 
                   14513:  #creating a hash
                   14514:  my %hash;
                   14515:  $hash{'foo'}='bar';
                   14516: 
                   14517:  #storing it
                   14518:  &Apache::lonnet::cstore(\%hash);
                   14519: 
                   14520:  #changing a value
                   14521:  $hash{'foo'}='notbar';
                   14522: 
                   14523:  #adding a new value
                   14524:  $hash{'bar'}='foo';
                   14525:  &Apache::lonnet::cstore(\%hash);
                   14526: 
                   14527:  #retrieving the hash
                   14528:  my %history=&Apache::lonnet::restore();
                   14529: 
                   14530:  #print the hash
                   14531:  foreach my $key (sort(keys(%history))) {
                   14532:    print("\%history{$key} = $history{$key}");
                   14533:  }
                   14534: 
                   14535: Will print out:
1.191     harris41 14536: 
1.394     bowersj2 14537:  %history{1:foo} = bar
                   14538:  %history{1:keys} = foo:timestamp
                   14539:  %history{1:timestamp} = 990455579
                   14540:  %history{2:bar} = foo
                   14541:  %history{2:foo} = notbar
                   14542:  %history{2:keys} = foo:bar:timestamp
                   14543:  %history{2:timestamp} = 990455580
                   14544:  %history{bar} = foo
                   14545:  %history{foo} = notbar
                   14546:  %history{timestamp} = 990455580
                   14547:  %history{version} = 2
                   14548: 
                   14549: Note that the special hash entries C<keys>, C<version> and
                   14550: C<timestamp> were added to the hash. C<version> will be equal to the
                   14551: total number of versions of the data that have been stored. The
                   14552: C<timestamp> attribute will be the UNIX time the hash was
                   14553: stored. C<keys> is available in every historical section to list which
                   14554: keys were added or changed at a specific historical revision of a
                   14555: hash.
                   14556: 
                   14557: B<Warning>: do not store the hash that restore returns directly. This
                   14558: will cause a mess since it will restore the historical keys as if the
                   14559: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14560: 
1.394     bowersj2 14561: Calling convention:
1.191     harris41 14562: 
1.1225    raeburn  14563:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14564:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14565: 
1.394     bowersj2 14566: For more detailed information, see lonnet specific documentation.
1.191     harris41 14567: 
1.394     bowersj2 14568: =head1 RETURN MESSAGES
1.191     harris41 14569: 
1.394     bowersj2 14570: =over 4
1.191     harris41 14571: 
1.394     bowersj2 14572: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14573: 
1.394     bowersj2 14574: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14575: when the connection is brought back up
1.191     harris41 14576: 
1.394     bowersj2 14577: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14578: for later delivery
1.191     harris41 14579: 
1.967     bisitz   14580: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14581: 
1.394     bowersj2 14582: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14583: that was requested
1.191     harris41 14584: 
1.243     albertel 14585: =back
1.191     harris41 14586: 
1.243     albertel 14587: =head1 PUBLIC SUBROUTINES
1.191     harris41 14588: 
1.243     albertel 14589: =head2 Session Environment Functions
1.191     harris41 14590: 
1.243     albertel 14591: =over 4
1.191     harris41 14592: 
1.394     bowersj2 14593: =item * 
                   14594: X<appenv()>
1.949     raeburn  14595: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14596: the user envirnoment file, and will be restored for each access this
1.620     albertel 14597: user makes during this session, also modifies the %env for the current
1.949     raeburn  14598: process. Optional rolesarrayref - if defined contains a reference to an array
                   14599: of roles which are exempt from the restriction on modifying user.role entries 
                   14600: in the user's environment.db and in %env.    
1.191     harris41 14601: 
                   14602: =item *
1.394     bowersj2 14603: X<delenv()>
1.987     raeburn  14604: B<delenv($delthis,$regexp)>: removes all items from the session
                   14605: environment file that begin with $delthis. If the 
                   14606: optional second arg - $regexp - is true, $delthis is treated as a 
                   14607: regular expression, otherwise \Q$delthis\E is used. 
                   14608: The values are also deleted from the current processes %env.
1.191     harris41 14609: 
1.795     albertel 14610: =item * get_env_multiple($name) 
                   14611: 
                   14612: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14613: values may be defined and end up as an array ref.
                   14614: 
                   14615: returns an array of values
                   14616: 
1.243     albertel 14617: =back
                   14618: 
                   14619: =head2 User Information
1.191     harris41 14620: 
1.243     albertel 14621: =over 4
1.191     harris41 14622: 
                   14623: =item *
1.394     bowersj2 14624: X<queryauthenticate()>
                   14625: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14626: authentication scheme
                   14627: 
                   14628: =item *
1.394     bowersj2 14629: X<authenticate()>
1.1073    raeburn  14630: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14631: authenticate user from domain's lib servers (first use the current
                   14632: one). C<$upass> should be the users password.
1.1073    raeburn  14633: $checkdefauth is optional (value is 1 if a check should be made to
                   14634:    authenticate user using default authentication method, and allow
                   14635:    account creation if username does not have account in the domain).
                   14636: $clientcancheckhost is optional (value is 1 if checking whether the
                   14637:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14638: 
                   14639: =item *
1.394     bowersj2 14640: X<homeserver()>
                   14641: B<homeserver($uname,$udom)>: find the server which has
                   14642: the user's directory and files (there must be only one), this caches
                   14643: the answer, and also caches if there is a borken connection.
1.191     harris41 14644: 
                   14645: =item *
1.394     bowersj2 14646: X<idget()>
1.1300    raeburn  14647: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14648: a list of student/employee IDs or clicker IDs
                   14649: (student/employee IDs are a unique resource in a domain, there must be 
                   14650: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14651: clickerIDs are not necessarily unique, as students might share clickers.
                   14652: (returns hash: id=>name,id=>name)
1.191     harris41 14653: 
                   14654: =item *
1.394     bowersj2 14655: X<idrget()>
                   14656: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14657: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14658: 
                   14659: =item *
1.394     bowersj2 14660: X<idput()>
1.1300    raeburn  14661: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14662: names and associated student/employee IDs or clicker IDs.
                   14663: 
                   14664: =item *
                   14665: X<iddel()>
                   14666: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14667: student/employee ID or clicker ID username look-ups from domain.
                   14668: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14669: If no $uhome is provided, it will be determined usig &homeserver()
                   14670: for each user.  If no $namespace is provided, the default is ids.
                   14671: 
                   14672: =item *
                   14673: X<updateclickers()>
                   14674: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14675: clicker ID-to-username look-ups in clickers.db on library server.
                   14676: Permitted actions are add or del (i.e., add or delete). The 
                   14677: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14678: value is an escaped comma-separated list of usernames (for whom the
                   14679: library server is the homeserver), who registered that particular ID.
                   14680: If $critical is true, the update will be sent via &critical, otherwise
                   14681: &reply() will be used.
1.191     harris41 14682: 
                   14683: =item *
1.394     bowersj2 14684: X<rolesinit()>
1.1169    droeschl 14685: B<rolesinit($udom,$username)>: get user privileges.
                   14686: returns user role, first access and timer interval hashes
1.243     albertel 14687: 
                   14688: =item *
1.1171    droeschl 14689: X<privileged()>
                   14690: B<privileged($username,$domain)>: returns a true if user has a
                   14691: privileged and active role (i.e. su or dc), false otherwise.
                   14692: 
                   14693: =item *
1.551     albertel 14694: X<getsection()>
                   14695: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14696: course $cname, return section name/number or '' for "not in course"
                   14697: and '-1' for "no section"
                   14698: 
                   14699: =item *
1.394     bowersj2 14700: X<userenvironment()>
                   14701: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14702: passed in @what from the requested user's environment, returns a hash
                   14703: 
1.858     raeburn  14704: =item * 
                   14705: X<userlog_query()>
1.859     albertel 14706: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14707: activity.log file. %filters defines filters applied when parsing the
                   14708: log file. These can be start or end timestamps, or the type of action
                   14709: - log to look for Login or Logout events, check for Checkin or
                   14710: Checkout, role for role selection. The response is in the form
                   14711: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14712: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14713: 
1.243     albertel 14714: =back
                   14715: 
                   14716: =head2 User Roles
                   14717: 
                   14718: =over 4
                   14719: 
                   14720: =item *
                   14721: 
1.1284    raeburn  14722: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14723: returns codes for allowed actions.
                   14724: 
                   14725: The first argument is required, all others are optional.
                   14726: 
                   14727: $priv is the privilege being checked.
                   14728: $uri contains additional information about what is being checked for access (e.g.,
                   14729: URL, course ID etc.). 
                   14730: $symb is the unique resource instance identifier in a course; if needed,
                   14731: but not provided, it will be retrieved via a call to &symbread(). 
                   14732: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14733: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14734: files).
                   14735: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14736: prevents recursive calls to &allowed.
                   14737: 
1.243     albertel 14738:  F: full access
                   14739:  U,I,K: authentication modes (cxx only)
                   14740:  '': forbidden
                   14741:  1: user needs to choose course
                   14742:  2: browse allowed
1.766     albertel 14743:  A: passphrase authentication needed
1.1284    raeburn  14744:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14745: 
                   14746: =item *
                   14747: 
1.1192    raeburn  14748: constructaccess($url,$setpriv) : check for access to construction space URL
                   14749: 
                   14750: See if the owner domain and name in the URL match those in the
                   14751: expected environment.  If so, return three element list
                   14752: ($ownername,$ownerdomain,$ownerhome).
                   14753: 
                   14754: Otherwise return the null string.
                   14755: 
                   14756: If second argument 'setpriv' is true, it assigns the privileges,
                   14757: and returns the same three element list, unless the owner has
                   14758: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14759: in which case the null string is returned.
                   14760: 
                   14761: =item *
                   14762: 
1.1326    raeburn  14763: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14764: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14765: for system, domain, and course level. $uname and $udom are optional (current
                   14766: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14767: 
                   14768: =item *
                   14769: 
1.988     raeburn  14770: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14771: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14772: $type is Course (default) or Community.
1.988     raeburn  14773: If $forcedefault evaluates to true, text returned will be default 
                   14774: text for $type. Otherwise, if this is a course, the text returned 
                   14775: will be a custom name for the role (if defined in the course's 
                   14776: environment).  If no custom name is defined the default is returned.
                   14777:    
1.832     raeburn  14778: =item *
                   14779: 
1.1219    raeburn  14780: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14781: All arguments are optional. Returns a hash of a roles, either for
                   14782: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14783: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14784: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14785: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14786: For each key, value is set to colon-separated start and end times for
                   14787: the role.  If no username and domain are specified, will default to
1.934     raeburn  14788: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14789: of role statuses (active, future or previous), roles 
                   14790: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14791: to restrict the list of roles reported. If no array ref is 
                   14792: provided for types, will default to return only active roles.
1.834     albertel 14793: 
1.1195    raeburn  14794: =item *
                   14795: 
                   14796: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14797: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14798: 
                   14799: Additional optional arguments are: $type (if role checking is to be restricted 
                   14800: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14801: available roles) or future (roles available in the future), and
                   14802: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14803: have active Domain Coordinator role in course's domain or in additional
                   14804: domains (specified in 'Domains to check for privileged users' in course
                   14805: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14806: 
                   14807: =item *
                   14808: 
                   14809: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14810: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14811: $possdomains and $possroles are optional array refs -- to domains to check and
                   14812: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14813: users' roles.db to check for a dc or su role in any domain. This can be
                   14814: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14815: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14816: this then allows &privileged_by_domain() to be used, which caches the identity
                   14817: of privileged users, eliminating the need for repeated calls to &dump().
                   14818: 
                   14819: =item *
                   14820: 
                   14821: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14822: where the outer hash keys are domains specified in the $possdomains array ref,
                   14823: next inner hash keys are privileged roles specified in the $roles array ref,
                   14824: and the innermost hash contains key = value pairs for username:domain = end:start
                   14825: for active or future "privileged" users with that role in that domain. To avoid
                   14826: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14827: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14828: 
1.243     albertel 14829: =back
                   14830: 
                   14831: =head2 User Modification
                   14832: 
                   14833: =over 4
                   14834: 
                   14835: =item *
                   14836: 
1.957     raeburn  14837: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14838: user for the level given by URL.  Optional start and end dates (leave empty
                   14839: string or zero for "no date")
1.191     harris41 14840: 
                   14841: =item *
                   14842: 
1.243     albertel 14843: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14844: change a users, password, possible return values are: ok,
                   14845: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14846: refused
1.191     harris41 14847: 
                   14848: =item *
                   14849: 
1.243     albertel 14850: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14851: 
                   14852: =item *
                   14853: 
1.1058    raeburn  14854: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14855:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14856: 
                   14857: will update user information (firstname,middlename,lastname,generation,
                   14858: permanentemail), and if forceid is true, student/employee ID also.
                   14859: A user's institutional affiliation(s) can also be updated.
                   14860: User information fields will not be overwritten with empty entries 
                   14861: unless the field is included in the $candelete array reference.
                   14862: This array is included when a single user is modified via "Manage Users",
                   14863: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14864: 
                   14865: =item *
                   14866: 
1.286     matthew  14867: modifystudent
                   14868: 
1.957     raeburn  14869: modify a student's enrollment and identification information.
1.1235    raeburn  14870: The course id is resolved based on the current user's environment.  
                   14871: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14872: associated with a course.
                   14873: 
1.297     matthew  14874: This call is essentially a wrapper for lonnet::modifyuser and
                   14875: lonnet::modify_student_enrollment
1.286     matthew  14876: 
                   14877: Inputs: 
                   14878: 
                   14879: =over 4
                   14880: 
1.957     raeburn  14881: =item B<$udom> Student's loncapa domain
1.286     matthew  14882: 
1.957     raeburn  14883: =item B<$uname> Student's loncapa login name
1.286     matthew  14884: 
1.964     bisitz   14885: =item B<$uid> Student/Employee ID
1.286     matthew  14886: 
1.957     raeburn  14887: =item B<$umode> Student's authentication mode
1.286     matthew  14888: 
1.957     raeburn  14889: =item B<$upass> Student's password
1.286     matthew  14890: 
1.957     raeburn  14891: =item B<$first> Student's first name
1.286     matthew  14892: 
1.957     raeburn  14893: =item B<$middle> Student's middle name
1.286     matthew  14894: 
1.957     raeburn  14895: =item B<$last> Student's last name
1.286     matthew  14896: 
1.957     raeburn  14897: =item B<$gene> Student's generation
1.286     matthew  14898: 
1.957     raeburn  14899: =item B<$usec> Student's section in course
1.286     matthew  14900: 
                   14901: =item B<$end> Unix time of the roles expiration
                   14902: 
                   14903: =item B<$start> Unix time of the roles start date
                   14904: 
                   14905: =item B<$forceid> If defined, allow $uid to be changed
                   14906: 
                   14907: =item B<$desiredhome> server to use as home server for student
                   14908: 
1.957     raeburn  14909: =item B<$email> Student's permanent e-mail address
                   14910: 
                   14911: =item B<$type> Type of enrollment (auto or manual)
                   14912: 
1.963     raeburn  14913: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14914: 
                   14915: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14916: 
1.963     raeburn  14917: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14918: 
1.963     raeburn  14919: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14920: 
1.1216    raeburn  14921: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14922: 
                   14923: =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  14924: 
1.286     matthew  14925: =back
1.297     matthew  14926: 
                   14927: =item *
                   14928: 
                   14929: modify_student_enrollment
                   14930: 
1.1235    raeburn  14931: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14932: 'role.request.course' must be defined for this function to proceed.
                   14933: 
                   14934: Inputs:
                   14935: 
                   14936: =over 4
                   14937: 
1.1235    raeburn  14938: =item $udom, student's domain
1.297     matthew  14939: 
1.1235    raeburn  14940: =item $uname, student's name
1.297     matthew  14941: 
1.1235    raeburn  14942: =item $uid, student's user id
1.297     matthew  14943: 
1.1235    raeburn  14944: =item $first, student's first name
1.297     matthew  14945: 
                   14946: =item $middle
                   14947: 
                   14948: =item $last
                   14949: 
                   14950: =item $gene
                   14951: 
                   14952: =item $usec
                   14953: 
                   14954: =item $end
                   14955: 
                   14956: =item $start
                   14957: 
1.957     raeburn  14958: =item $type
                   14959: 
                   14960: =item $locktype
                   14961: 
                   14962: =item $cid
                   14963: 
                   14964: =item $selfenroll
                   14965: 
                   14966: =item $context
                   14967: 
1.1216    raeburn  14968: =item $credits, number of credits student will earn from this class
                   14969: 
1.1314    raeburn  14970: =item $instsec, institutional course section code for student
                   14971: 
1.297     matthew  14972: =back
                   14973: 
1.191     harris41 14974: 
                   14975: =item *
                   14976: 
1.243     albertel 14977: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14978: custom role; give a custom role to a user for the level given by URL.  Specify
                   14979: name and domain of role author, and role name
1.191     harris41 14980: 
                   14981: =item *
                   14982: 
1.243     albertel 14983: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14984: 
                   14985: =item *
                   14986: 
1.243     albertel 14987: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14988: 
                   14989: =back
                   14990: 
                   14991: =head2 Course Infomation
                   14992: 
                   14993: =over 4
1.191     harris41 14994: 
                   14995: =item *
                   14996: 
1.1118    foxr     14997: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14998: specified course id, including all environment settings for the
                   14999: course, the description of the course will be in the hash under the
                   15000: key 'description'
1.191     harris41 15001: 
1.1118    foxr     15002: $options is an optional parameter that if supplied is a hash reference that controls
                   15003: what how this function works.  It has the following key/values:
                   15004: 
                   15005: =over 4
                   15006: 
                   15007: =item freshen_cache
                   15008: 
                   15009: If defined, and the environment cache for the course is valid, it is 
                   15010: returned in the returned hash.
                   15011: 
                   15012: =item one_time
                   15013: 
                   15014: If defined, the last cache time is set to _now_
                   15015: 
                   15016: =item user
                   15017: 
                   15018: If defined, the supplied username is used instead of the current user.
                   15019: 
                   15020: 
                   15021: =back
                   15022: 
1.191     harris41 15023: =item *
                   15024: 
1.624     albertel 15025: resdata($name,$domain,$type,@which) : request for current parameter
                   15026: setting for a specific $type, where $type is either 'course' or 'user',
                   15027: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15028: answers for 10 minutes.
1.243     albertel 15029: 
1.877     foxr     15030: =item *
                   15031: 
                   15032: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15033: data base, returning a hash that is keyed by the resource name and has
                   15034: values that are the resource value.  I believe that the timestamps and
                   15035: versions are also returned.
                   15036: 
1.1236    raeburn  15037: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15038: supplemental content area. This routine caches the number of files for 
                   15039: 10 minutes.
                   15040: 
1.243     albertel 15041: =back
                   15042: 
                   15043: =head2 Course Modification
                   15044: 
                   15045: =over 4
1.191     harris41 15046: 
                   15047: =item *
                   15048: 
1.243     albertel 15049: writecoursepref($courseid,%prefs) : write preferences (environment
                   15050: database) for a course
1.191     harris41 15051: 
                   15052: =item *
                   15053: 
1.1011    raeburn  15054: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15055: 
                   15056: =item *
                   15057: 
1.1038    raeburn  15058: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15059: 
1.1167    droeschl 15060: =item *
                   15061: 
                   15062: is_course($courseid), is_course($cdom, $cnum)
                   15063: 
                   15064: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15065: two component version $cdom, $cnum. It checks if the specified course exists.
                   15066: 
                   15067: Returns:
                   15068:     undef if the course doesn't exist, otherwise
                   15069:     in scalar context the combined courseid.
                   15070:     in list context the two components of the course identifier, domain and 
                   15071:     courseid.    
                   15072: 
1.243     albertel 15073: =back
                   15074: 
                   15075: =head2 Resource Subroutines
                   15076: 
                   15077: =over 4
1.191     harris41 15078: 
                   15079: =item *
                   15080: 
1.243     albertel 15081: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15082: 
                   15083: =item *
                   15084: 
1.243     albertel 15085: repcopy($filename) : subscribes to the requested file, and attempts to
                   15086: replicate from the owning library server, Might return
1.607     raeburn  15087: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15088: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15089: resource. Expects the local filesystem pathname
                   15090: (/home/httpd/html/res/....)
                   15091: 
                   15092: =back
                   15093: 
                   15094: =head2 Resource Information
                   15095: 
                   15096: =over 4
1.191     harris41 15097: 
                   15098: =item *
                   15099: 
1.1228    raeburn  15100: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15101: and returns the value of a variety of different possible values,
                   15102: $varname should be a request string, and the other parameters can be
                   15103: used to specify who and what one is asking about. Ordinarily, $cid 
                   15104: does not need to be specified, as it is retrived from 
                   15105: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15106: within lonuserstate::loadmap() when initializing a course, before
                   15107: $env{'request.course.id'} has been set, so it needs to be provided
                   15108: in that one case.
1.243     albertel 15109: 
                   15110: Possible values for $varname are environment.lastname (or other item
                   15111: from the envirnment hash), user.name (or someother aspect about the
                   15112: user), resource.0.maxtries (or some other part and parameter of a
                   15113: resource)
1.204     albertel 15114: 
                   15115: =item *
                   15116: 
1.243     albertel 15117: directcondval($number) : get current value of a condition; reads from a state
                   15118: string
1.204     albertel 15119: 
                   15120: =item *
                   15121: 
1.243     albertel 15122: condval($condidx) : value of condition index based on state
1.204     albertel 15123: 
                   15124: =item *
                   15125: 
1.1362    raeburn  15126: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15127: resource's metadata, $what should be either a specific key, or either
                   15128: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15129: packages that this resource currently uses, the last 3 arguments are 
                   15130: only used internally for recursive metadata.
                   15131: 
                   15132: the toolsymb is only used where the uri is for an external tool (for which
                   15133: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15134: 
1.1371    raeburn  15135: this function automatically caches all requests except any made recursively
                   15136: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15137: defined).
1.191     harris41 15138: 
                   15139: =item *
                   15140: 
1.243     albertel 15141: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15142: network of library servers; returns file handle of where SQL and regex results
                   15143: will be stored for query
1.191     harris41 15144: 
                   15145: =item *
                   15146: 
1.1282    raeburn  15147: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15148: return symbolic list entry (all arguments optional). 
                   15149: 
                   15150: Args: filename is the filename (including path) for the file for which a symb 
                   15151: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15152: to check access status if more than one resource was found in the bighash 
                   15153: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15154: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15155: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15156: cause possible symbs to be checked to determine if they are subject to content
                   15157: blocking, if so they will not be included as possible symbs; possibles is a
                   15158: ref to a hash, which, as a side effect, will be populated with all possible 
                   15159: symbs (content blocking not tested).
                   15160:  
1.243     albertel 15161: returns the data handle
1.191     harris41 15162: 
                   15163: =item *
                   15164: 
1.1190    raeburn  15165: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15166: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15167: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15168: on failure, user must be in a course, as it assumes the existence of
                   15169: the course initial hash, and uses $env('request.course.id'}.  The third
                   15170: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15171: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15172: encrypted; otherwise it will be null.  
1.191     harris41 15173: 
                   15174: =item *
                   15175: 
1.243     albertel 15176: symbclean($symb) : removes versions numbers from a symb, returns the
                   15177: cleaned symb
1.191     harris41 15178: 
                   15179: =item *
                   15180: 
1.243     albertel 15181: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15182: course map, user must be in a course for it to work.
1.191     harris41 15183: 
                   15184: =item *
                   15185: 
1.243     albertel 15186: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15187: 
                   15188: =item *
                   15189: 
1.243     albertel 15190: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15191: a random seed, all arguments are optional, if they aren't sent it uses the
                   15192: environment to derive them. Note: if symb isn't sent and it can't get one
                   15193: from &symbread it will use the current time as its return value
1.191     harris41 15194: 
                   15195: =item *
                   15196: 
1.243     albertel 15197: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15198: unfakeable, receipt
1.191     harris41 15199: 
                   15200: =item *
                   15201: 
1.620     albertel 15202: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15203: 
                   15204: =item *
                   15205: 
1.243     albertel 15206: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15207: 
                   15208: =item *
                   15209: 
1.243     albertel 15210: 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 15211: 
                   15212: =item *
                   15213: 
1.243     albertel 15214: 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 15215: 
                   15216: =item *
                   15217: 
1.243     albertel 15218: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15219: 
                   15220: =item *
                   15221: 
1.243     albertel 15222: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15223: forcing spreadsheet to reevaluate the resource scores next time.
                   15224: 
1.1195    raeburn  15225: =item * 
                   15226: 
1.1196    raeburn  15227: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15228: when viewing in course context.
1.1195    raeburn  15229: 
1.1196    raeburn  15230:  input: six args -- filename (decluttered), course number, course domain,
                   15231:                     url, symb (if registered) and group (if this is a 
                   15232:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15233: 
1.1196    raeburn  15234:  output: array of five scalars --
1.1195    raeburn  15235:          $cfile -- url for file editing if editable on current server
                   15236:          $home -- homeserver of resource (i.e., for author if published,
                   15237:                                           or course if uploaded.).
                   15238:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15239:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15240:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15241: 
                   15242: =item *
                   15243: 
                   15244: is_course_upload($file,$cnum,$cdom)
                   15245: 
                   15246: Used in course context to determine if current file was uploaded to 
                   15247: the course (i.e., would be found in /userfiles/docs on the course's 
                   15248: homeserver.
                   15249: 
                   15250:   input: 3 args -- filename (decluttered), course number and course domain.
                   15251:   output: boolean -- 1 if file was uploaded.
                   15252: 
1.243     albertel 15253: =back
                   15254: 
                   15255: =head2 Storing/Retreiving Data
                   15256: 
                   15257: =over 4
1.191     harris41 15258: 
                   15259: =item *
                   15260: 
1.1269    raeburn  15261: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15262: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15263: the remaining args aren't required and if they aren't passed or are '' they will
                   15264: be derived from the env (with the exception of $laststore, which is an 
                   15265: optional arg used when a user's submission is stored in grading).
                   15266: $laststore is $version=$timestamp, where $version is the most recent version
                   15267: number retrieved for the corresponding $symb in the $namespace db file, and
                   15268: $timestamp is the timestamp for that transaction (UNIX time).
                   15269: $laststore is currently only passed when cstore() is called by 
                   15270: structuretags::finalize_storage().
1.191     harris41 15271: 
                   15272: =item *
                   15273: 
1.1269    raeburn  15274: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15275: but uses critical subroutine
1.191     harris41 15276: 
                   15277: =item *
                   15278: 
1.243     albertel 15279: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15280: all args are optional
1.191     harris41 15281: 
                   15282: =item *
                   15283: 
1.717     albertel 15284: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15285: dumps the complete (or key matching regexp) namespace into a hash
                   15286: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15287: normally &store()ed into
                   15288: 
                   15289: $range should be either an integer '100' (give me the first 100
                   15290:                                            matching records)
                   15291:               or be  two integers sperated by a - with no spaces
                   15292:                  '30-50' (give me the 30th through the 50th matching
                   15293:                           records)
                   15294: 
                   15295: 
                   15296: =item *
                   15297: 
1.1269    raeburn  15298: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15299: replaces a &store() version of data with a replacement set of data
                   15300: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15301: reference. If $tolog is true, the transaction is logged in the courselog
                   15302: with an action=PUTSTORE.
1.717     albertel 15303: 
                   15304: =item *
                   15305: 
1.243     albertel 15306: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15307: works very similar to store/cstore, but all data is stored in a
                   15308: temporary location and can be reset using tmpreset, $storehash should
                   15309: be a hash reference, returns nothing on success
1.191     harris41 15310: 
                   15311: =item *
                   15312: 
1.243     albertel 15313: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15314: similar to restore, but all data is stored in a temporary location and
                   15315: can be reset using tmpreset. Returns a hash of values on success,
                   15316: error string otherwise.
1.191     harris41 15317: 
                   15318: =item *
                   15319: 
1.243     albertel 15320: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15321: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15322: 
                   15323: =item *
                   15324: 
1.243     albertel 15325: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15326: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15327: 
                   15328: =item *
                   15329: 
1.243     albertel 15330: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15331: namesp ($udom and $uname are optional)
1.191     harris41 15332: 
                   15333: =item *
                   15334: 
1.702     albertel 15335: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15336: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15337: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15338: 
1.702     albertel 15339: $range should be either an integer '100' (give me the first 100
                   15340:                                            matching records)
                   15341:               or be  two integers sperated by a - with no spaces
                   15342:                  '30-50' (give me the 30th through the 50th matching
                   15343:                           records)
1.449     matthew  15344: =item *
                   15345: 
                   15346: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15347: $store can be a scalar, an array reference, or if the amount to be 
                   15348: incremented is > 1, a hash reference.
                   15349: 
                   15350: ($udom and $uname are optional)
1.191     harris41 15351: 
                   15352: =item *
                   15353: 
1.243     albertel 15354: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15355: ($udom and $uname are optional)
1.191     harris41 15356: 
                   15357: =item *
                   15358: 
1.243     albertel 15359: cput($namespace,$storehash,$udom,$uname) : critical put
                   15360: ($udom and $uname are optional)
1.191     harris41 15361: 
                   15362: =item *
                   15363: 
1.748     albertel 15364: newput($namespace,$storehash,$udom,$uname) :
                   15365: 
                   15366: Attempts to store the items in the $storehash, but only if they don't
                   15367: currently exist, if this succeeds you can be certain that you have 
                   15368: successfully created a new key value pair in the $namespace db.
                   15369: 
                   15370: 
                   15371: Args:
                   15372:  $namespace: name of database to store values to
                   15373:  $storehash: hashref to store to the db
                   15374:  $udom: (optional) domain of user containing the db
                   15375:  $uname: (optional) name of user caontaining the db
                   15376: 
                   15377: Returns:
                   15378:  'ok' -> succeeded in storing all keys of $storehash
                   15379:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15380:                         least <key> already existed in the db (other
                   15381:                         requested keys may also already exist)
1.967     bisitz   15382:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15383:  'con_lost' -> unable to contact request server
                   15384:  'refused' -> action was not allowed by remote machine
                   15385: 
                   15386: 
                   15387: =item *
                   15388: 
1.243     albertel 15389: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15390: reference filled in from namesp (encrypts the return communication)
                   15391: ($udom and $uname are optional)
1.191     harris41 15392: 
                   15393: =item *
                   15394: 
1.243     albertel 15395: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15396: critical subroutine
                   15397: 
1.806     raeburn  15398: =item *
                   15399: 
1.860     raeburn  15400: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15401: array reference filled in from namespace found in domain level on either
                   15402: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15403: 
                   15404: =item *
                   15405: 
1.860     raeburn  15406: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15407: domain level either on specified domain server ($uhome) or primary domain 
                   15408: server ($udom and $uhome are optional)
1.806     raeburn  15409: 
1.943     raeburn  15410: =item * 
                   15411: 
1.1240    raeburn  15412: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15413: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15414: the target domain.
                   15415: 
                   15416: May also include additional key => value pairs for the following groups:
                   15417: 
                   15418: =over
                   15419: 
                   15420: =item
                   15421: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15422: 
                   15423: =over
                   15424: 
                   15425: =item defaultquota, authorquota
                   15426: 
                   15427: =back
                   15428: 
                   15429: =item
                   15430: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15431: portfolio for users).
                   15432: 
                   15433: =over
                   15434: 
                   15435: =item
                   15436: aboutme, blog, webdav, portfolio
                   15437: 
                   15438: =back
                   15439: 
                   15440: =item
                   15441: requestcourses: ability to request courses, and how requests are processed.
                   15442: 
                   15443: =over
                   15444: 
                   15445: =item
1.1305    raeburn  15446: official, unofficial, community, textbook, placement
1.1240    raeburn  15447: 
                   15448: =back
                   15449: 
                   15450: =item
                   15451: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15452: 
                   15453: =over
                   15454: 
                   15455: =item
1.1256    raeburn  15456: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15457: 
                   15458: =back
                   15459: 
                   15460: =item
                   15461: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15462: for course's uploaded content.
                   15463: 
                   15464: =over
                   15465: 
                   15466: =item
1.1246    raeburn  15467: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15468: communityquota, textbookquota, placementquota
1.1240    raeburn  15469: 
                   15470: =back
                   15471: 
                   15472: =item
                   15473: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15474: on your servers.
                   15475: 
                   15476: =over
                   15477: 
                   15478: =item 
                   15479: remotesessions, hostedsessions
                   15480: 
                   15481: =back
                   15482: 
                   15483: =back
                   15484: 
                   15485: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15486: utility to create a configuration.db file on a domain's primary library server 
                   15487: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15488: -- corresponding values are authentication type (internal, krb4, krb5,
                   15489: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15490: will be available. Values are retrieved from cache (if current), unless the
                   15491: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15492: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15493: 
                   15494: Typical usage:
1.943     raeburn  15495: 
1.1240    raeburn  15496: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15497: 
1.243     albertel 15498: =back
                   15499: 
                   15500: =head2 Network Status Functions
                   15501: 
                   15502: =over 4
1.191     harris41 15503: 
                   15504: =item *
                   15505: 
1.1137    raeburn  15506: dirlist() : return directory list based on URI (first arg).
                   15507: 
                   15508: Inputs: 1 required, 5 optional.
                   15509: 
                   15510: =over
                   15511: 
                   15512: =item 
                   15513: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15514: 
                   15515: =item
                   15516: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15517: 
                   15518: =item
                   15519: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15520: 
                   15521: =item
                   15522: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15523: 
                   15524: =item
                   15525: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15526: 
                   15527: =item 
                   15528: $alternateRoot - path to prepend in place of path from $uri.
                   15529: 
                   15530: =back
                   15531: 
                   15532: Returns: Array of up to two items.
                   15533: 
                   15534: =over
                   15535: 
                   15536: a reference to an array of files/subdirectories
                   15537: 
                   15538: =over
                   15539: 
                   15540: Each element in the array of files/subdirectories is a & separated list of
                   15541: item name and the result of running stat on the item.  If dirlist was requested
                   15542: for a file instead of a directory, the item name will be ''. For a directory 
                   15543: listing, if the item is a metadata file, the element will end &N&M 
                   15544: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15545: default copyright set (1).  
                   15546: 
                   15547: =back
                   15548: 
                   15549: a scalar containing error condition (if encountered).
                   15550: 
                   15551: =over
                   15552: 
                   15553: =item 
                   15554: no_host (no homeserver identified for $username:$domain).
                   15555: 
                   15556: =item 
                   15557: no_such_host (server contacted for listing not identified as valid host).
                   15558: 
                   15559: =item 
                   15560: con_lost (connection to remote server failed).
                   15561: 
                   15562: =item 
                   15563: refused (invalid $username:$domain received on lond side).
                   15564: 
                   15565: =item 
                   15566: no_such_dir (directory at specified path on lond side does not exist). 
                   15567: 
                   15568: =item 
                   15569: empty (directory at specified path on lond side is empty).
                   15570: 
                   15571: =over
                   15572: 
                   15573: This is currently not encountered because the &ls3, &ls2, 
                   15574: &ls (_handler) routines on the lond side do not filter out
                   15575: . and .. from a directory listing. 
                   15576: 
                   15577: =back
                   15578: 
                   15579: =back
                   15580: 
                   15581: =back
1.191     harris41 15582: 
                   15583: =item *
                   15584: 
1.243     albertel 15585: spareserver() : find server with least workload from spare.tab
                   15586: 
1.986     foxr     15587: 
                   15588: =item *
                   15589: 
                   15590: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15591: if there is no corresponding loncapa host.
                   15592: 
1.243     albertel 15593: =back
                   15594: 
1.986     foxr     15595: 
1.243     albertel 15596: =head2 Apache Request
                   15597: 
                   15598: =over 4
1.191     harris41 15599: 
                   15600: =item *
                   15601: 
1.243     albertel 15602: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15603: localhost, posts hash
                   15604: 
                   15605: =back
                   15606: 
                   15607: =head2 Data to String to Data
                   15608: 
                   15609: =over 4
1.191     harris41 15610: 
                   15611: =item *
                   15612: 
1.243     albertel 15613: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15614: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15615: 
                   15616: =item *
                   15617: 
1.243     albertel 15618: hashref2str($hashref) : convert a hashref into a string complete with
                   15619: escaping and '=' and '&' separators, supports elements that are
                   15620: arrayrefs and hashrefs
1.191     harris41 15621: 
                   15622: =item *
                   15623: 
1.243     albertel 15624: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15625: with escaping and '&' separators, supports elements that are arrayrefs
                   15626: and hashrefs
1.191     harris41 15627: 
                   15628: =item *
                   15629: 
1.243     albertel 15630: str2hash($string) : convert string to hash using unescaping and
                   15631: splitting on '=' and '&', supports elements that are arrayrefs and
                   15632: hashrefs
1.191     harris41 15633: 
                   15634: =item *
                   15635: 
1.243     albertel 15636: str2array($string) : convert string to hash using unescaping and
                   15637: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15638: 
                   15639: =back
                   15640: 
                   15641: =head2 Logging Routines
                   15642: 
                   15643: 
                   15644: These routines allow one to make log messages in the lonnet.log and
                   15645: lonnet.perm logfiles.
1.191     harris41 15646: 
1.1119    foxr     15647: =over 4
                   15648: 
1.191     harris41 15649: =item *
                   15650: 
1.243     albertel 15651: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15652: 
                   15653: =item *
                   15654: 
1.243     albertel 15655: logthis() : append message to the normal lonnet.log file, it gets
                   15656: preiodically rolled over and deleted.
1.191     harris41 15657: 
                   15658: =item *
                   15659: 
1.243     albertel 15660: logperm() : append a permanent message to lonnet.perm.log, this log
                   15661: file never gets deleted by any automated portion of the system, only
                   15662: messages of critical importance should go in here.
                   15663: 
1.1119    foxr     15664: 
1.243     albertel 15665: =back
                   15666: 
                   15667: =head2 General File Helper Routines
                   15668: 
                   15669: =over 4
1.191     harris41 15670: 
                   15671: =item *
                   15672: 
1.481     raeburn  15673: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15674: (a) files in /uploaded
                   15675:   (i) If a local copy of the file exists - 
                   15676:       compares modification date of local copy with last-modified date for 
                   15677:       definitive version stored on home server for course. If local copy is 
                   15678:       stale, requests a new version from the home server and stores it. 
                   15679:       If the original has been removed from the home server, then local copy 
                   15680:       is unlinked.
                   15681:   (ii) If local copy does not exist -
                   15682:       requests the file from the home server and stores it. 
                   15683:   
                   15684:   If $caller is 'uploadrep':  
                   15685:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15686:     for request for files originally uploaded via DOCS. 
                   15687:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15688:   
                   15689:   Otherwise:
                   15690:      This indicates a call from the content generation phase of the request.
                   15691:      -  returns the entire contents of the file or -1.
                   15692:      
                   15693: (b) files in /res
                   15694:    - returns the entire contents of a file or -1; 
                   15695:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15696: 
1.712     albertel 15697: 
                   15698: =item *
                   15699: 
                   15700: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15701:                   reference
                   15702: 
                   15703: returns either a stat() list of data about the file or an empty list
                   15704: if the file doesn't exist or couldn't find out about it (connection
                   15705: problems or user unknown)
                   15706: 
1.191     harris41 15707: =item *
                   15708: 
1.243     albertel 15709: filelocation($dir,$file) : returns file system location of a file
                   15710: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15711: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15712: and a file of ../bob will become /a/bob)
1.191     harris41 15713: 
                   15714: =item *
                   15715: 
                   15716: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15717: filelocation except for hrefs
                   15718: 
                   15719: =item *
                   15720: 
1.1261    raeburn  15721: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15722: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15723: 
1.243     albertel 15724: =back
                   15725: 
1.608     albertel 15726: =head2 Usererfile file routines (/uploaded*)
                   15727: 
                   15728: =over 4
                   15729: 
                   15730: =item *
                   15731: 
                   15732: userfileupload(): main rotine for putting a file in a user or course's
                   15733:                   filespace, arguments are,
                   15734: 
1.620     albertel 15735:  formname - required - this is the name of the element in $env where the
1.608     albertel 15736:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15737:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15738:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15739:  context - if coursedoc, store the file in the course of the active role
                   15740:              of the current user; 
                   15741:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15742:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15743:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15744:          if undefined, it will be placed in "unknown"
                   15745: 
                   15746:  (This routine calls clean_filename() to remove any dangerous
                   15747:  characters from the filename, and then calls finuserfileupload() to
                   15748:  complete the transaction)
                   15749: 
                   15750:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15751:  and /adm/notfound.html if unsuccessful
                   15752: 
                   15753: =item *
                   15754: 
                   15755: clean_filename(): routine for cleaing a filename up for storage in
                   15756:                  userfile space, argument is:
                   15757: 
                   15758:  filename - proposed filename
                   15759: 
                   15760: returns: the new clean filename
                   15761: 
                   15762: =item *
                   15763: 
1.1090    raeburn  15764: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15765: userspace, probably shouldn't be called directly
                   15766: 
                   15767:   docuname: username or courseid of destination for the file
                   15768:   docudom: domain of user/course of destination for the file
                   15769:   formname: same as for userfileupload()
1.1090    raeburn  15770:   fname: filename (including subdirectories) for the file
                   15771:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15772:   allfiles: reference to hash used to store objects found by parser
                   15773:   codebase: reference to hash used for codebases of java objects found by parser
                   15774:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15775:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15776:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15777:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15778:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15779:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15780:   mimetype: reference to scalar to accommodate mime type determined
                   15781:             from File::MMagic if $parser = parse.
1.608     albertel 15782: 
                   15783:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15784:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15785:  was 'overwrite').
                   15786:  
1.608     albertel 15787: 
                   15788: =item *
                   15789: 
                   15790: renameuserfile(): renames an existing userfile to a new name
                   15791: 
                   15792:   Args:
                   15793:    docuname: username or courseid of destination for the file
                   15794:    docudom: domain of user/course of destination for the file
                   15795:    old: current file name (including any subdirs under userfiles)
                   15796:    new: desired file name (including any subdirs under userfiles)
                   15797: 
                   15798: =item *
                   15799: 
                   15800: mkdiruserfile(): creates a directory is a userfiles dir
                   15801: 
                   15802:   Args:
                   15803:    docuname: username or courseid of destination for the file
                   15804:    docudom: domain of user/course of destination for the file
                   15805:    dir: dir to create (including any subdirs under userfiles)
                   15806: 
                   15807: =item *
                   15808: 
                   15809: removeuserfile(): removes a file that exists in userfiles
                   15810: 
                   15811:   Args:
                   15812:    docuname: username or courseid of destination for the file
                   15813:    docudom: domain of user/course of destination for the file
                   15814:    fname: filname to delete (including any subdirs under userfiles)
                   15815: 
                   15816: =item *
                   15817: 
                   15818: removeuploadedurl(): convience function for removeuserfile()
                   15819: 
                   15820:   Args:
                   15821:    url:  a full /uploaded/... url to delete
                   15822: 
1.747     albertel 15823: =item * 
                   15824: 
                   15825: get_portfile_permissions():
                   15826:   Args:
                   15827:     domain: domain of user or course contain the portfolio files
                   15828:     user: name of user or num of course contain the portfolio files
                   15829:   Returns:
                   15830:     hashref of a dump of the proper file_permissions.db
                   15831:    
                   15832: 
                   15833: =item * 
                   15834: 
                   15835: get_access_controls():
                   15836: 
                   15837: Args:
                   15838:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15839:   group: (optional) the group you want the files associated with
                   15840:   file: (optional) the file you want access info on
                   15841: 
                   15842: Returns:
1.749     raeburn  15843:     a hash (keys are file names) of hashes containing
                   15844:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15845:         values are XML containing access control settings (see below) 
1.747     albertel 15846: 
                   15847: Internal notes:
                   15848: 
1.749     raeburn  15849:  access controls are stored in file_permissions.db as key=value pairs.
                   15850:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15851:         where scope -> public,guest,course,group,domains or users.
                   15852:               end -> UNIX time for end of access (0 -> no end date)
                   15853:               start -> UNIX time for start of access
                   15854: 
                   15855:     value -> XML description of access control
                   15856:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15857:             <start></start>
                   15858:             <end></end>
                   15859: 
                   15860:             <password></password>  for scope type = guest
                   15861: 
                   15862:             <domain></domain>     for scope type = course or group
                   15863:             <number></number>
                   15864:             <roles id="">
                   15865:              <role></role>
                   15866:              <access></access>
                   15867:              <section></section>
                   15868:              <group></group>
                   15869:             </roles>
                   15870: 
                   15871:             <dom></dom>         for scope type = domains
                   15872: 
                   15873:             <users>             for scope type = users
                   15874:              <user>
                   15875:               <uname></uname>
                   15876:               <udom></udom>
                   15877:              </user>
                   15878:             </users>
                   15879:            </scope> 
                   15880:               
                   15881:  Access data is also aggregated for each file in an additional key=value pair:
                   15882:  key -> path to file/file_name\0accesscontrol 
                   15883:  value -> reference to hash
                   15884:           hash contains key = value pairs
                   15885:           where key = uniqueID:scope_end_start
                   15886:                 value = UNIX time record was last updated
                   15887: 
                   15888:           Used to improve speed of look-ups of access controls for each file.  
                   15889:  
                   15890:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15891: 
1.1198    raeburn  15892: =item *
                   15893: 
1.749     raeburn  15894: modify_access_controls():
                   15895: 
                   15896: Modifies access controls for a portfolio file
                   15897: Args
                   15898: 1. file name
                   15899: 2. reference to hash of required changes,
                   15900: 3. domain
                   15901: 4. username
                   15902:   where domain,username are the domain of the portfolio owner 
                   15903:   (either a user or a course) 
                   15904: 
                   15905: Returns:
                   15906: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15907: 2. result of deletions ('ok' or 'error', with error message).
                   15908: 3. reference to hash of any new or updated access controls.
                   15909: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15910:    key = integer (inbound ID)
1.1198    raeburn  15911:    value = uniqueID
                   15912: 
                   15913: =item *
                   15914: 
                   15915: get_timebased_id():
                   15916: 
                   15917: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15918: course via the Course Editor (e.g., folders, composite pages, 
                   15919: group bulletin boards).
                   15920: 
                   15921: Args: (first three required; six others optional)
                   15922: 
                   15923: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15924:    docssequence, or name of group
                   15925: 
                   15926: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15927:    e.g., num, boardids
                   15928: 
                   15929: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15930:    file will be named nohist_namespace.db
                   15931: 
                   15932: 4. cdom: domain of course; default is current course domain from %env
                   15933: 
                   15934: 5. cnum: course number; default is current course number from %env
                   15935: 
                   15936: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15937:    unix timestamp to form the suffix, if the plain timestamp is already
                   15938:    in use.  Default is to not do this, but simply increment the unix 
                   15939:    timestamp by 1 until a unique key is obtained.
                   15940: 
                   15941: 7. who: holder of locking key; defaults to user:domain for user.
                   15942: 
                   15943: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15944:    retrying); default is 3.
                   15945: 
                   15946: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15947: 
                   15948: Returns:
                   15949: 
                   15950: 1. suffix obtained (numeric)
                   15951: 
                   15952: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15953: 
                   15954: 3. error: contains (localized) error message if an error occurred.
                   15955: 
1.747     albertel 15956: 
1.608     albertel 15957: =back
                   15958: 
1.243     albertel 15959: =head2 HTTP Helper Routines
                   15960: 
                   15961: =over 4
                   15962: 
1.191     harris41 15963: =item *
                   15964: 
                   15965: escape() : unpack non-word characters into CGI-compatible hex codes
                   15966: 
                   15967: =item *
                   15968: 
                   15969: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15970: 
1.243     albertel 15971: =back
                   15972: 
                   15973: =head1 PRIVATE SUBROUTINES
                   15974: 
                   15975: =head2 Underlying communication routines (Shouldn't call)
                   15976: 
                   15977: =over 4
                   15978: 
                   15979: =item *
                   15980: 
                   15981: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15982: 
                   15983: =item *
                   15984: 
                   15985: reply() : uses subreply to send a message to remote machine, logs all failures
                   15986: 
                   15987: =item *
                   15988: 
                   15989: critical() : passes a critical message to another server; if cannot
                   15990: get through then place message in connection buffer directory and
                   15991: returns con_delayed, if incapable of saving message, returns
                   15992: con_failed
                   15993: 
                   15994: =item *
                   15995: 
                   15996: reconlonc() : tries to reconnect lonc client processes.
                   15997: 
                   15998: =back
                   15999: 
                   16000: =head2 Resource Access Logging
                   16001: 
                   16002: =over 4
                   16003: 
                   16004: =item *
                   16005: 
                   16006: flushcourselogs() : flush (save) buffer logs and access logs
                   16007: 
                   16008: =item *
                   16009: 
                   16010: courselog($what) : save message for course in hash
                   16011: 
                   16012: =item *
                   16013: 
                   16014: courseacclog($what) : save message for course using &courselog().  Perform
                   16015: special processing for specific resource types (problems, exams, quizzes, etc).
                   16016: 
1.191     harris41 16017: =item *
                   16018: 
                   16019: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16020: as a PerlChildExitHandler
1.243     albertel 16021: 
                   16022: =back
                   16023: 
                   16024: =head2 Other
                   16025: 
                   16026: =over 4
                   16027: 
                   16028: =item *
                   16029: 
                   16030: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16031: 
                   16032: =back
                   16033: 
                   16034: =cut
1.877     foxr     16035: 

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