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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1390  ! raeburn     4: # $Id: lonnet.pm,v 1.1389 2018/11/24 16:19:20 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.5       www       750: # ---------------------------------------------------------- Append Environment
                    751: 
                    752: sub appenv {
1.949     raeburn   753:     my ($newenv,$roles) = @_;
                    754:     if (ref($newenv) eq 'HASH') {
                    755:         foreach my $key (keys(%{$newenv})) {
                    756:             my $refused = 0;
                    757: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    758:                 $refused = 1;
                    759:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   760:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   761:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    762:                         $refused = 0;
                    763:                     }
                    764:                 }
                    765:             }
                    766:             if ($refused) {
                    767:                 &logthis("<font color=\"blue\">WARNING: ".
                    768:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    769:                          .'</font>');
                    770: 	        delete($newenv->{$key});
                    771:             } else {
                    772:                 $env{$key}=$newenv->{$key};
                    773:             }
                    774:         }
1.1376    raeburn   775:         my $lonids = $perlvar{'lonIDsDir'};
                    776:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    777:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    778:             if ($opened
                    779: 	        && &timed_flock($env_file,LOCK_EX)
                    780: 	        &&
                    781: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    782: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    783: 	        while (my ($key,$value) = each(%{$newenv})) {
                    784: 	            $disk_env{$key} = $value;
                    785: 	        }
                    786: 	        untie(%disk_env);
                    787:             }
1.35      www       788:         }
1.191     harris41  789:     }
1.56      www       790:     return 'ok';
                    791: }
                    792: # ----------------------------------------------------- Delete from Environment
                    793: 
                    794: sub delenv {
1.1104    raeburn   795:     my ($delthis,$regexp,$roles) = @_;
                    796:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    797:         my $refused = 1;
                    798:         if (ref($roles) eq 'ARRAY') {
                    799:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    800:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    801:                 $refused = 0;
                    802:             }
                    803:         }
                    804:         if ($refused) {
                    805:             &logthis("<font color=\"blue\">WARNING: ".
                    806:                      "Attempt to delete from environment ".$delthis);
                    807:             return 'error';
                    808:         }
1.56      www       809:     }
1.917     albertel  810:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    811:     if ($opened
1.915     albertel  812: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  813: 	&&
                    814: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    815: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  816: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   817: 	    if ($regexp) {
                    818:                 if ($key=~/^$delthis/) {
                    819:                     delete($env{$key});
                    820:                     delete($disk_env{$key});
                    821:                 } 
                    822:             } else {
                    823:                 if ($key=~/^\Q$delthis\E/) {
                    824: 		    delete($env{$key});
                    825: 		    delete($disk_env{$key});
                    826: 	        }
                    827:             }
1.448     albertel  828: 	}
1.783     albertel  829: 	untie(%disk_env);
1.5       www       830:     }
                    831:     return 'ok';
1.369     albertel  832: }
                    833: 
1.790     albertel  834: sub get_env_multiple {
                    835:     my ($name) = @_;
                    836:     my @values;
                    837:     if (defined($env{$name})) {
                    838:         # exists is it an array
                    839:         if (ref($env{$name})) {
                    840:             @values=@{ $env{$name} };
                    841:         } else {
                    842:             $values[0]=$env{$name};
                    843:         }
                    844:     }
                    845:     return(@values);
                    846: }
                    847: 
1.958     www       848: # ------------------------------------------------------------------- Locking
                    849: 
                    850: sub set_lock {
                    851:     my ($text)=@_;
                    852:     $locknum++;
                    853:     my $id=$$.'-'.$locknum;
                    854:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    855:              'session.lock.'.$id => $text});
                    856:     return $id;
                    857: }
                    858: 
                    859: sub get_locks {
                    860:     my $num=0;
                    861:     my %texts=();
                    862:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    863:        if ($lock=~/\w/) {
                    864:           $num++;
                    865:           $texts{$lock}=$env{'session.lock.'.$lock};
                    866:        }
                    867:    }
                    868:    return ($num,%texts);
                    869: }
                    870: 
                    871: sub remove_lock {
                    872:     my ($id)=@_;
                    873:     my $newlocks='';
                    874:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    875:        if (($lock=~/\w/) && ($lock ne $id)) {
                    876:           $newlocks.=','.$lock;
                    877:        }
                    878:     }
                    879:     &appenv({'session.locks' => $newlocks});
                    880:     &delenv('session.lock.'.$id);
                    881: }
                    882: 
                    883: sub remove_all_locks {
                    884:     my $activelocks=$env{'session.locks'};
                    885:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    886:        if ($lock=~/\w/) {
                    887:           &remove_lock($lock);
                    888:        }
                    889:     }
                    890: }
                    891: 
                    892: 
1.369     albertel  893: # ------------------------------------------ Find out current server userload
                    894: sub userload {
                    895:     my $numusers=0;
                    896:     {
                    897: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    898: 	my $filename;
                    899: 	my $curtime=time;
                    900: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  901: 	    next if ($filename eq '.' || $filename eq '..');
                    902: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390  ! raeburn   903:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  904: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  905: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  906: 	}
                    907: 	closedir(LONIDS);
                    908:     }
                    909:     my $userloadpercent=0;
                    910:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    911:     if ($maxuserload) {
1.371     albertel  912: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  913:     }
1.372     albertel  914:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  915:     return $userloadpercent;
1.283     www       916: }
                    917: 
1.1       albertel  918: # ------------------------------ Find server with least workload from spare.tab
1.11      www       919: 
1.1       albertel  920: sub spareserver {
1.1083    raeburn   921:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  922:     my $spare_server;
1.370     albertel  923:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  924:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    925:                                                      :  $userloadpercent;
1.1083    raeburn   926:     my ($uint_dom,$remotesessions);
                    927:     if (($udom ne '') && (&domain($udom) ne '')) {
                    928:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    929:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    930:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    931:         $remotesessions = $udomdefaults{'remotesessions'};
                    932:     }
1.1123    raeburn   933:     my $spareshash = &this_host_spares($udom);
                    934:     if (ref($spareshash) eq 'HASH') {
                    935:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    936:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   937:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    938:                                              $try_server));
1.1123    raeburn   939: 	        ($spare_server, $lowest_load) =
                    940: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    941:             }
1.1083    raeburn   942:         }
1.784     albertel  943: 
1.1123    raeburn   944:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    945: 
                    946:         if (!$found_server) {
                    947:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    948: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   949:                     next unless (&spare_can_host($udom,$uint_dom,
                    950:                                                  $remotesessions,$try_server));
1.1123    raeburn   951: 	            ($spare_server, $lowest_load) =
                    952: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    953:                 }
                    954: 	    }
                    955:         }
1.784     albertel  956:     }
                    957: 
                    958:     if (!$want_server_name) {
1.968     raeburn   959:         my $protocol = 'http';
                    960:         if ($protocol{$spare_server} eq 'https') {
                    961:             $protocol = $protocol{$spare_server};
                    962:         }
1.1001    raeburn   963:         if (defined($spare_server)) {
                    964:             my $hostname = &hostname($spare_server);
1.1083    raeburn   965:             if (defined($hostname)) {
1.1001    raeburn   966: 	        $spare_server = $protocol.'://'.$hostname;
                    967:             }
                    968:         }
1.784     albertel  969:     }
                    970:     return $spare_server;
                    971: }
                    972: 
                    973: sub compare_server_load {
1.1253    raeburn   974:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    975: 
                    976:     if ($required) {
                    977:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    978:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    979:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    980:         if (($major eq '' && $minor eq '') ||
                    981:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    982:             return ($spare_server,$lowest_load);
                    983:         }
                    984:     }
1.784     albertel  985: 
                    986:     my $loadans     = &reply('load',    $try_server);
                    987:     my $userloadans = &reply('userload',$try_server);
                    988: 
                    989:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   990: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  991:     }
                    992: 
                    993:     my $load;
                    994:     if ($loadans =~ /\d/) {
                    995: 	if ($userloadans =~ /\d/) {
                    996: 	    #both are numbers, pick the bigger one
                    997: 	    $load = ($loadans > $userloadans) ? $loadans 
                    998: 		                              : $userloadans;
1.411     albertel  999: 	} else {
1.784     albertel 1000: 	    $load = $loadans;
1.411     albertel 1001: 	}
1.784     albertel 1002:     } else {
                   1003: 	$load = $userloadans;
                   1004:     }
                   1005: 
                   1006:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1007: 	$spare_server = $try_server;
                   1008: 	$lowest_load  = $load;
1.370     albertel 1009:     }
1.784     albertel 1010:     return ($spare_server,$lowest_load);
1.202     matthew  1011: }
1.914     albertel 1012: 
                   1013: # --------------------------- ask offload servers if user already has a session
                   1014: sub find_existing_session {
                   1015:     my ($udom,$uname) = @_;
1.1123    raeburn  1016:     my $spareshash = &this_host_spares($udom);
                   1017:     if (ref($spareshash) eq 'HASH') {
                   1018:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1019:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1020:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1021:             }
                   1022:         }
                   1023:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1024:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1025:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1026:             }
                   1027:         }
1.914     albertel 1028:     }
                   1029:     return;
                   1030: }
                   1031: 
1.1389    raeburn  1032: # check if user's browser sent load balancer cookie and server still has session
                   1033: # and is not overloaded.
                   1034: sub check_for_balancer_cookie {
                   1035:     my ($r,$update_mtime) = @_;
                   1036:     my ($otherserver,$cookie);
                   1037:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1038:     if (exists($cookies{'balanceID'})) {
                   1039:         my $balid = $cookies{'balanceID'};
                   1040:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1041:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1042:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1043:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1044:                 my ($possudom,$possuname) = ($1,$2);
                   1045:                 my $has_session = 0;
                   1046:                 if ((&domain($possudom) ne '') &&
                   1047:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1048:                     my $try_server;
                   1049:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1050:                     if ($opened) {
                   1051:                         flock($idf,LOCK_SH);
                   1052:                         while (my $line = <$idf>) {
                   1053:                             chomp($line);
                   1054:                             if (&hostname($line) ne '') {
                   1055:                                 $try_server = $line;
                   1056:                                 last;
                   1057:                             }
                   1058:                         }
                   1059:                         close($idf);
                   1060:                         if (($try_server) &&
                   1061:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1062:                             my $lowest_load = 30000;
                   1063:                             ($otherserver,$lowest_load) =
                   1064:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1065:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1066:                                 $has_session = 1;
                   1067:                             } else {
                   1068:                                 undef($otherserver);
                   1069:                             }
                   1070:                         }
                   1071:                     }
                   1072:                 }
                   1073:                 if ($has_session) {
                   1074:                     if ($update_mtime) {
                   1075:                         my $atime = my $mtime = time;
                   1076:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1077:                     }
                   1078:                 } else {
                   1079:                     unlink("$balancedir/$cookie.id");
                   1080:                 }
                   1081:             }
                   1082:         }
                   1083:     }
                   1084:     return ($otherserver,$cookie);
                   1085: }
                   1086: 
                   1087: sub delbalcookie {
                   1088:     my ($cookie,$balancer) =@_;
                   1089:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1090:         my ($udom,$uname) = ($1,$2);
                   1091:         my $uprimary_id = &domain($udom,'primary');
                   1092:         my $uintdom = &internet_dom($uprimary_id);
                   1093:         my $intdom = &internet_dom($balancer);
                   1094:         my $serverhomedom = &host_domain($balancer);
                   1095:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1096:             return &reply("delbalcookie:$cookie",$balancer);
                   1097:         }
                   1098:     }
                   1099: }
                   1100: 
1.914     albertel 1101: # -------------------------------- ask if server already has a session for user
                   1102: sub has_user_session {
                   1103:     my ($lonid,$udom,$uname) = @_;
                   1104:     my $result = &reply(join(':','userhassession',
                   1105: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1106:     return 1 if ($result eq 'ok');
                   1107: 
                   1108:     return 0;
                   1109: }
                   1110: 
1.1076    raeburn  1111: # --------- determine least loaded server in a user's domain which allows login
                   1112: 
                   1113: sub choose_server {
1.1259    raeburn  1114:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1115:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1116:     my %servers = &get_servers($udom);
1.1076    raeburn  1117:     my $lowest_load = 30000;
1.1259    raeburn  1118:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1119:     if ($skiploadbal) {
                   1120:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1121:         unless (defined($cached)) {
                   1122:             my $cachetime = 60*60*24;
                   1123:             my %domconfig =
                   1124:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1125:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1126:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1127:                                            $cachetime);
                   1128:             }
                   1129:         }
                   1130:     }
1.1076    raeburn  1131:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1132:         if ($skiploadbal) {
                   1133:             if (ref($balancers) eq 'HASH') {
                   1134:                 next if (exists($balancers->{$lonhost}));
                   1135:             }
1.1389    raeburn  1136:         }
1.1115    raeburn  1137:         my $loginvia;
                   1138:         if ($checkloginvia) {
                   1139:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1140:             if ($loginvia) {
                   1141:                 my ($server,$path) = split(/:/,$loginvia);
                   1142:                 ($login_host, $lowest_load) =
1.1253    raeburn  1143:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1144:                 if ($login_host eq $server) {
                   1145:                     $portal_path = $path;
1.1151    raeburn  1146:                     $isredirect = 1;
1.1116    raeburn  1147:                 }
                   1148:             } else {
                   1149:                 ($login_host, $lowest_load) =
1.1253    raeburn  1150:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1151:                 if ($login_host eq $lonhost) {
                   1152:                     $portal_path = '';
1.1151    raeburn  1153:                     $isredirect = ''; 
1.1116    raeburn  1154:                 }
                   1155:             }
                   1156:         } else {
1.1076    raeburn  1157:             ($login_host, $lowest_load) =
1.1253    raeburn  1158:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1159:         }
                   1160:     }
                   1161:     if ($login_host ne '') {
1.1116    raeburn  1162:         $hostname = &hostname($login_host);
1.1076    raeburn  1163:     }
1.1331    raeburn  1164:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1165: }
                   1166: 
1.202     matthew  1167: # --------------------------------------------- Try to change a user's password
                   1168: 
                   1169: sub changepass {
1.799     raeburn  1170:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1171:     $currentpass = &escape($currentpass);
                   1172:     $newpass     = &escape($newpass);
1.1030    raeburn  1173:     my $lonhost = $perlvar{'lonHostID'};
                   1174:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1175: 		       $server);
                   1176:     if (! $answer) {
                   1177: 	&logthis("No reply on password change request to $server ".
                   1178: 		 "by $uname in domain $udom.");
                   1179:     } elsif ($answer =~ "^ok") {
                   1180:         &logthis("$uname in $udom successfully changed their password ".
                   1181: 		 "on $server.");
                   1182:     } elsif ($answer =~ "^pwchange_failure") {
                   1183: 	&logthis("$uname in $udom was unable to change their password ".
                   1184: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1185: 		 "or pwchange");
                   1186:     } elsif ($answer =~ "^non_authorized") {
                   1187:         &logthis("$uname in $udom did not get their password correct when ".
                   1188: 		 "attempting to change it on $server.");
                   1189:     } elsif ($answer =~ "^auth_mode_error") {
                   1190:         &logthis("$uname in $udom attempted to change their password despite ".
                   1191: 		 "not being locally or internally authenticated on $server.");
                   1192:     } elsif ($answer =~ "^unknown_user") {
                   1193:         &logthis("$uname in $udom attempted to change their password ".
                   1194: 		 "on $server but were unable to because $server is not ".
                   1195: 		 "their home server.");
                   1196:     } elsif ($answer =~ "^refused") {
                   1197: 	&logthis("$server refused to change $uname in $udom password because ".
                   1198: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1199:     } elsif ($answer =~ "invalid_client") {
                   1200:         &logthis("$server refused to change $uname in $udom password because ".
                   1201:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1202:     }
                   1203:     return $answer;
1.1       albertel 1204: }
                   1205: 
1.169     harris41 1206: # ----------------------- Try to determine user's current authentication scheme
                   1207: 
                   1208: sub queryauthenticate {
                   1209:     my ($uname,$udom)=@_;
1.456     albertel 1210:     my $uhome=&homeserver($uname,$udom);
                   1211:     if (!$uhome) {
                   1212: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1213: 	return 'no_host';
                   1214:     }
                   1215:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1216:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1217: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1218:     }
1.456     albertel 1219:     return $answer;
1.169     harris41 1220: }
                   1221: 
1.1       albertel 1222: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1223: 
1.1       albertel 1224: sub authenticate {
1.1073    raeburn  1225:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1226:     $upass=&escape($upass);
                   1227:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1228:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1229:     my $newhome;
1.836     www      1230:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1231: # Maybe the machine was offline and only re-appeared again recently?
                   1232:         &reconlonc();
                   1233: # One more
1.952     raeburn  1234: 	$uhome=&homeserver($uname,$udom,1);
                   1235:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1236:             if (defined(&domain($udom,'primary'))) {
                   1237:                 $newhome=&domain($udom,'primary');
                   1238:             }
                   1239:             if ($newhome ne '') {
                   1240:                 $uhome = $newhome;
                   1241:             }
                   1242:         }
1.836     www      1243: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1244: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1245: 	    return 'no_host';
                   1246:         }
1.1       albertel 1247:     }
1.1073    raeburn  1248:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1249:     if ($answer eq 'authorized') {
1.952     raeburn  1250:         if ($newhome) {
                   1251:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1252:             return 'no_account_on_host'; 
                   1253:         } else {
                   1254:             &logthis("User $uname at $udom authorized by $uhome");
                   1255:             return $uhome;
                   1256:         }
1.471     albertel 1257:     }
                   1258:     if ($answer eq 'non_authorized') {
                   1259: 	&logthis("User $uname at $udom rejected by $uhome");
                   1260: 	return 'no_host'; 
1.9       www      1261:     }
1.471     albertel 1262:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1263:     return 'no_host';
                   1264: }
                   1265: 
1.1073    raeburn  1266: sub can_host_session {
1.1074    raeburn  1267:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1268:     my $canhost = 1;
1.1074    raeburn  1269:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1270:     if (ref($remotesessions) eq 'HASH') {
                   1271:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1272:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1273:                 $canhost = 0;
                   1274:             } else {
                   1275:                 $canhost = 1;
                   1276:             }
                   1277:         }
                   1278:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1279:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1280:                 $canhost = 1;
                   1281:             } else {
                   1282:                 $canhost = 0;
                   1283:             }
                   1284:         }
                   1285:         if ($canhost) {
                   1286:             if ($remotesessions->{'version'} ne '') {
                   1287:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1288:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1289:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1290:                         my $major = $1;
                   1291:                         my $minor = $2;
                   1292:                         if (($major < $reqmajor ) ||
                   1293:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1294:                             $canhost = 0;
                   1295:                         }
                   1296:                     } else {
                   1297:                         $canhost = 0;
                   1298:                     }
                   1299:                 }
                   1300:             }
                   1301:         }
                   1302:     }
                   1303:     if ($canhost) {
                   1304:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1305:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1306:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1307:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1308:                 if (($uint_dom ne '') && 
                   1309:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1310:                     $canhost = 0;
                   1311:                 } else {
                   1312:                     $canhost = 1;
                   1313:                 }
                   1314:             }
                   1315:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1316:                 if (($uint_dom ne '') && 
                   1317:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1318:                     $canhost = 1;
                   1319:                 } else {
                   1320:                     $canhost = 0;
                   1321:                 }
                   1322:             }
                   1323:         }
                   1324:     }
                   1325:     return $canhost;
                   1326: }
                   1327: 
1.1083    raeburn  1328: sub spare_can_host {
                   1329:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1330:     my $canhost=1;
1.1279    raeburn  1331:     my $try_server_hostname = &hostname($try_server);
                   1332:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1333:     my $serverhomedom = &host_domain($serverhomeID);
                   1334:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1335:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1336:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1337:             $canhost = 0;
                   1338:         }
                   1339:     }
                   1340:     if (($canhost) && ($uint_dom)) {
                   1341:         my @intdoms;
                   1342:         my $internet_names = &get_internet_names($try_server);
                   1343:         if (ref($internet_names) eq 'ARRAY') {
                   1344:             @intdoms = @{$internet_names};
                   1345:         }
                   1346:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1347:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1348:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1349:                                          $remotesessions,
                   1350:                                          $defdomdefaults{'hostedsessions'});
                   1351:         }
1.1083    raeburn  1352:     }
                   1353:     return $canhost;
                   1354: }
                   1355: 
1.1123    raeburn  1356: sub this_host_spares {
                   1357:     my ($dom) = @_;
1.1126    raeburn  1358:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1359:     my @hosts = &current_machine_ids();
                   1360:     foreach my $lonhost (@hosts) {
                   1361:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1362:             $dom_in_use = $dom;
                   1363:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1364:             last;
                   1365:         }
                   1366:     }
1.1126    raeburn  1367:     if ($dom_in_use ne '') {
                   1368:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1369:     }
                   1370:     if (ref($result) ne 'HASH') {
                   1371:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1372:         $dom_in_use = &host_domain($lonhost_in_use);
                   1373:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1374:         if (ref($result) ne 'HASH') {
                   1375:             $result = \%spareid;
                   1376:         }
                   1377:     }
                   1378:     return $result;
                   1379: }
                   1380: 
                   1381: sub spares_for_offload  {
                   1382:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1383:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1384:     if (defined($cached)) {
                   1385:         return $result;
                   1386:     } else {
1.1126    raeburn  1387:         my $cachetime = 60*60*24;
                   1388:         my %domconfig =
                   1389:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1390:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1391:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1392:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1393:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1394:                 }
                   1395:             }
                   1396:         }
                   1397:     }
1.1126    raeburn  1398:     return;
1.1123    raeburn  1399: }
                   1400: 
1.1129    raeburn  1401: sub get_lonbalancer_config {
                   1402:     my ($servers) = @_;
                   1403:     my ($currbalancer,$currtargets);
                   1404:     if (ref($servers) eq 'HASH') {
                   1405:         foreach my $server (keys(%{$servers})) {
                   1406:             my %what = (
                   1407:                          spareid => 1,
                   1408:                          perlvar => 1,
                   1409:                        );
                   1410:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1411:             if ($result eq 'ok') {
                   1412:                 if (ref($returnhash) eq 'HASH') {
                   1413:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1414:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1415:                             $currbalancer = $server;
                   1416:                             $currtargets = {};
                   1417:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1418:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1419:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1420:                                 }
                   1421:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1422:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1423:                                 }
                   1424:                             }
                   1425:                             last;
                   1426:                         }
                   1427:                     }
                   1428:                 }
                   1429:             }
                   1430:         }
                   1431:     }
                   1432:     return ($currbalancer,$currtargets);
                   1433: }
                   1434: 
                   1435: sub check_loadbalancing {
1.1331    raeburn  1436:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1437:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1389    raeburn  1438:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1439:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1440:     my @hosts = &current_machine_ids();
1.1129    raeburn  1441:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1442:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1443:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1444:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1445:     my $domneedscache;
1.1129    raeburn  1446:     my $cachetime = 60*60*24;
                   1447: 
                   1448:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1449:         $dom_in_use = $udom;
                   1450:         $homeintdom = 1;
                   1451:     } else {
                   1452:         $dom_in_use = $serverhomedom;
                   1453:     }
                   1454:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1455:     unless (defined($cached)) {
                   1456:         my %domconfig =
                   1457:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1458:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1459:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1460:         } else {
                   1461:             $domneedscache = $dom_in_use;
1.1129    raeburn  1462:         }
                   1463:     }
                   1464:     if (ref($result) eq 'HASH') {
1.1389    raeburn  1465:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1191    raeburn  1466:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1467:         if ($is_balancer) {
                   1468:             if (ref($currrules) eq 'HASH') {
                   1469:                 if ($homeintdom) {
                   1470:                     if ($uname ne '') {
                   1471:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1472:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1473:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1474:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1475:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1476:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1477:                             }
                   1478:                         }
                   1479:                         if ($rule_in_effect eq '') {
                   1480:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1481:                             if ($userenv{'inststatus'} ne '') {
                   1482:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1483:                                 my ($othertitle,$usertypes,$types) =
                   1484:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1485:                                 if (ref($types) eq 'ARRAY') {
                   1486:                                     foreach my $type (@{$types}) {
                   1487:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1488:                                             if (exists($currrules->{$type})) {
                   1489:                                                 $rule_in_effect = $currrules->{$type};
                   1490:                                             }
                   1491:                                         }
                   1492:                                     }
                   1493:                                 }
                   1494:                             } else {
                   1495:                                 if (exists($currrules->{'default'})) {
                   1496:                                     $rule_in_effect = $currrules->{'default'};
                   1497:                                 }
                   1498:                             }
                   1499:                         }
                   1500:                     } else {
                   1501:                         if (exists($currrules->{'default'})) {
                   1502:                             $rule_in_effect = $currrules->{'default'};
                   1503:                         }
                   1504:                     }
                   1505:                 } else {
                   1506:                     if ($currrules->{'_LC_external'} ne '') {
                   1507:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1508:                     }
                   1509:                 }
                   1510:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1511:                                                        $uname,$udom);
                   1512:             }
                   1513:         }
                   1514:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1515:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1516:         unless (defined($cached)) {
                   1517:             my %domconfig =
                   1518:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1519:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1520:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1521:             } else {
                   1522:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1523:             }
                   1524:         }
                   1525:         if (ref($result) eq 'HASH') {
1.1389    raeburn  1526:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1191    raeburn  1527:                 &check_balancer_result($result,@hosts);
                   1528:             if ($is_balancer) {
1.1129    raeburn  1529:                 if (ref($currrules) eq 'HASH') {
                   1530:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1531:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1532:                     }
                   1533:                 }
                   1534:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1535:                                                        $uname,$udom);
                   1536:             }
                   1537:         } else {
                   1538:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1539:                 $is_balancer = 1;
                   1540:                 $offloadto = &this_host_spares($dom_in_use);
                   1541:             }
1.1307    raeburn  1542:             unless (defined($cached)) {
                   1543:                 $domneedscache = $serverhomedom;
                   1544:             }
1.1129    raeburn  1545:         }
                   1546:     } else {
                   1547:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1548:             $is_balancer = 1;
                   1549:             $offloadto = &this_host_spares($dom_in_use);
                   1550:         }
1.1307    raeburn  1551:         unless (defined($cached)) {
                   1552:             $domneedscache = $serverhomedom;
                   1553:         }
                   1554:     }
                   1555:     if ($domneedscache) {
                   1556:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1557:     }
1.1176    raeburn  1558:     if ($is_balancer) {
                   1559:         my $lowest_load = 30000;
                   1560:         if (ref($offloadto) eq 'HASH') {
                   1561:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1562:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1563:                     ($otherserver,$lowest_load) =
                   1564:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1565:                 }
1.1129    raeburn  1566:             }
1.1176    raeburn  1567:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1568: 
1.1176    raeburn  1569:             if (!$found_server) {
                   1570:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1571:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1572:                         ($otherserver,$lowest_load) =
                   1573:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1574:                     }
                   1575:                 }
                   1576:             }
                   1577:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1578:             if (@{$offloadto} == 1) {
                   1579:                 $otherserver = $offloadto->[0];
                   1580:             } elsif (@{$offloadto} > 1) {
                   1581:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1582:                     ($otherserver,$lowest_load) =
                   1583:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1584:                 }
                   1585:             }
                   1586:         }
1.1331    raeburn  1587:         unless ($caller eq 'login') {
                   1588:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1589:                 $is_balancer = 0;
                   1590:                 if ($uname ne '' && $udom ne '') {
                   1591:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1592:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1593:                                  'user.loadbalcheck.time' => time});
                   1594:                     }
1.1176    raeburn  1595:                 }
1.1129    raeburn  1596:             }
                   1597:         }
1.1389    raeburn  1598:         unless ($homeintdom) {
                   1599:             undef($setcookie);
                   1600:         }
1.1129    raeburn  1601:     }
1.1389    raeburn  1602:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1603: }
                   1604: 
1.1191    raeburn  1605: sub check_balancer_result {
                   1606:     my ($result,@hosts) = @_;
1.1389    raeburn  1607:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1191    raeburn  1608:     if (ref($result) eq 'HASH') {
                   1609:         if ($result->{'lonhost'} ne '') {
                   1610:             my $currbalancer = $result->{'lonhost'};
                   1611:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1612:                 $is_balancer = 1;
                   1613:                 $currtargets = $result->{'targets'};
                   1614:                 $currrules = $result->{'rules'};
                   1615:             }
                   1616:         } else {
                   1617:             foreach my $key (keys(%{$result})) {
                   1618:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1619:                     (ref($result->{$key}) eq 'HASH')) {
                   1620:                     $is_balancer = 1;
                   1621:                     $currrules = $result->{$key}{'rules'};
                   1622:                     $currtargets = $result->{$key}{'targets'};
1.1389    raeburn  1623:                     $setcookie = $result->{$key}{'cookie'};
1.1191    raeburn  1624:                     last;
                   1625:                 }
                   1626:             }
                   1627:         }
                   1628:     }
1.1389    raeburn  1629:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1191    raeburn  1630: }
                   1631: 
1.1129    raeburn  1632: sub get_loadbalancer_targets {
                   1633:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1634:     my $offloadto;
1.1175    raeburn  1635:     if ($rule_in_effect eq 'none') {
                   1636:         return [$perlvar{'lonHostID'}];
                   1637:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1638:         $offloadto = $currtargets;
                   1639:     } else {
                   1640:         if ($rule_in_effect eq 'homeserver') {
                   1641:             my $homeserver = &homeserver($uname,$udom);
                   1642:             if ($homeserver ne 'no_host') {
                   1643:                 $offloadto = [$homeserver];
                   1644:             }
                   1645:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1646:             my %domconfig =
                   1647:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1648:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1649:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1650:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1651:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1652:                     }
                   1653:                 }
                   1654:             } else {
1.1178    raeburn  1655:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1656:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1657:                 if (&hostname($remotebalancer) ne '') {
                   1658:                     $offloadto = [$remotebalancer];
                   1659:                 }
                   1660:             }
                   1661:         } elsif (&hostname($rule_in_effect) ne '') {
                   1662:             $offloadto = [$rule_in_effect];
                   1663:         }
                   1664:     }
                   1665:     return $offloadto;
                   1666: }
                   1667: 
1.1127    raeburn  1668: sub internet_dom_servers {
                   1669:     my ($dom) = @_;
                   1670:     my (%uniqservers,%servers);
                   1671:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1672:     my @machinedoms = &machine_domains($primaryserver);
                   1673:     foreach my $mdom (@machinedoms) {
                   1674:         my %currservers = %servers;
                   1675:         my %server = &get_servers($mdom);
                   1676:         %servers = (%currservers,%server);
                   1677:     }
                   1678:     my %by_hostname;
                   1679:     foreach my $id (keys(%servers)) {
                   1680:         push(@{$by_hostname{$servers{$id}}},$id);
                   1681:     }
                   1682:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1683:         if (@{$by_hostname{$hostname}} > 1) {
                   1684:             my $match = 0;
                   1685:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1686:                 if (&host_domain($id) eq $dom) {
                   1687:                     $uniqservers{$id} = $hostname;
                   1688:                     $match = 1;
                   1689:                 }
                   1690:             }
                   1691:             unless ($match) {
                   1692:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1693:             }
                   1694:         } else {
                   1695:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1696:         }
                   1697:     }
                   1698:     return %uniqservers;
                   1699: }
                   1700: 
1.1347    raeburn  1701: sub trusted_domains {
                   1702:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1703:     my ($trusted,$untrusted);
1.1347    raeburn  1704:     if (&domain($calldom) eq '') {
1.1349    raeburn  1705:         return ($trusted,$untrusted);
1.1347    raeburn  1706:     }
                   1707:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1708:         return ($trusted,$untrusted);
1.1347    raeburn  1709:     }
                   1710:     my $callprimary = &domain($calldom,'primary');
                   1711:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1712:     if ($intcalldom eq '') {
1.1349    raeburn  1713:         return ($trusted,$untrusted);
1.1347    raeburn  1714:     }
                   1715: 
                   1716:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1717:     unless (defined($cached)) {
                   1718:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1719:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1720:         $trustconfig = $domconfig{'trust'};
                   1721:     }
                   1722:     if (ref($trustconfig)) {
                   1723:         my (%possexc,%possinc,@allexc,@allinc); 
                   1724:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1725:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1726:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1727:             }
                   1728:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1729:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1730:             }
                   1731:         }
                   1732:         if (keys(%possexc)) {
                   1733:             if (keys(%possinc)) {
                   1734:                 foreach my $key (sort(keys(%possexc))) {
                   1735:                     next if ($key eq $intcalldom);
                   1736:                     unless ($possinc{$key}) {
                   1737:                         push(@allexc,$key);
                   1738:                     }
                   1739:                 }
                   1740:             } else {
                   1741:                 @allexc = sort(keys(%possexc));
                   1742:             }
                   1743:         }
                   1744:         if (keys(%possinc)) {
                   1745:             $possinc{$intcalldom} = 1;
                   1746:             @allinc = sort(keys(%possinc));
                   1747:         }
                   1748:         if ((@allexc > 0) || (@allinc > 0)) {
                   1749:             my %doms_by_intdom;
                   1750:             my %allintdoms = &all_host_intdom();
                   1751:             my %alldoms = &all_host_domain();
                   1752:             foreach my $key (%allintdoms) {
                   1753:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1754:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1755:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1756:                     }
                   1757:                 } else {
                   1758:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1759:                 }
                   1760:             }
                   1761:             foreach my $exc (@allexc) {
                   1762:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349    raeburn  1763:                     $untrusted = $doms_by_intdom{$exc};
1.1347    raeburn  1764:                 }
                   1765:             }
                   1766:             foreach my $inc (@allinc) {
                   1767:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349    raeburn  1768:                     $trusted = $doms_by_intdom{$inc};
1.1347    raeburn  1769:                 }
                   1770:             }
                   1771:         }
                   1772:     }
1.1349    raeburn  1773:     return ($trusted,$untrusted);
1.1347    raeburn  1774: }
                   1775: 
                   1776: sub will_trust {
                   1777:     my ($cmdtype,$domain,$possdom) = @_;
                   1778:     return 1 if ($domain eq $possdom);
                   1779:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1780:     my $willtrust; 
                   1781:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1782:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1783:             $willtrust = 1;
                   1784:         }
                   1785:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1786:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1787:             $willtrust = 1;
                   1788:         }
                   1789:     } else {
                   1790:         $willtrust = 1;
                   1791:     }
                   1792:     return $willtrust;
                   1793: }
                   1794: 
1.1       albertel 1795: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1796: 
1.599     albertel 1797: my %homecache;
1.1       albertel 1798: sub homeserver {
1.230     stredwic 1799:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1800:     my $index="$uname:$udom";
1.426     albertel 1801: 
1.599     albertel 1802:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1803: 
                   1804:     my %servers = &get_servers($udom,'library');
                   1805:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1806:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1807: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1808: 
                   1809: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1810: 	if ($answer eq 'found') {
                   1811: 	    delete($badServerCache{$tryserver}); 
                   1812: 	    return $homecache{$index}=$tryserver;
                   1813: 	} elsif ($answer eq 'no_host') {
                   1814: 	    $badServerCache{$tryserver}=1;
                   1815: 	}
1.1       albertel 1816:     }    
                   1817:     return 'no_host';
1.70      www      1818: }
                   1819: 
1.1300    raeburn  1820: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1821: 
                   1822: sub idget {
1.1300    raeburn  1823:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1824:     my %returnhash=();
1.1300    raeburn  1825:     my @ids=(); 
                   1826:     if (ref($idsref) eq 'ARRAY') {
                   1827:         @ids = @{$idsref};
                   1828:     } else {
                   1829:         return %returnhash; 
                   1830:     }
                   1831:     if ($namespace eq '') {
                   1832:         $namespace = 'ids';
                   1833:     }
1.70      www      1834:     
1.841     albertel 1835:     my %servers = &get_servers($udom,'library');
                   1836:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1837: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1838: 	if ($namespace eq 'ids') {
                   1839: 	    $idlist=~tr/A-Z/a-z/;
                   1840: 	}
                   1841: 	my $reply;
                   1842: 	if ($namespace eq 'ids') {
                   1843: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1844: 	} else {
                   1845: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1846: 	}
1.841     albertel 1847: 	my @answer=();
                   1848: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1849: 	    @answer=split(/\&/,$reply);
                   1850: 	}                    ;
                   1851: 	my $i;
                   1852: 	for ($i=0;$i<=$#ids;$i++) {
                   1853: 	    if ($answer[$i]) {
1.1299    raeburn  1854: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1855: 	    }
1.841     albertel 1856: 	}
1.1300    raeburn  1857:     }
1.70      www      1858:     return %returnhash;
                   1859: }
                   1860: 
                   1861: # ------------------------------------- Find the IDs behind a list of usernames
                   1862: 
                   1863: sub idrget {
                   1864:     my ($udom,@unames)=@_;
                   1865:     my %returnhash=();
1.800     albertel 1866:     foreach my $uname (@unames) {
                   1867:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1868:     }
1.70      www      1869:     return %returnhash;
                   1870: }
                   1871: 
1.1300    raeburn  1872: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1873: 
                   1874: sub idput {
1.1300    raeburn  1875:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1876:     my %servers=();
1.1300    raeburn  1877:     my %ids=();
                   1878:     my %byid = ();
                   1879:     if (ref($idsref) eq 'HASH') {
                   1880:         %ids=%{$idsref};
                   1881:     }
                   1882:     if ($namespace eq '') {
                   1883:         $namespace = 'ids'; 
                   1884:     }
1.800     albertel 1885:     foreach my $uname (keys(%ids)) {
                   1886: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1887:         if ($uhom eq '') {
                   1888:             $uhom=&homeserver($uname,$udom);
                   1889:         }
1.70      www      1890:         if ($uhom ne 'no_host') {
1.800     albertel 1891:             my $esc_unam=&escape($uname);
1.1300    raeburn  1892:             if ($namespace eq 'ids') {
                   1893:                 my $id=&escape($ids{$uname});
                   1894:                 $id=~tr/A-Z/a-z/;
                   1895:                 my $esc_unam=&escape($uname);
                   1896:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1897:             } else {
1.1300    raeburn  1898:                 my @currids = split(/,/,$ids{$uname});
                   1899:                 foreach my $id (@currids) {
                   1900:                     $byid{$uhom}{$id} .= $uname.',';
                   1901:                 }
                   1902:             }
                   1903:         }
                   1904:     }
                   1905:     if ($namespace eq 'clickers') {
                   1906:         foreach my $server (keys(%byid)) {
                   1907:             if (ref($byid{$server}) eq 'HASH') {
                   1908:                 foreach my $id (keys(%{$byid{$server}})) {
                   1909:                     $byid{$server} =~ s/,$//;
                   1910:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1911:                 }
1.70      www      1912:             }
                   1913:         }
1.191     harris41 1914:     }
1.800     albertel 1915:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1916:         $servers{$server} =~ s/\&$//;
                   1917:         if ($namespace eq 'ids') {     
                   1918:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1919:         } else {
                   1920:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1921:         }
1.191     harris41 1922:     }
1.344     www      1923: }
                   1924: 
1.1300    raeburn  1925: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1926: 
                   1927: sub iddel {
1.1300    raeburn  1928:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1929:     my %result=();
1.1300    raeburn  1930:     my %ids=();
                   1931:     my %byid = ();
                   1932:     if (ref($idshashref) eq 'HASH') {
                   1933:         %ids=%{$idshashref};
                   1934:     } else {
1.1231    raeburn  1935:         return %result;
                   1936:     }
1.1300    raeburn  1937:     if ($namespace eq '') {
                   1938:         $namespace = 'ids';
                   1939:     }
1.1231    raeburn  1940:     my %servers=();
1.1300    raeburn  1941:     while (my ($id,$unamestr) = each(%ids)) {
                   1942:         if ($namespace eq 'ids') {
                   1943:             my $uhom = $uhome;
                   1944:             if ($uhom eq '') { 
                   1945:                 $uhom=&homeserver($unamestr,$udom);
                   1946:             }
                   1947:             if ($uhom ne 'no_host') {
                   1948:                 $servers{$uhom}.='&'.&escape($id);
                   1949:             }
                   1950:          } else {
                   1951:             my @curritems = split(/,/,$ids{$id});
                   1952:             foreach my $uname (@curritems) {
                   1953:                 my $uhom = $uhome;
                   1954:                 if ($uhom eq '') {
                   1955:                     $uhom=&homeserver($uname,$udom);
                   1956:                 }
                   1957:                 if ($uhom ne 'no_host') { 
                   1958:                     $byid{$uhom}{$id} .= $uname.',';
                   1959:                 }
                   1960:             }
1.1231    raeburn  1961:         }
1.1300    raeburn  1962:     }
                   1963:     if ($namespace eq 'clickers') {
                   1964:         foreach my $server (keys(%byid)) {
                   1965:             if (ref($byid{$server}) eq 'HASH') {
                   1966:                 foreach my $id (keys(%{$byid{$server}})) {
                   1967:                     $byid{$server}{$id} =~ s/,$//;
                   1968:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1969:                 }
1.1231    raeburn  1970:             }
                   1971:         }
                   1972:     }
                   1973:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1974:         $servers{$server} =~ s/\&$//;
                   1975:         if ($namespace eq 'ids') {
                   1976:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1977:         } elsif ($namespace eq 'clickers') {
                   1978:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1979:         }
1.1231    raeburn  1980:     }
                   1981:     return %result;
                   1982: }
                   1983: 
1.1300    raeburn  1984: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1985: 
                   1986: sub updateclickers {
                   1987:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1988:     my %clickers;
                   1989:     if (ref($idshashref) eq 'HASH') {
                   1990:         %clickers=%{$idshashref};
                   1991:     } else {
                   1992:         return;
                   1993:     }
                   1994:     my $items='';
                   1995:     foreach my $item (keys(%clickers)) {
                   1996:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1997:     }
                   1998:     $items=~s/\&$//;
                   1999:     my $request = "updateclickers:$udom:$action:$items";
                   2000:     if ($critical) {
                   2001:         return &critical($request,$uhome);
                   2002:     } else {
                   2003:         return &reply($request,$uhome);
                   2004:     }
                   2005: }
                   2006: 
1.1023    raeburn  2007: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2008: sub dump_dom {
1.1165    droeschl 2009:     my ($namespace, $udom, $regexp) = @_;
                   2010: 
                   2011:     $udom ||= $env{'user.domain'};
                   2012: 
                   2013:     return () unless $udom;
                   2014: 
                   2015:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2016: }
                   2017: 
1.1023    raeburn  2018: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2019: 
                   2020: sub get_dom {
1.860     raeburn  2021:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2022:     return if ($udom eq 'public');
1.806     raeburn  2023:     my $items='';
                   2024:     foreach my $item (@$storearr) {
                   2025:         $items.=&escape($item).'&';
                   2026:     }
                   2027:     $items=~s/\&$//;
1.860     raeburn  2028:     if (!$udom) {
                   2029:         $udom=$env{'user.domain'};
1.1267    raeburn  2030:         return if ($udom eq 'public');
1.860     raeburn  2031:         if (defined(&domain($udom,'primary'))) {
                   2032:             $uhome=&domain($udom,'primary');
                   2033:         } else {
1.874     albertel 2034:             undef($uhome);
1.860     raeburn  2035:         }
                   2036:     } else {
                   2037:         if (!$uhome) {
                   2038:             if (defined(&domain($udom,'primary'))) {
                   2039:                 $uhome=&domain($udom,'primary');
                   2040:             }
                   2041:         }
                   2042:     }
                   2043:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2044:         my $rep;
                   2045:         if ($namespace =~ /^enc/) {
                   2046:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2047:         } else {
                   2048:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2049:         }
1.866     raeburn  2050:         my %returnhash;
1.875     albertel 2051:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2052:             return %returnhash;
                   2053:         }
1.806     raeburn  2054:         my @pairs=split(/\&/,$rep);
                   2055:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2056:             return @pairs;
                   2057:         }
                   2058:         my $i=0;
                   2059:         foreach my $item (@$storearr) {
                   2060:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2061:             $i++;
                   2062:         }
                   2063:         return %returnhash;
                   2064:     } else {
1.880     banghart 2065:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2066:     }
                   2067: }
                   2068: 
                   2069: # -------------------------------------------- put items in domain db files 
                   2070: 
                   2071: sub put_dom {
1.860     raeburn  2072:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2073:     if (!$udom) {
                   2074:         $udom=$env{'user.domain'};
                   2075:         if (defined(&domain($udom,'primary'))) {
                   2076:             $uhome=&domain($udom,'primary');
                   2077:         } else {
1.874     albertel 2078:             undef($uhome);
1.860     raeburn  2079:         }
                   2080:     } else {
                   2081:         if (!$uhome) {
                   2082:             if (defined(&domain($udom,'primary'))) {
                   2083:                 $uhome=&domain($udom,'primary');
                   2084:             }
                   2085:         }
                   2086:     } 
                   2087:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2088:         my $items='';
                   2089:         foreach my $item (keys(%$storehash)) {
                   2090:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2091:         }
                   2092:         $items=~s/\&$//;
1.1344    raeburn  2093:         if ($namespace =~ /^enc/) {
                   2094:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2095:         } else {
                   2096:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2097:         }
1.806     raeburn  2098:     } else {
1.860     raeburn  2099:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2100:     }
                   2101: }
                   2102: 
1.1023    raeburn  2103: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2104: sub newput_dom {
1.1023    raeburn  2105:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2106:     my $result;
                   2107:     if (!$udom) {
                   2108:         $udom=$env{'user.domain'};
                   2109:     }
1.1023    raeburn  2110:     if ($udom) {
                   2111:         my $uname = &get_domainconfiguser($udom);
                   2112:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2113:     }
                   2114:     return $result;
                   2115: }
                   2116: 
1.1023    raeburn  2117: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2118: sub del_dom {
1.1023    raeburn  2119:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2120:     if (ref($storearr) eq 'ARRAY') {
                   2121:         if (!$udom) {
                   2122:             $udom=$env{'user.domain'};
                   2123:         }
1.1023    raeburn  2124:         if ($udom) {
                   2125:             my $uname = &get_domainconfiguser($udom); 
                   2126:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2127:         }
                   2128:     }
                   2129: }
                   2130: 
1.1023    raeburn  2131: # ----------------------------------construct domainconfig user for a domain 
                   2132: sub get_domainconfiguser {
                   2133:     my ($udom) = @_;
                   2134:     return $udom.'-domainconfig';
                   2135: }
                   2136: 
1.837     raeburn  2137: sub retrieve_inst_usertypes {
                   2138:     my ($udom) = @_;
                   2139:     my (%returnhash,@order);
1.989     raeburn  2140:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2141:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2142:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2143:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2144:     } else {
                   2145:         if (defined(&domain($udom,'primary'))) {
                   2146:             my $uhome=&domain($udom,'primary');
                   2147:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2148:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2149:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2150:                 return (\%returnhash,\@order);
                   2151:             }
                   2152:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2153:             my @pairs=split(/\&/,$hashitems);
                   2154:             foreach my $item (@pairs) {
                   2155:                 my ($key,$value)=split(/=/,$item,2);
                   2156:                 $key = &unescape($key);
                   2157:                 next if ($key =~ /^error: 2 /);
                   2158:                 $returnhash{$key}=&thaw_unescape($value);
                   2159:             }
                   2160:             my @esc_order = split(/\&/,$orderitems);
                   2161:             foreach my $item (@esc_order) {
                   2162:                 push(@order,&unescape($item));
                   2163:             }
                   2164:         } else {
1.1256    raeburn  2165:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2166:         }
1.1256    raeburn  2167:         return (\%returnhash,\@order);
1.837     raeburn  2168:     }
                   2169: }
                   2170: 
1.868     raeburn  2171: sub is_domainimage {
                   2172:     my ($url) = @_;
1.1306    raeburn  2173:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2174:         if (&domain($1) ne '') {
                   2175:             return '1';
                   2176:         }
                   2177:     }
                   2178:     return;
                   2179: }
                   2180: 
1.899     raeburn  2181: sub inst_directory_query {
                   2182:     my ($srch) = @_;
                   2183:     my $udom = $srch->{'srchdomain'};
                   2184:     my %results;
                   2185:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2186:     my $outcome;
1.899     raeburn  2187:     if ($homeserver ne '') {
1.1357    raeburn  2188:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2189:             if ($srch->{'srchby'} eq 'email') {
                   2190:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2191:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2192:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2193:                     (($major == 2) && ($minor < 12))) {
                   2194:                     return;
                   2195:                 }
                   2196:             }
                   2197:         }
1.904     albertel 2198: 	my $queryid=&reply("querysend:instdirsearch:".
                   2199: 			   &escape($srch->{'srchby'}).':'.
                   2200: 			   &escape($srch->{'srchterm'}).':'.
                   2201: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2202: 	my $host=&hostname($homeserver);
                   2203: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2204: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2205: 	    return;
                   2206: 	}
                   2207: 	my $response = &get_query_reply($queryid);
                   2208: 	my $maxtries = 5;
                   2209: 	my $tries = 1;
                   2210: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2211: 	    $response = &get_query_reply($queryid);
                   2212: 	    $tries ++;
                   2213: 	}
                   2214: 
                   2215:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2216:             if ($response eq 'unavailable') {
                   2217:                 $outcome = $response;
                   2218:             } else {
                   2219:                 $outcome = 'ok';
                   2220:                 my @matches = split(/\n/,$response);
                   2221:                 foreach my $match (@matches) {
                   2222:                     my ($key,$value) = split(/=/,$match);
                   2223:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2224:                 }
1.899     raeburn  2225:             }
                   2226:         }
                   2227:     }
1.909     raeburn  2228:     return ($outcome,%results);
1.899     raeburn  2229: }
                   2230: 
                   2231: sub usersearch {
                   2232:     my ($srch) = @_;
                   2233:     my $dom = $srch->{'srchdomain'};
                   2234:     my %results;
                   2235:     my %libserv = &all_library();
                   2236:     my $query = 'usersearch';
                   2237:     foreach my $tryserver (keys(%libserv)) {
                   2238:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2239:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2240:                 if ($srch->{'srchby'} eq 'email') {
                   2241:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2242:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2243:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2244:                              (($major == 2) && ($minor < 12)));
                   2245:                 }
                   2246:             }
1.899     raeburn  2247:             my $host=&hostname($tryserver);
                   2248:             my $queryid=
1.911     raeburn  2249:                 &reply("querysend:".&escape($query).':'.
                   2250:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2251:                        &escape($srch->{'srchtype'}).':'.
                   2252:                        &escape($srch->{'srchterm'}),$tryserver);
                   2253:             if ($queryid !~/^\Q$host\E\_/) {
                   2254:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2255:                 next;
1.899     raeburn  2256:             }
                   2257:             my $reply = &get_query_reply($queryid);
                   2258:             my $maxtries = 1;
                   2259:             my $tries = 1;
                   2260:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2261:                 $reply = &get_query_reply($queryid);
                   2262:                 $tries ++;
                   2263:             }
                   2264:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2265:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2266:             } else {
1.911     raeburn  2267:                 my @matches;
                   2268:                 if ($reply =~ /\n/) {
                   2269:                     @matches = split(/\n/,$reply);
                   2270:                 } else {
                   2271:                     @matches = split(/\&/,$reply);
                   2272:                 }
1.899     raeburn  2273:                 foreach my $match (@matches) {
                   2274:                     my ($uname,$udom,%userhash);
1.911     raeburn  2275:                     foreach my $entry (split(/:/,$match)) {
                   2276:                         my ($key,$value) =
                   2277:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2278:                         $userhash{$key} = $value;
                   2279:                         if ($key eq 'username') {
                   2280:                             $uname = $value;
                   2281:                         } elsif ($key eq 'domain') {
                   2282:                             $udom = $value;
1.911     raeburn  2283:                         }
1.899     raeburn  2284:                     }
                   2285:                     $results{$uname.':'.$udom} = \%userhash;
                   2286:                 }
                   2287:             }
                   2288:         }
                   2289:     }
                   2290:     return %results;
                   2291: }
                   2292: 
1.912     raeburn  2293: sub get_instuser {
                   2294:     my ($udom,$uname,$id) = @_;
                   2295:     my $homeserver = &domain($udom,'primary');
                   2296:     my ($outcome,%results);
                   2297:     if ($homeserver ne '') {
                   2298:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2299:                            &escape($id).':'.&escape($udom),$homeserver);
                   2300:         my $host=&hostname($homeserver);
                   2301:         if ($queryid !~/^\Q$host\E\_/) {
                   2302:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2303:             return;
                   2304:         }
                   2305:         my $response = &get_query_reply($queryid);
                   2306:         my $maxtries = 5;
                   2307:         my $tries = 1;
                   2308:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2309:             $response = &get_query_reply($queryid);
                   2310:             $tries ++;
                   2311:         }
                   2312:         if (!&error($response) && $response ne 'refused') {
                   2313:             if ($response eq 'unavailable') {
                   2314:                 $outcome = $response;
                   2315:             } else {
                   2316:                 $outcome = 'ok';
                   2317:                 my @matches = split(/\n/,$response);
                   2318:                 foreach my $match (@matches) {
                   2319:                     my ($key,$value) = split(/=/,$match);
                   2320:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2321:                 }
                   2322:             }
                   2323:         }
                   2324:     }
                   2325:     my %userinfo;
                   2326:     if (ref($results{$uname}) eq 'HASH') {
                   2327:         %userinfo = %{$results{$uname}};
                   2328:     } 
                   2329:     return ($outcome,%userinfo);
                   2330: }
                   2331: 
1.1290    raeburn  2332: sub get_multiple_instusers {
                   2333:     my ($udom,$users,$caller) = @_;
                   2334:     my ($outcome,$results);
                   2335:     if (ref($users) eq 'HASH') {
                   2336:         my $count = keys(%{$users}); 
                   2337:         my $requested = &freeze_escape($users);
                   2338:         my $homeserver = &domain($udom,'primary');
                   2339:         if ($homeserver ne '') {
                   2340:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2341:             my $host=&hostname($homeserver);
                   2342:             if ($queryid !~/^\Q$host\E\_/) {
                   2343:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2344:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2345:                 return ($outcome,$results);
                   2346:             }
                   2347:             my $response = &get_query_reply($queryid);
                   2348:             my $maxtries = 5;
                   2349:             if ($count > 100) {
                   2350:                 $maxtries = 1+int($count/20);
                   2351:             }
                   2352:             my $tries = 1;
                   2353:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2354:                 $response = &get_query_reply($queryid);
                   2355:                 $tries ++;
                   2356:             }
                   2357:             if ($response eq '') {
                   2358:                 $results = {};
                   2359:                 foreach my $key (keys(%{$users})) {
                   2360:                     my ($uname,$id);
                   2361:                     if ($caller eq 'id') {
                   2362:                         $id = $key;
                   2363:                     } else {
                   2364:                         $uname = $key;
                   2365:                     }
                   2366:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2367:                     $outcome = $resp;
1.1290    raeburn  2368:                     if ($resp eq 'ok') {
                   2369:                         %{$results} = (%{$results}, %info);
                   2370:                     } else {
                   2371:                         last;
                   2372:                     }
                   2373:                 }
                   2374:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2375:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2376:                     $outcome = $response;
                   2377:                 } else {
1.1291    raeburn  2378:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2379:                     if ($outcome eq 'ok') {
                   2380:                         $results = &thaw_unescape($userdata); 
                   2381:                     }
                   2382:                 }
                   2383:             }
                   2384:         }
                   2385:     }
                   2386:     return ($outcome,$results);
                   2387: }
                   2388: 
1.912     raeburn  2389: sub inst_rulecheck {
1.923     raeburn  2390:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2391:     my %returnhash;
                   2392:     if ($udom ne '') {
                   2393:         if (ref($rules) eq 'ARRAY') {
                   2394:             @{$rules} = map {&escape($_);} (@{$rules});
                   2395:             my $rulestr = join(':',@{$rules});
                   2396:             my $homeserver=&domain($udom,'primary');
                   2397:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2398:                 my $response;
                   2399:                 if ($item eq 'username') {                
                   2400:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2401:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2402:                                               $homeserver));
1.923     raeburn  2403:                 } elsif ($item eq 'id') {
                   2404:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2405:                                               ':'.&escape($id).':'.$rulestr,
                   2406:                                               $homeserver));
1.945     raeburn  2407:                 } elsif ($item eq 'selfcreate') {
                   2408:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2409:                                                &escape($udom).':'.&escape($uname).
                   2410:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2411:                 }
1.912     raeburn  2412:                 if ($response ne 'refused') {
                   2413:                     my @pairs=split(/\&/,$response);
                   2414:                     foreach my $item (@pairs) {
                   2415:                         my ($key,$value)=split(/=/,$item,2);
                   2416:                         $key = &unescape($key);
                   2417:                         next if ($key =~ /^error: 2 /);
                   2418:                         $returnhash{$key}=&thaw_unescape($value);
                   2419:                     }
                   2420:                 }
                   2421:             }
                   2422:         }
                   2423:     }
                   2424:     return %returnhash;
                   2425: }
                   2426: 
                   2427: sub inst_userrules {
1.923     raeburn  2428:     my ($udom,$check) = @_;
1.912     raeburn  2429:     my (%ruleshash,@ruleorder);
                   2430:     if ($udom ne '') {
                   2431:         my $homeserver=&domain($udom,'primary');
                   2432:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2433:             my $response;
                   2434:             if ($check eq 'id') {
                   2435:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2436:                                  $homeserver);
1.943     raeburn  2437:             } elsif ($check eq 'email') {
                   2438:                 $response=&reply('instemailrules:'.&escape($udom),
                   2439:                                  $homeserver);
1.923     raeburn  2440:             } else {
                   2441:                 $response=&reply('instuserrules:'.&escape($udom),
                   2442:                                  $homeserver);
                   2443:             }
1.912     raeburn  2444:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2445:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2446:                 ($response ne 'no_such_host')) {
                   2447:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2448:                 my @pairs=split(/\&/,$hashitems);
                   2449:                 foreach my $item (@pairs) {
                   2450:                     my ($key,$value)=split(/=/,$item,2);
                   2451:                     $key = &unescape($key);
                   2452:                     next if ($key =~ /^error: 2 /);
                   2453:                     $ruleshash{$key}=&thaw_unescape($value);
                   2454:                 }
                   2455:                 my @esc_order = split(/\&/,$orderitems);
                   2456:                 foreach my $item (@esc_order) {
                   2457:                     push(@ruleorder,&unescape($item));
                   2458:                 }
                   2459:             }
                   2460:         }
                   2461:     }
                   2462:     return (\%ruleshash,\@ruleorder);
                   2463: }
                   2464: 
1.976     raeburn  2465: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2466: 
                   2467: sub get_domain_defaults {
1.1240    raeburn  2468:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2469:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2470:     my $cachetime = 60*60*24;
1.1240    raeburn  2471:     unless ($ignore_cache) {
                   2472:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2473:         if (defined($cached)) {
                   2474:             if (ref($result) eq 'HASH') {
                   2475:                 return %{$result};
                   2476:             }
1.943     raeburn  2477:         }
                   2478:     }
                   2479:     my %domdefaults;
                   2480:     my %domconfig =
1.989     raeburn  2481:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2482:                                   'requestcourses','inststatus',
1.1183    raeburn  2483:                                   'coursedefaults','usersessions',
1.1258    raeburn  2484:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2485:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2486:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2487:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2488:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2489:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2490:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2491:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2492:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2493:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2494:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2495:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2496:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2497:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2498:     } else {
                   2499:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2500:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2501:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2502:     }
1.976     raeburn  2503:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2504:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2505:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2506:         } else {
                   2507:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2508:         }
1.1177    raeburn  2509:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2510:         foreach my $item (@usertools) {
                   2511:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2512:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2513:             }
                   2514:         }
1.1229    raeburn  2515:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2516:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2517:         }
1.976     raeburn  2518:     }
1.985     raeburn  2519:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2520:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2521:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2522:         }
                   2523:     }
1.1183    raeburn  2524:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2525:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2526:     }
1.989     raeburn  2527:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2528:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2529:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2530:         }
                   2531:     }
1.1047    raeburn  2532:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2533:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2534:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2535:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2536:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2537:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2538:         }
1.1254    raeburn  2539:         foreach my $type (@coursetypes) {
                   2540:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2541:                 unless ($type eq 'community') {
                   2542:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2543:                 }
                   2544:             }
                   2545:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2546:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2547:             }
1.1277    raeburn  2548:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2549:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2550:                     $domdefaults{$type.'postsubtimeout'} = 
                   2551:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2552:                 }
                   2553:             }
1.1230    raeburn  2554:         }
1.1286    raeburn  2555:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2556:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2557:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2558:                 if (@clonecodes) {
                   2559:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2560:                 }
                   2561:             }
                   2562:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2563:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2564:         }
1.1356    raeburn  2565:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2566:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2567:         } 
1.1047    raeburn  2568:     }
1.1073    raeburn  2569:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2570:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2571:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2572:         }
                   2573:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2574:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2575:         }
1.1279    raeburn  2576:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2577:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2578:         }
1.1073    raeburn  2579:     }
1.1254    raeburn  2580:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2581:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2582:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2583:                             'approval','limit');
                   2584:             foreach my $type (@coursetypes) {
                   2585:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2586:                     my @mgrdc = ();
                   2587:                     foreach my $item (@settings) {
                   2588:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2589:                             push(@mgrdc,$item);
                   2590:                         }
                   2591:                     }
                   2592:                     if (@mgrdc) {
                   2593:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2594:                     }
                   2595:                 }
                   2596:             }
                   2597:         }
                   2598:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2599:             foreach my $type (@coursetypes) {
                   2600:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2601:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2602:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2603:                     }
                   2604:                 }
                   2605:             }
                   2606:         }
                   2607:     }
1.1258    raeburn  2608:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2609:         $domdefaults{'catauth'} = 'std';
                   2610:         $domdefaults{'catunauth'} = 'std';
                   2611:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2612:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2613:         }
                   2614:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2615:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2616:         }
                   2617:     }
1.1315    raeburn  2618:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2619:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2620:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2621:         }
1.1338    raeburn  2622:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2623:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2624:         }
                   2625:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2626:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2627:         }
                   2628:     }
1.1320    raeburn  2629:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2630:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2631:         foreach my $prefix (@prefixes) {
                   2632:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2633:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2634:             }
                   2635:         }
                   2636:     }
1.1314    raeburn  2637:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2638:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2639:     }
1.1332    raeburn  2640:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2641:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2642:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2643:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2644:         }
                   2645:     }
1.1219    raeburn  2646:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2647:     return %domdefaults;
                   2648: }
                   2649: 
1.1311    raeburn  2650: sub course_portal_url {
                   2651:     my ($cnum,$cdom) = @_;
                   2652:     my $chome = &homeserver($cnum,$cdom);
                   2653:     my $hostname = &hostname($chome);
                   2654:     my $protocol = $protocol{$chome};
                   2655:     $protocol = 'http' if ($protocol ne 'https');
                   2656:     my %domdefaults = &get_domain_defaults($cdom);
                   2657:     my $firsturl;
                   2658:     if ($domdefaults{'portal_def'}) {
                   2659:         $firsturl = $domdefaults{'portal_def'};
                   2660:     } else {
                   2661:         $firsturl = $protocol.'://'.$hostname;
                   2662:     }
                   2663:     return $firsturl;
                   2664: }
                   2665: 
1.344     www      2666: # --------------------------------------------------- Assign a key to a student
                   2667: 
                   2668: sub assign_access_key {
1.364     www      2669: #
                   2670: # a valid key looks like uname:udom#comments
                   2671: # comments are being appended
                   2672: #
1.498     www      2673:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2674:     $kdom=
1.620     albertel 2675:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2676:     $knum=
1.620     albertel 2677:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2678:     $cdom=
1.620     albertel 2679:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2680:     $cnum=
1.620     albertel 2681:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2682:     $udom=$env{'user.name'} unless (defined($udom));
                   2683:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2684:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2685:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2686:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2687:                                                   # assigned to this person
                   2688:                                                   # - this should not happen,
1.345     www      2689:                                                   # unless something went wrong
                   2690:                                                   # the first time around
                   2691: # ready to assign
1.364     www      2692:         $logentry=$1.'; '.$logentry;
1.496     www      2693:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2694:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2695: # key now belongs to user
1.346     www      2696: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2697:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2698:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2699:                 return 'ok';
                   2700:             } else {
                   2701:                 return 
                   2702:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2703: 	    }
                   2704:         } else {
                   2705:             return 'error: Could not assign key, try again later.';
                   2706:         }
1.364     www      2707:     } elsif (!$existing{$ckey}) {
1.345     www      2708: # the key does not exist
                   2709: 	return 'error: The key does not exist';
                   2710:     } else {
                   2711: # the key is somebody else's
                   2712: 	return 'error: The key is already in use';
                   2713:     }
1.344     www      2714: }
                   2715: 
1.364     www      2716: # ------------------------------------------ put an additional comment on a key
                   2717: 
                   2718: sub comment_access_key {
                   2719: #
                   2720: # a valid key looks like uname:udom#comments
                   2721: # comments are being appended
                   2722: #
                   2723:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2724:     $cdom=
1.620     albertel 2725:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2726:     $cnum=
1.620     albertel 2727:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2728:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2729:     if ($existing{$ckey}) {
                   2730:         $existing{$ckey}.='; '.$logentry;
                   2731: # ready to assign
1.367     www      2732:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2733:                                                  $cdom,$cnum) eq 'ok') {
                   2734: 	    return 'ok';
                   2735:         } else {
                   2736: 	    return 'error: Count not store comment.';
                   2737:         }
                   2738:     } else {
                   2739: # the key does not exist
                   2740: 	return 'error: The key does not exist';
                   2741:     }
                   2742: }
                   2743: 
1.344     www      2744: # ------------------------------------------------------ Generate a set of keys
                   2745: 
                   2746: sub generate_access_keys {
1.364     www      2747:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2748:     $cdom=
1.620     albertel 2749:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2750:     $cnum=
1.620     albertel 2751:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2752:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2753:     unless (($cdom) && ($cnum)) { return 0; }
                   2754:     if ($number>10000) { return 0; }
                   2755:     sleep(2); # make sure don't get same seed twice
                   2756:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2757:     my $total=0;
                   2758:     for (my $i=1;$i<=$number;$i++) {
                   2759:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2760:                   sprintf("%lx",int(100000*rand)).'-'.
                   2761:                   sprintf("%lx",int(100000*rand));
                   2762:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2763:        $newkey=~s/0/h/g; # and also 0 and O
                   2764:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2765:        if ($existing{$newkey}) {
                   2766:            $i--;
                   2767:        } else {
1.364     www      2768: 	  if (&put('accesskeys',
                   2769:               { $newkey => '# generated '.localtime().
1.620     albertel 2770:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2771:                            '; '.$logentry },
                   2772: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2773:               $total++;
                   2774: 	  }
                   2775:        }
                   2776:     }
1.620     albertel 2777:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2778:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2779:     return $total;
                   2780: }
                   2781: 
                   2782: # ------------------------------------------------------- Validate an accesskey
                   2783: 
                   2784: sub validate_access_key {
                   2785:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2786:     $cdom=
1.620     albertel 2787:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2788:     $cnum=
1.620     albertel 2789:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2790:     $udom=$env{'user.domain'} unless (defined($udom));
                   2791:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2792:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2793:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2794: }
                   2795: 
                   2796: # ------------------------------------- Find the section of student in a course
1.652     albertel 2797: sub devalidate_getsection_cache {
                   2798:     my ($udom,$unam,$courseid)=@_;
                   2799:     my $hashid="$udom:$unam:$courseid";
                   2800:     &devalidate_cache_new('getsection',$hashid);
                   2801: }
1.298     matthew  2802: 
1.815     albertel 2803: sub courseid_to_courseurl {
                   2804:     my ($courseid) = @_;
                   2805:     #already url style courseid
                   2806:     return $courseid if ($courseid =~ m{^/});
                   2807: 
                   2808:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2809: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2810: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2811: 	return "/$cdom/$cnum";
                   2812:     }
                   2813: 
                   2814:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2815:     if (exists($courseinfo{'num'})) {
                   2816: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2817:     }
                   2818: 
                   2819:     return undef;
                   2820: }
                   2821: 
1.298     matthew  2822: sub getsection {
                   2823:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2824:     my $cachetime=1800;
1.551     albertel 2825: 
                   2826:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2827:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2828:     if (defined($cached)) { return $result; }
                   2829: 
1.298     matthew  2830:     my %Pending; 
                   2831:     my %Expired;
                   2832:     #
                   2833:     # Each role can either have not started yet (pending), be active, 
                   2834:     #    or have expired.
                   2835:     #
                   2836:     # If there is an active role, we are done.
                   2837:     #
                   2838:     # If there is more than one role which has not started yet, 
                   2839:     #     choose the one which will start sooner
                   2840:     # If there is one role which has not started yet, return it.
                   2841:     #
                   2842:     # If there is more than one expired role, choose the one which ended last.
                   2843:     # If there is a role which has expired, return it.
                   2844:     #
1.815     albertel 2845:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2846:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2847:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2848:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2849:         my $section=$1;
                   2850:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2851:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2852:         my $now=time;
1.548     albertel 2853:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2854:             $Expired{$end}=$section;
                   2855:             next;
                   2856:         }
1.548     albertel 2857:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2858:             $Pending{$start}=$section;
                   2859:             next;
                   2860:         }
1.599     albertel 2861:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2862:     }
                   2863:     #
                   2864:     # Presumedly there will be few matching roles from the above
                   2865:     # loop and the sorting time will be negligible.
                   2866:     if (scalar(keys(%Pending))) {
                   2867:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2868:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2869:     } 
                   2870:     if (scalar(keys(%Expired))) {
                   2871:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2872:         my $time = pop(@sorted);
1.599     albertel 2873:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2874:     }
1.599     albertel 2875:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2876: }
1.70      www      2877: 
1.599     albertel 2878: sub save_cache {
                   2879:     &purge_remembered();
1.722     albertel 2880:     #&Apache::loncommon::validate_page();
1.620     albertel 2881:     undef(%env);
1.780     albertel 2882:     undef($env_loaded);
1.599     albertel 2883: }
1.452     albertel 2884: 
1.599     albertel 2885: my $to_remember=-1;
                   2886: my %remembered;
                   2887: my %accessed;
                   2888: my $kicks=0;
                   2889: my $hits=0;
1.849     albertel 2890: sub make_key {
                   2891:     my ($name,$id) = @_;
1.872     albertel 2892:     if (length($id) > 65 
                   2893: 	&& length(&escape($id)) > 200) {
                   2894: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2895:     }
1.849     albertel 2896:     return &escape($name.':'.$id);
                   2897: }
                   2898: 
1.599     albertel 2899: sub devalidate_cache_new {
                   2900:     my ($name,$id,$debug) = @_;
                   2901:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2902:     my $remembered_id=$name.':'.$id;
1.849     albertel 2903:     $id=&make_key($name,$id);
1.599     albertel 2904:     $memcache->delete($id);
1.1319    damieng  2905:     delete($remembered{$remembered_id});
                   2906:     delete($accessed{$remembered_id});
1.599     albertel 2907: }
                   2908: 
                   2909: sub is_cached_new {
                   2910:     my ($name,$id,$debug) = @_;
1.1319    damieng  2911:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2912:     if (exists($remembered{$remembered_id})) {
                   2913: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2914: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2915: 	$hits++;
1.1319    damieng  2916: 	return ($remembered{$remembered_id},1);
1.599     albertel 2917:     }
1.1319    damieng  2918:     $id=&make_key($name,$id);
1.599     albertel 2919:     my $value = $memcache->get($id);
                   2920:     if (!(defined($value))) {
                   2921: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2922: 	return (undef,undef);
1.416     albertel 2923:     }
1.599     albertel 2924:     if ($value eq '__undef__') {
                   2925: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2926: 	$value=undef;
                   2927:     }
1.1319    damieng  2928:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2929:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2930:     return ($value,1);
                   2931: }
                   2932: 
                   2933: sub do_cache_new {
                   2934:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2935:     my $remembered_id=$name.':'.$id;
1.849     albertel 2936:     $id=&make_key($name,$id);
1.599     albertel 2937:     my $setvalue=$value;
                   2938:     if (!defined($setvalue)) {
                   2939: 	$setvalue='__undef__';
                   2940:     }
1.623     albertel 2941:     if (!defined($time) ) {
                   2942: 	$time=600;
                   2943:     }
1.599     albertel 2944:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2945:     my $result = $memcache->set($id,$setvalue,$time);
                   2946:     if (! $result) {
1.872     albertel 2947: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2948: 	$memcache->disconnect_all();
1.872     albertel 2949:     }
1.600     albertel 2950:     # need to make a copy of $value
1.1319    damieng  2951:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2952:     return $value;
                   2953: }
                   2954: 
                   2955: sub make_room {
1.1319    damieng  2956:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2957: 
1.1319    damieng  2958:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2959:                                     : $value;
1.599     albertel 2960:     if ($to_remember<0) { return; }
1.1319    damieng  2961:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2962:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2963:     my $to_kick;
                   2964:     my $max_time=0;
                   2965:     foreach my $other (keys(%accessed)) {
                   2966: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2967: 	    $to_kick=$other;
                   2968: 	    $max_time=&tv_interval($accessed{$other});
                   2969: 	}
                   2970:     }
                   2971:     delete($remembered{$to_kick});
                   2972:     delete($accessed{$to_kick});
                   2973:     $kicks++;
                   2974:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2975:     return;
                   2976: }
                   2977: 
1.599     albertel 2978: sub purge_remembered {
1.604     albertel 2979:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2980:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2981:     undef(%remembered);
                   2982:     undef(%accessed);
1.428     albertel 2983: }
1.70      www      2984: # ------------------------------------- Read an entry from a user's environment
                   2985: 
                   2986: sub userenvironment {
                   2987:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2988:     my $items;
                   2989:     foreach my $item (@what) {
                   2990:         $items.=&escape($item).'&';
                   2991:     }
                   2992:     $items=~s/\&$//;
1.70      www      2993:     my %returnhash=();
1.1009    raeburn  2994:     my $uhome = &homeserver($unam,$udom);
                   2995:     unless ($uhome eq 'no_host') {
                   2996:         my @answer=split(/\&/, 
                   2997:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2998:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2999:             return %returnhash;
                   3000:         }
1.1009    raeburn  3001:         my $i;
                   3002:         for ($i=0;$i<=$#what;$i++) {
                   3003: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3004:         }
1.70      www      3005:     }
                   3006:     return %returnhash;
1.1       albertel 3007: }
                   3008: 
1.617     albertel 3009: # ---------------------------------------------------------- Get a studentphoto
                   3010: sub studentphoto {
                   3011:     my ($udom,$unam,$ext) = @_;
                   3012:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3013:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3014:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3015:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3016:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3017:             } else {
                   3018:                 my ($result,$perm_reqd)=
1.707     albertel 3019: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3020:                 if ($result eq 'ok') {
                   3021:                     if (!($perm_reqd eq 'yes')) {
                   3022:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3023:                     }
                   3024:                 }
                   3025:             }
                   3026:         }
                   3027:     } else {
                   3028:         my ($result,$perm_reqd) = 
1.707     albertel 3029: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3030:         if ($result eq 'ok') {
                   3031:             if (!($perm_reqd eq 'yes')) {
                   3032:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3033:             }
                   3034:         }
                   3035:     }
                   3036:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3037: }
                   3038: 
                   3039: sub retrievestudentphoto {
                   3040:     my ($udom,$unam,$ext,$type) = @_;
                   3041:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3042:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3043:     if ($ret eq 'ok') {
                   3044:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3045:         if ($type eq 'thumbnail') {
                   3046:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3047:         }
                   3048:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3049:         return $tokenurl;
                   3050:     } else {
                   3051:         if ($type eq 'thumbnail') {
                   3052:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3053:         } else { 
                   3054:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3055:         }
1.617     albertel 3056:     }
                   3057: }
                   3058: 
1.263     www      3059: # -------------------------------------------------------------------- New chat
                   3060: 
                   3061: sub chatsend {
1.724     raeburn  3062:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3063:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3064:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3065:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3066:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3067: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3068: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3069: }
                   3070: 
                   3071: # ------------------------------------------ Find current version of a resource
                   3072: 
                   3073: sub getversion {
                   3074:     my $fname=&clutter(shift);
1.1189    raeburn  3075:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3076:     return &currentversion(&filelocation('',$fname));
                   3077: }
                   3078: 
                   3079: sub currentversion {
                   3080:     my $fname=shift;
                   3081:     my $author=$fname;
                   3082:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3083:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3084:     my $home=&homeserver($uname,$udom);
1.292     www      3085:     if ($home eq 'no_host') { 
                   3086:         return -1; 
                   3087:     }
1.1112    www      3088:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3089:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3090: 	return -1;
                   3091:     }
1.1112    www      3092:     return $answer;
1.263     www      3093: }
                   3094: 
1.1111    www      3095: #
                   3096: # Return special version number of resource if set by override, empty otherwise
                   3097: #
                   3098: sub usedversion {
                   3099:     my $fname=shift;
                   3100:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3101:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3102:     if ($urlversion) { return $urlversion; }
                   3103:     return '';
                   3104: }
                   3105: 
1.1       albertel 3106: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3107: 
1.1       albertel 3108: sub subscribe {
                   3109:     my $fname=shift;
1.761     raeburn  3110:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3111:     $fname=~s/[\n\r]//g;
1.1       albertel 3112:     my $author=$fname;
                   3113:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3114:     my ($udom,$uname)=split(/\//,$author);
                   3115:     my $home=homeserver($uname,$udom);
1.335     albertel 3116:     if ($home eq 'no_host') {
                   3117:         return 'not_found';
1.1       albertel 3118:     }
                   3119:     my $answer=reply("sub:$fname",$home);
1.64      www      3120:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3121: 	$answer.=' by '.$home;
                   3122:     }
1.1       albertel 3123:     return $answer;
                   3124: }
                   3125:     
1.8       www      3126: # -------------------------------------------------------------- Replicate file
                   3127: 
                   3128: sub repcopy {
                   3129:     my $filename=shift;
1.23      www      3130:     $filename=~s/\/+/\//g;
1.1142    raeburn  3131:     my $londocroot = $perlvar{'lonDocRoot'};
                   3132:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3133:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3134:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3135: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3136: 	return &repcopy_userfile($filename);
                   3137:     }
1.532     albertel 3138:     $filename=~s/[\n\r]//g;
1.8       www      3139:     my $transname="$filename.in.transfer";
1.828     www      3140: # FIXME: this should flock
1.607     raeburn  3141:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3142:     my $remoteurl=subscribe($filename);
1.64      www      3143:     if ($remoteurl =~ /^con_lost by/) {
                   3144: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3145:            return 'unavailable';
1.8       www      3146:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3147: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3148: 	   return 'not_found';
1.64      www      3149:     } elsif ($remoteurl =~ /^rejected by/) {
                   3150: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3151:            return 'forbidden';
1.20      www      3152:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3153:            return 'ok';
1.8       www      3154:     } else {
1.290     www      3155:         my $author=$filename;
                   3156:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3157:         my ($udom,$uname)=split(/\//,$author);
                   3158:         my $home=homeserver($uname,$udom);
                   3159:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3160:            my @parts=split(/\//,$filename);
                   3161:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3162:            if ($path ne "$londocroot/res") {
1.8       www      3163:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3164: 	       return 'bad_request';
1.8       www      3165:            }
                   3166:            my $count;
                   3167:            for ($count=5;$count<$#parts;$count++) {
                   3168:                $path.="/$parts[$count]";
                   3169:                if ((-e $path)!=1) {
                   3170: 		   mkdir($path,0777);
                   3171:                }
                   3172:            }
                   3173:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3174:            my $response;
                   3175:            if ($remoteurl =~ m{/raw/}) {
                   3176:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3177:            } else {
                   3178:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3179:            }
1.8       www      3180:            if ($response->is_error()) {
                   3181: 	       unlink($transname);
                   3182:                my $message=$response->status_line;
1.672     albertel 3183:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3184:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3185:                return 'unavailable';
1.8       www      3186:            } else {
1.16      www      3187: 	       if ($remoteurl!~/\.meta$/) {
                   3188:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3189:                   my $mresponse;
                   3190:                   if ($remoteurl =~ m{/raw/}) {
                   3191:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3192:                   } else {
                   3193:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3194:                   }
1.16      www      3195:                   if ($mresponse->is_error()) {
                   3196: 		      unlink($filename.'.meta');
                   3197:                       &logthis(
1.672     albertel 3198:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3199:                   }
                   3200: 	       }
1.8       www      3201:                rename($transname,$filename);
1.607     raeburn  3202:                return 'ok';
1.8       www      3203:            }
1.290     www      3204:        }
1.8       www      3205:     }
1.330     www      3206: }
                   3207: 
                   3208: # ------------------------------------------------ Get server side include body
                   3209: sub ssi_body {
1.381     albertel 3210:     my ($filelink,%form)=@_;
1.606     matthew  3211:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3212:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3213:     }
1.953     www      3214:     my $output='';
                   3215:     my $response;
1.980     raeburn  3216:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3217:        ($output,$response)=&externalssi($filelink);
1.953     www      3218:     } else {
1.1004    droeschl 3219:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3220:        $filelink .= 'inhibitmenu=yes';
1.953     www      3221:        ($output,$response)=&ssi($filelink,%form);
                   3222:     }
1.778     albertel 3223:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3224:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3225:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3226:     if (wantarray) {
                   3227:         return ($output, $response);
                   3228:     } else {
                   3229:         return $output;
                   3230:     }
1.8       www      3231: }
                   3232: 
1.15      www      3233: # --------------------------------------------------------- Server Side Include
                   3234: 
1.782     albertel 3235: sub absolute_url {
                   3236:     my ($host_name) = @_;
                   3237:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3238:     if ($host_name eq '') {
                   3239: 	$host_name = $ENV{'SERVER_NAME'};
                   3240:     }
                   3241:     return $protocol.$host_name;
                   3242: }
                   3243: 
1.942     foxr     3244: #
                   3245: #   Server side include.
                   3246: # Parameters:
                   3247: #  fn     Possibly encrypted resource name/id.
                   3248: #  form   Hash that describes how the rendering should be done
                   3249: #         and other things.
1.944     foxr     3250: # Returns:
1.950     raeburn  3251: #   Scalar context: The content of the response.
                   3252: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3253: #     
1.15      www      3254: sub ssi {
                   3255: 
1.944     foxr     3256:     my ($fn,%form)=@_;
1.23      www      3257:     my $request;
1.711     albertel 3258: 
                   3259:     $form{'no_update_last_known'}=1;
1.895     albertel 3260:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3261:     if (%form) {
1.782     albertel 3262:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3263:       $request->content(join('&',map { 
                   3264:             my $name = escape($_);
                   3265:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3266:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3267:             : &escape($form{$_}) );    
                   3268:         } keys(%form)));
1.23      www      3269:     } else {
1.782     albertel 3270:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3271:     }
                   3272: 
1.15      www      3273:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3274:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3275:     my $islocal;
                   3276:     if (($env{'request.course.id'}) &&
                   3277:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3278:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3279:         ($form{'grade_symb'} ne '') &&
                   3280:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3281:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3282:         $islocal = 1;
                   3283:     }
1.1384    raeburn  3284:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3285:                                                 '','','',$islocal);
1.1182    foxr     3286: 
1.944     foxr     3287:     if (wantarray) {
1.1345    raeburn  3288: 	return ($response->content, $response);
1.944     foxr     3289:     } else {
1.1345    raeburn  3290: 	return $response->content;
1.942     foxr     3291:     }
1.324     www      3292: }
                   3293: 
                   3294: sub externalssi {
                   3295:     my ($url)=@_;
                   3296:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3297:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3298:     if (wantarray) {
                   3299:         return ($response->content, $response);
                   3300:     } else {
                   3301:         return $response->content;
                   3302:     }
1.15      www      3303: }
1.254     www      3304: 
1.1354    raeburn  3305: 
                   3306: # If the local copy of a replicated resource is outdated, trigger a  
                   3307: # connection from the homeserver to flush the delayed queue. If no update 
                   3308: # happens, remove local copies of outdated resource (and corresponding
                   3309: # metadata file).
                   3310: 
1.1352    raeburn  3311: sub remove_stale_resfile {
                   3312:     my ($url) = @_;
1.1354    raeburn  3313:     my $removed;
1.1352    raeburn  3314:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3315:         my $audom = $1;
                   3316:         my $auname = $2;
1.1353    raeburn  3317:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3318:             my $homeserver = &homeserver($auname,$audom);
                   3319:             unless (($homeserver eq 'no_host') ||
                   3320:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3321:                 my $fname = &filelocation('',$url);
                   3322:                 if (-e $fname) {
                   3323:                     my $protocol = $protocol{$homeserver};
                   3324:                     $protocol = 'http' if ($protocol ne 'https');
                   3325:                     my $hostname = &hostname($homeserver);
                   3326:                     if ($hostname) {
                   3327:                         my $uri = &declutter($url);
                   3328:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3329:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3330:                         if ($response->is_success()) {
                   3331:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3332:                             my $locmodtime = (stat($fname))[9];
                   3333:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3334:                                 my $stale;
                   3335:                                 my $answer = &reply('pong',$homeserver);
                   3336:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3337:                                     sleep(0.2);
                   3338:                                     $locmodtime = (stat($fname))[9];
                   3339:                                     if ($locmodtime < $remmodtime) {
                   3340:                                         my $posstransfer = $fname.'.in.transfer';
                   3341:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3342:                                             $removed = 1;
                   3343:                                         } else {
                   3344:                                             $stale = 1;
                   3345:                                         }
                   3346:                                     } else {
                   3347:                                         $removed = 1;
                   3348:                                     }
                   3349:                                 } else {
                   3350:                                     $stale = 1;
                   3351:                                 }
                   3352:                                 if ($stale) {
                   3353:                                     unlink($fname);
                   3354:                                     if ($uri!~/\.meta$/) {
                   3355:                                         unlink($fname.'.meta');
                   3356:                                     }
                   3357:                                     &reply("unsub:$fname",$homeserver);
                   3358:                                     $removed = 1;
1.1352    raeburn  3359:                                 }
                   3360:                             }
                   3361:                         }
                   3362:                     }
                   3363:                 }
                   3364:             }
                   3365:         }
                   3366:     }
1.1354    raeburn  3367:     return $removed;
1.1352    raeburn  3368: }
                   3369: 
1.492     albertel 3370: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3371: 
                   3372: sub allowuploaded {
                   3373:     my ($srcurl,$url)=@_;
                   3374:     $url=&clutter(&declutter($url));
                   3375:     my $dir=$url;
                   3376:     $dir=~s/\/[^\/]+$//;
                   3377:     my %httpref=();
                   3378:     my $httpurl=&hreflocation('',$url);
                   3379:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3380:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3381: }
1.477     raeburn  3382: 
1.1193    raeburn  3383: #
                   3384: # Determine if the current user should be able to edit a particular resource,
                   3385: # when viewing in course context.
                   3386: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3387: #     Functions.
                   3388: # (b) When displaying folder contents in course editor, used to determine if
                   3389: #     "Edit" link will be displayed alongside resource.
                   3390: #
1.1196    raeburn  3391: #  input: six args -- filename (decluttered), course number, course domain,
                   3392: #                   url, symb (if registered) and group (if this is a group
                   3393: #                   item -- e.g., bulletin board, group page etc.).
                   3394: #  output: array of five scalars -- 
1.1193    raeburn  3395: #          $cfile -- url for file editing if editable on current server
                   3396: #          $home -- homeserver of resource (i.e., for author if published,
                   3397: #                                           or course if uploaded.).
                   3398: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3399: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3400: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3401: #
                   3402: 
                   3403: sub can_edit_resource {
1.1194    raeburn  3404:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3405:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3406: #
                   3407: # For aboutme pages user can only edit his/her own.
                   3408: #
1.1199    raeburn  3409:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3410:         my ($sdom,$sname) = ($1,$2);
                   3411:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3412:             $home = $env{'user.home'};
                   3413:             $cfile = $resurl;
                   3414:             if ($env{'form.forceedit'}) {
                   3415:                 $forceview = 1;
                   3416:             } else {
                   3417:                 $forceedit = 1;
                   3418:             }
                   3419:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3420:         } else {
                   3421:             return;
                   3422:         }
                   3423:     }
                   3424: 
                   3425:     if ($env{'request.course.id'}) {
                   3426:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3427:         if ($group ne '') {
                   3428: # if this is a group homepage or group bulletin board, check group privs
                   3429:             my $allowed = 0;
1.1197    raeburn  3430:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3431:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3432:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3433:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3434:                     $allowed = 1;
                   3435:                 }
1.1197    raeburn  3436:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3437:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3438:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3439:                     $allowed = 1;
                   3440:                 }
                   3441:             }
                   3442:             if ($allowed) {
                   3443:                 $home=&homeserver($cnum,$cdom);
                   3444:                 if ($env{'form.forceedit'}) {
                   3445:                     $forceview = 1;
                   3446:                 } else {
                   3447:                     $forceedit = 1;
                   3448:                 }
                   3449:                 $cfile = $resurl;
                   3450:             } else {
                   3451:                 return;
                   3452:             }
                   3453:         } else {
1.1208    raeburn  3454:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3455:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3456:                     return;
                   3457:                 }
                   3458:             } elsif (!$crsedit) {
1.1194    raeburn  3459: #
                   3460: # No edit allowed where CC has switched to student role.
                   3461: #
                   3462:                 return;
                   3463:             }
                   3464:         }
                   3465:     }
                   3466: 
1.1193    raeburn  3467:     if ($file ne '') {
                   3468:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3469:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3470:                 $uploaded = 1;
                   3471:                 $incourse = 1;
1.1193    raeburn  3472:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3473:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3474:                     if ($env{'form.forceedit'}) {
                   3475:                         $forceview = 1;
                   3476:                     } else {
                   3477:                         $forceedit = 1;
                   3478:                     }
1.1194    raeburn  3479:                 }
                   3480:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3481:                 $incourse = 1;
                   3482:                 if ($env{'form.forceedit'}) {
                   3483:                     $forceview = 1;
                   3484:                 } else {
                   3485:                     $forceedit = 1;
                   3486:                 }
                   3487:                 $cfile = $resurl;
                   3488:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3489:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3490:                     $incourse = 1;
                   3491:                     if ($env{'form.forceedit'}) {
                   3492:                         $forceview = 1;
                   3493:                     } else {
                   3494:                         $forceedit = 1;
                   3495:                     }
                   3496:                     $cfile = $resurl;
1.1199    raeburn  3497:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3498:                     $incourse = 1;
                   3499:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3500:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3501:                     $incourse = 1;
1.1199    raeburn  3502:                     if ($env{'form.forceedit'}) {
                   3503:                         $forceview = 1;
                   3504:                     } else {
                   3505:                         $forceedit = 1;
                   3506:                     }
                   3507:                     $cfile = $resurl;
1.1343    raeburn  3508:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3509:                     $incourse = 1;
                   3510:                     if ($env{'form.forceedit'}) {
                   3511:                         $forceview = 1;
                   3512:                     } else {
                   3513:                         $forceedit = 1;
                   3514:                     }
                   3515:                     $cfile = $resurl;
1.1208    raeburn  3516:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3517:                     $incourse = 1;
                   3518:                     if ($env{'form.forceedit'}) {
                   3519:                         $forceview = 1;
                   3520:                     } else {
                   3521:                         $forceedit = 1;
                   3522:                     }
                   3523:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3524:                 }
                   3525:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3526:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3527:                 if (&is_on_map($template)) { 
                   3528:                     $incourse = 1;
                   3529:                     $forceview = 1;
                   3530:                     $cfile = $template;
1.1193    raeburn  3531:                 }
1.1199    raeburn  3532:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3533:                     $incourse = 1;
                   3534:                     if ($env{'form.forceedit'}) {
                   3535:                         $forceview = 1;
                   3536:                     } else {
                   3537:                         $forceedit = 1;
                   3538:                     }
                   3539:                     $cfile = $resurl;
1.1343    raeburn  3540:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3541:                 $incourse = 1;
                   3542:                 if ($env{'form.forceedit'}) {
                   3543:                     $forceview = 1;
                   3544:                 } else {
                   3545:                     $forceedit = 1;
                   3546:                 }
                   3547:                 $cfile = $resurl;
1.1199    raeburn  3548:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3549:                 $incourse = 1;
                   3550:                 $forceview = 1;
                   3551:                 if ($symb) {
                   3552:                     my ($map,$id,$res)=&decode_symb($symb);
                   3553:                     $env{'request.symb'} = $symb;
                   3554:                     $cfile = &clutter($res);
                   3555:                 } else {
                   3556:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3557:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3558:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3559:                         $cfile = '/adm/wrapper'.$escfile;
                   3560:                     } else {
                   3561:                         $escfile =~ s{^http://}{};
                   3562:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3563:                     }
1.1199    raeburn  3564:                 }
1.1234    raeburn  3565:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3566:                 if ($env{'form.forceedit'}) {
                   3567:                     $forceview = 1;
                   3568:                 } else {
                   3569:                     $forceedit = 1;
                   3570:                 }
                   3571:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3572:             }
                   3573:         }
1.1194    raeburn  3574:         if ($uploaded || $incourse) {
                   3575:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3576:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3577:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3578:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3579:             # Check that the user has permission to edit this resource
                   3580:             my $setpriv = 1;
                   3581:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3582:             if (defined($cfudom)) {
                   3583:                 $home=&homeserver($cfuname,$cfudom);
                   3584:                 $cfile=$file;
                   3585:             }
                   3586:         }
1.1194    raeburn  3587:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3588:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3589:             my @ids=&current_machine_ids();
                   3590:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3591:                 $switchserver=1;
                   3592:             }
                   3593:         }
                   3594:     }
1.1194    raeburn  3595:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3596: }
                   3597: 
                   3598: sub is_course_upload {
                   3599:     my ($file,$cnum,$cdom) = @_;
                   3600:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3601:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3602:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3603:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3604:         return 1;
                   3605:     }
                   3606:     return;
                   3607: }
                   3608: 
1.1194    raeburn  3609: sub in_course {
1.1195    raeburn  3610:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3611:     if ($hideprivileged) {
                   3612:         my $skipuser;
1.1219    raeburn  3613:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3614:         my @possdoms = ($cdom);  
                   3615:         if ($coursehash{'checkforpriv'}) { 
                   3616:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3617:         }
                   3618:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3619:             $skipuser = 1;
                   3620:             if ($coursehash{'nothideprivileged'}) {
                   3621:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3622:                     my $user;
                   3623:                     if ($item =~ /:/) {
                   3624:                         $user = $item;
                   3625:                     } else {
                   3626:                         $user = join(':',split(/[\@]/,$item));
                   3627:                     }
                   3628:                     if ($user eq $uname.':'.$udom) {
                   3629:                         undef($skipuser);
                   3630:                         last;
                   3631:                     }
                   3632:                 }
                   3633:             }
                   3634:             if ($skipuser) {
                   3635:                 return 0;
                   3636:             }
                   3637:         }
                   3638:     }
1.1194    raeburn  3639:     $type ||= 'any';
                   3640:     if (!defined($cdom) || !defined($cnum)) {
                   3641:         my $cid  = $env{'request.course.id'};
                   3642:         $cdom = $env{'course.'.$cid.'.domain'};
                   3643:         $cnum = $env{'course.'.$cid.'.num'};
                   3644:     }
                   3645:     my $typesref;
1.1195    raeburn  3646:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3647:         $typesref = ['active','previous','future'];
                   3648:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3649:         $typesref = [$type];
                   3650:     }
                   3651:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3652:                               $typesref,undef,[$cdom]);
                   3653:     my ($tmp) = keys(%roles);
                   3654:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3655:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3656:     if (@course_roles > 0) {
                   3657:         return 1;
                   3658:     }
                   3659:     return 0;
                   3660: }
                   3661: 
1.478     albertel 3662: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3663: # input: action, courseID, current domain, intended
1.637     raeburn  3664: #        path to file, source of file, instruction to parse file for objects,
                   3665: #        ref to hash for embedded objects,
                   3666: #        ref to hash for codebase of java objects.
1.1095    raeburn  3667: #        reference to scalar to accommodate mime type determined
                   3668: #          from File::MMagic if $parser = parse.
1.637     raeburn  3669: #
1.485     raeburn  3670: # output: url to file (if action was uploaddoc), 
                   3671: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3672: #
1.478     albertel 3673: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3674: # course.
1.477     raeburn  3675: #
1.478     albertel 3676: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3677: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3678: #          course's home server.
1.477     raeburn  3679: #
1.478     albertel 3680: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3681: #          be copied from $source (current location) to 
                   3682: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3683: #         and will then be copied to
                   3684: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3685: #         course's home server.
1.485     raeburn  3686: #
1.481     raeburn  3687: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3688: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3689: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3690: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3691: #         in course's home server.
1.637     raeburn  3692: #
1.477     raeburn  3693: 
                   3694: sub process_coursefile {
1.1095    raeburn  3695:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3696:         $mimetype)=@_;
1.477     raeburn  3697:     my $fetchresult;
1.638     albertel 3698:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3699:     if ($action eq 'propagate') {
1.638     albertel 3700:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3701: 			     $home);
1.481     raeburn  3702:     } else {
1.477     raeburn  3703:         my $fpath = '';
                   3704:         my $fname = $file;
1.478     albertel 3705:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3706:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3707:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3708:         if ($action eq 'copy') {
                   3709:             if ($source eq '') {
                   3710:                 $fetchresult = 'no source file';
                   3711:                 return $fetchresult;
                   3712:             } else {
                   3713:                 my $destination = $filepath.'/'.$fname;
                   3714:                 rename($source,$destination);
                   3715:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3716:                                  $home);
1.481     raeburn  3717:             }
                   3718:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3719:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3720:             print $fh $env{'form.'.$source};
1.481     raeburn  3721:             close($fh);
1.637     raeburn  3722:             if ($parser eq 'parse') {
1.1024    raeburn  3723:                 my $mm = new File::MMagic;
1.1095    raeburn  3724:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3725:                 if ($type eq 'text/html') {
1.1024    raeburn  3726:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3727:                     unless ($parse_result eq 'ok') {
                   3728:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3729:                     }
1.637     raeburn  3730:                 }
1.1095    raeburn  3731:                 if (ref($mimetype)) {
                   3732:                     $$mimetype = $type;
                   3733:                 } 
1.637     raeburn  3734:             }
1.477     raeburn  3735:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3736:                                  $home);
1.481     raeburn  3737:             if ($fetchresult eq 'ok') {
                   3738:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3739:             } else {
                   3740:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3741:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3742:                 return '/adm/notfound.html';
                   3743:             }
1.477     raeburn  3744:         }
                   3745:     }
1.485     raeburn  3746:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3747:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3748:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3749:     }
                   3750:     return $fetchresult;
                   3751: }
                   3752: 
1.637     raeburn  3753: sub build_filepath {
                   3754:     my ($fpath) = @_;
                   3755:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3756:     unless ($fpath eq '') {
                   3757:         my @parts=split('/',$fpath);
                   3758:         foreach my $part (@parts) {
                   3759:             $filepath.= '/'.$part;
                   3760:             if ((-e $filepath)!=1) {
                   3761:                 mkdir($filepath,0777);
                   3762:             }
                   3763:         }
                   3764:     }
                   3765:     return $filepath;
                   3766: }
                   3767: 
                   3768: sub store_edited_file {
1.638     albertel 3769:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3770:     my $file = $primary_url;
                   3771:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3772:     my $fpath = '';
                   3773:     my $fname = $file;
                   3774:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3775:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3776:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3777:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3778:     print $fh $content;
                   3779:     close($fh);
1.638     albertel 3780:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3781:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3782: 			  $home);
1.637     raeburn  3783:     if ($$fetchresult eq 'ok') {
                   3784:         return '/uploaded/'.$fpath.'/'.$fname;
                   3785:     } else {
1.638     albertel 3786:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3787: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3788:         return '/adm/notfound.html';
                   3789:     }
                   3790: }
                   3791: 
1.531     albertel 3792: sub clean_filename {
1.831     albertel 3793:     my ($fname,$args)=@_;
1.315     www      3794: # Replace Windows backslashes by forward slashes
1.257     www      3795:     $fname=~s/\\/\//g;
1.831     albertel 3796:     if (!$args->{'keep_path'}) {
                   3797:         # Get rid of everything but the actual filename
                   3798: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3799:     }
1.315     www      3800: # Replace spaces by underscores
                   3801:     $fname=~s/\s+/\_/g;
                   3802: # Replace all other weird characters by nothing
1.831     albertel 3803:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3804: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3805: # numbers
                   3806:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3807:     return $fname;
                   3808: }
1.1051    raeburn  3809: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3810: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3811: # image with the same aspect ratio as the original, but with dimensions which do 
                   3812: # not exceed $resizewidth and $resizeheight.
                   3813:  
1.984     neumanie 3814: sub resizeImage {
1.1051    raeburn  3815:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3816:     my $ima = Image::Magick->new;
                   3817:     my $resized;
                   3818:     if (-e $img_path) {
                   3819:         $ima->Read($img_path);
                   3820:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3821:             my $width = $ima->Get('width');
                   3822:             my $height = $ima->Get('height');
                   3823:             if ($width > $resizewidth) {
                   3824: 	        my $factor = $width/$resizewidth;
                   3825:                 my $newheight = $height/$factor;
                   3826:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3827:                 $resized = 1;
                   3828:             }
                   3829:         }
                   3830:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3831:             my $width = $ima->Get('width');
                   3832:             my $height = $ima->Get('height');
                   3833:             if ($height > $resizeheight) {
                   3834:                 my $factor = $height/$resizeheight;
                   3835:                 my $newwidth = $width/$factor;
                   3836:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3837:                 $resized = 1;
                   3838:             }
                   3839:         }
                   3840:         if ($resized) {
                   3841:             $ima->Write($img_path);
                   3842:         }
                   3843:     }
                   3844:     return;
1.977     amueller 3845: }
                   3846: 
1.608     albertel 3847: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3848: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3849: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3850: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3851: #                                    canceloverwrite, or ''. 
                   3852: #                   if 'coursedoc': upload to the current course
                   3853: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3854: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3855: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3856: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3857: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3858: #        $allfiles - reference to hash for embedded objects
                   3859: #        $codebase - reference to hash for codebase of java objects
                   3860: #        $desuname - username for permanent storage of uploaded file
                   3861: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3862: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3863: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3864: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3865: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3866: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3867: #                    from File::MMagic.
1.858     raeburn  3868: # 
1.686     albertel 3869: # output: url of file in userspace, or error: <message> 
                   3870: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3871: 
1.531     albertel 3872: sub userfileupload {
1.1090    raeburn  3873:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3874:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3875:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3876:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3877:     $fname=&clean_filename($fname);
1.1090    raeburn  3878:     # See if there is anything left
1.257     www      3879:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3880:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3881:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3882:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3883:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3884:         my $now = time;
1.1090    raeburn  3885:         my $filepath;
1.1095    raeburn  3886:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3887:              $filepath = 'tmp/helprequests/'.$now;
                   3888:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3889:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3890:                          '_'.$env{'user.domain'}.'/pending';
                   3891:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3892:             my ($docuname,$docudom);
1.1350    raeburn  3893:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3894:                 $docudom = $destudom;
                   3895:             } else {
                   3896:                 $docudom = $env{'user.domain'};
                   3897:             }
1.1350    raeburn  3898:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3899:                 $docuname = $destuname;
                   3900:             } else {
                   3901:                 $docuname = $env{'user.name'};
                   3902:             }
                   3903:             if (exists($env{'form.group'})) {
                   3904:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3905:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3906:             }
                   3907:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3908:             if ($context eq 'canceloverwrite') {
                   3909:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3910:                 if (-e  $tempfile) {
                   3911:                     my @info = stat($tempfile);
                   3912:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3913:                         unlink($tempfile);
                   3914:                     }
                   3915:                 }
                   3916:                 return;
1.523     raeburn  3917:             }
                   3918:         }
1.1090    raeburn  3919:         # Create the directory if not present
1.741     raeburn  3920:         my @parts=split(/\//,$filepath);
                   3921:         my $fullpath = $perlvar{'lonDaemons'};
                   3922:         for (my $i=0;$i<@parts;$i++) {
                   3923:             $fullpath .= '/'.$parts[$i];
                   3924:             if ((-e $fullpath)!=1) {
                   3925:                 mkdir($fullpath,0777);
                   3926:             }
                   3927:         }
1.1359    raeburn  3928:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3929:         print $fh $env{'form.'.$formname};
                   3930:         close($fh);
1.1090    raeburn  3931:         if ($context eq 'existingfile') {
                   3932:             my @info = stat($fullpath.'/'.$fname);
                   3933:             return ($fullpath.'/'.$fname,$info[9]);
                   3934:         } else {
                   3935:             return $fullpath.'/'.$fname;
                   3936:         }
1.523     raeburn  3937:     }
1.995     raeburn  3938:     if ($subdir eq 'scantron') {
                   3939:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3940:     } else {
1.995     raeburn  3941:         $fname="$subdir/$fname";
                   3942:     }
1.1090    raeburn  3943:     if ($context eq 'coursedoc') {
1.638     albertel 3944: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3945: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3946:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3947:             return &finishuserfileupload($docuname,$docudom,
                   3948: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3949: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3950:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3951:         } else {
1.1218    raeburn  3952:             if ($env{'form.folder'}) {
                   3953:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3954:             }
1.638     albertel 3955:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3956: 				       $fname,$formname,$parser,
1.1095    raeburn  3957: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3958:         }
1.719     banghart 3959:     } elsif (defined($destuname)) {
                   3960:         my $docuname=$destuname;
                   3961:         my $docudom=$destudom;
1.860     raeburn  3962: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3963: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3964:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3965:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3966:     } else {
1.638     albertel 3967:         my $docuname=$env{'user.name'};
                   3968:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3969:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3970:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3971:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3972:         }
1.860     raeburn  3973: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3974: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3975:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3976:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3977:     }
1.271     www      3978: }
                   3979: 
                   3980: sub finishuserfileupload {
1.860     raeburn  3981:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3982:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3983:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3984:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3985:   
1.860     raeburn  3986:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3987:     $file=$fname;
                   3988:     if ($fname=~m|/|) {
                   3989:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3990: 	$path.=$fnamepath.'/';
                   3991:     }
1.259     www      3992:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3993:     my $count;
                   3994:     for ($count=4;$count<=$#parts;$count++) {
                   3995:         $filepath.="/$parts[$count]";
                   3996:         if ((-e $filepath)!=1) {
                   3997: 	    mkdir($filepath,0777);
                   3998:         }
                   3999:     }
1.984     neumanie 4000: 
1.258     www      4001: # Save the file
                   4002:     {
1.1359    raeburn  4003: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4004: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4005: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4006: 	    return '/adm/notfound.html';
                   4007: 	}
1.1090    raeburn  4008:         if ($context eq 'overwrite') {
1.1117    foxr     4009:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4010:             my $target = $filepath.'/'.$file;
                   4011:             if (-e $source) {
                   4012:                 my @info = stat($source);
                   4013:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4014:                     unless (&File::Copy::move($source,$target)) {
                   4015:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4016:                         return "Moving from $source failed";
                   4017:                     }
                   4018:                 } else {
                   4019:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4020:                 }
                   4021:             } else {
                   4022:                 return "Temporary file: $source missing";
                   4023:             }
                   4024:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4025: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4026: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4027: 	    return '/adm/notfound.html';
                   4028: 	}
1.570     albertel 4029: 	close(FH);
1.1051    raeburn  4030:         if ($resizewidth && $resizeheight) {
                   4031:             my $mm = new File::MMagic;
                   4032:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4033:             if ($mime_type =~ m{^image/}) {
                   4034: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4035:             }  
1.977     amueller 4036: 	}
1.258     www      4037:     }
1.1152    raeburn  4038:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4039:         if (ref($mimetype)) {
                   4040:             if ($$mimetype eq '') {
                   4041:                 my $mm = new File::MMagic;
                   4042:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4043:                 $$mimetype = $type;
                   4044:             }
                   4045:         }
                   4046:     }
1.637     raeburn  4047:     if ($parser eq 'parse') {
1.1152    raeburn  4048:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4049:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4050:                                                        $allfiles,$codebase);
                   4051:             unless ($parse_result eq 'ok') {
                   4052:                 &logthis('Failed to parse '.$filepath.$file.
                   4053: 	   	         ' for embedded media: '.$parse_result); 
                   4054:             }
1.637     raeburn  4055:         }
                   4056:     }
1.860     raeburn  4057:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4058:         my $input = $filepath.'/'.$file;
                   4059:         my $output = $filepath.'/'.'tn-'.$file;
                   4060:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4061:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4062:         system({$args[0]} @args);
1.860     raeburn  4063:         if (-e $filepath.'/'.'tn-'.$file) {
                   4064:             $fetchthumb  = 1; 
                   4065:         }
                   4066:     }
1.858     raeburn  4067:  
1.259     www      4068: # Notify homeserver to grep it
                   4069: #
1.984     neumanie 4070:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4071:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4072:     if ($fetchresult eq 'ok') {
1.860     raeburn  4073:         if ($fetchthumb) {
                   4074:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4075:             if ($thumbresult ne 'ok') {
                   4076:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4077:                          $docuhome.': '.$thumbresult);
                   4078:             }
                   4079:         }
1.259     www      4080: #
1.258     www      4081: # Return the URL to it
1.494     albertel 4082:         return '/uploaded/'.$path.$file;
1.263     www      4083:     } else {
1.494     albertel 4084:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4085: 		 ': '.$fetchresult);
1.263     www      4086:         return '/adm/notfound.html';
1.858     raeburn  4087:     }
1.493     albertel 4088: }
                   4089: 
1.637     raeburn  4090: sub extract_embedded_items {
1.961     raeburn  4091:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4092:     my @state = ();
1.1164    raeburn  4093:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4094:     my %javafiles = (
                   4095:                       codebase => '',
                   4096:                       code => '',
                   4097:                       archive => ''
                   4098:                     );
                   4099:     my %mediafiles = (
                   4100:                       src => '',
                   4101:                       movie => '',
                   4102:                      );
1.648     raeburn  4103:     my $p;
                   4104:     if ($content) {
                   4105:         $p = HTML::LCParser->new($content);
                   4106:     } else {
1.961     raeburn  4107:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4108:     }
1.641     albertel 4109:     while (my $t=$p->get_token()) {
1.640     albertel 4110: 	if ($t->[0] eq 'S') {
                   4111: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4112: 	    push(@state, $tagname);
1.648     raeburn  4113:             if (lc($tagname) eq 'allow') {
                   4114:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4115:             }
1.640     albertel 4116: 	    if (lc($tagname) eq 'img') {
                   4117: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4118: 	    }
1.886     albertel 4119: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4120:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4121:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4122:                 }
1.886     albertel 4123: 	    }
1.645     raeburn  4124:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4125:                 my $src;
1.645     raeburn  4126:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4127:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4128:                 } else {
1.1164    raeburn  4129:                     if ($attr->{'src'} ne '') {
                   4130:                         $src = $attr->{'src'};
                   4131:                         &add_filetype($allfiles,$src,'src');
                   4132:                     }
                   4133:                 }
                   4134:                 my $text = $p->get_trimmed_text();
                   4135:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4136:                     my @swfargs = split(/,/,$1);
                   4137:                     foreach my $item (@swfargs) {
                   4138:                         $item =~ s/["']//g;
                   4139:                         $item =~ s/^\s+//;
                   4140:                         $item =~ s/\s+$//;
                   4141:                     }
                   4142:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4143:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4144:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4145:                         } else {
                   4146:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4147:                         }
                   4148:                     }
1.645     raeburn  4149:                 }
                   4150:             }
                   4151:             if (lc($tagname) eq 'link') {
                   4152:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4153:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4154:                 }
                   4155:             }
1.640     albertel 4156: 	    if (lc($tagname) eq 'object' ||
                   4157: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4158: 		foreach my $item (keys(%javafiles)) {
                   4159: 		    $javafiles{$item} = '';
                   4160: 		}
1.1164    raeburn  4161:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4162:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4163:                 }
1.640     albertel 4164: 	    }
                   4165: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4166: 		my $name = lc($attr->{'name'});
                   4167: 		foreach my $item (keys(%javafiles)) {
                   4168: 		    if ($name eq $item) {
                   4169: 			$javafiles{$item} = $attr->{'value'};
                   4170: 			last;
                   4171: 		    }
                   4172: 		}
1.1164    raeburn  4173:                 my $pathfrom;
1.640     albertel 4174: 		foreach my $item (keys(%mediafiles)) {
                   4175: 		    if ($name eq $item) {
1.1164    raeburn  4176:                         $pathfrom = $attr->{'value'};
                   4177:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4178: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4179: 			last;
                   4180: 		    }
                   4181: 		}
1.1164    raeburn  4182:                 if ($name eq 'flashvars') {
                   4183:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4184:                 }
                   4185:                 if ($pathfrom ne '') {
                   4186:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4187:                                          $pathfrom);
                   4188:                 }
1.640     albertel 4189: 	    }
                   4190: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4191: 		foreach my $item (keys(%javafiles)) {
                   4192: 		    if ($attr->{$item}) {
                   4193: 			$javafiles{$item} = $attr->{$item};
                   4194: 			last;
                   4195: 		    }
                   4196: 		}
                   4197: 		foreach my $item (keys(%mediafiles)) {
                   4198: 		    if ($attr->{$item}) {
                   4199: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4200: 			last;
                   4201: 		    }
                   4202: 		}
1.1164    raeburn  4203:                 if (lc($tagname) eq 'embed') {
                   4204:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4205:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4206:                                              $attr->{'src'});
                   4207:                     }
                   4208:                 }
1.640     albertel 4209: 	    }
1.1243    raeburn  4210:             if (lc($tagname) eq 'iframe') {
                   4211:                 my $src = $attr->{'src'} ;
                   4212:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4213:                     &add_filetype($allfiles,$src,'src');
                   4214:                 } elsif ($src =~ m{^/}) {
                   4215:                     if ($env{'request.course.id'}) {
                   4216:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4217:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4218:                         my $url = &hreflocation('',$fullpath);
                   4219:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4220:                             my $relpath = $1;
                   4221:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4222:                                 &add_filetype($allfiles,$1,'src');
                   4223:                             }
                   4224:                         }
                   4225:                     }
                   4226:                 }
                   4227:             }
1.1164    raeburn  4228:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4229:                 pop(@state);
1.1164    raeburn  4230:             }
1.640     albertel 4231: 	} elsif ($t->[0] eq 'E') {
                   4232: 	    my ($tagname) = ($t->[1]);
                   4233: 	    if ($javafiles{'codebase'} ne '') {
                   4234: 		$javafiles{'codebase'} .= '/';
                   4235: 	    }  
                   4236: 	    if (lc($tagname) eq 'applet' ||
                   4237: 		lc($tagname) eq 'object' ||
                   4238: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4239: 		) {
                   4240: 		foreach my $item (keys(%javafiles)) {
                   4241: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4242: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4243: 			&add_filetype($allfiles,$file,$item);
                   4244: 		    }
                   4245: 		}
                   4246: 	    } 
                   4247: 	    pop @state;
                   4248: 	}
                   4249:     }
1.1164    raeburn  4250:     foreach my $id (sort(keys(%flashvars))) {
                   4251:         if ($shockwave{$id} ne '') {
                   4252:             my @pairs = split(/\&/,$flashvars{$id});
                   4253:             foreach my $pair (@pairs) {
                   4254:                 my ($key,$value) = split(/\=/,$pair);
                   4255:                 if ($key eq 'thumb') {
                   4256:                     &add_filetype($allfiles,$value,$key);
                   4257:                 } elsif ($key eq 'content') {
                   4258:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4259:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4260:                     if ($ext ne '') {
                   4261:                         &add_filetype($allfiles,$path.$value,$ext);
                   4262:                     }
                   4263:                 }
                   4264:             }
                   4265:         }
                   4266:     }
1.637     raeburn  4267:     return 'ok';
                   4268: }
                   4269: 
1.639     albertel 4270: sub add_filetype {
                   4271:     my ($allfiles,$file,$type)=@_;
                   4272:     if (exists($allfiles->{$file})) {
                   4273: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4274: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4275: 	}
                   4276:     } else {
                   4277: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4278:     }
                   4279: }
                   4280: 
1.1164    raeburn  4281: sub embedded_dependency {
                   4282:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4283:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4284:         if (($identifier ne '') &&
                   4285:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4286:             ($pathfrom ne '')) {
                   4287:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4288:             foreach my $dep (@{$related->{$identifier}}) {
                   4289:                 &add_filetype($allfiles,$path.$dep,'object');
                   4290:             }
                   4291:         }
                   4292:     }
                   4293:     return;
                   4294: }
                   4295: 
1.493     albertel 4296: sub removeuploadedurl {
1.984     neumanie 4297:     my ($url)=@_;	
                   4298:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4299:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4300: }
                   4301: 
                   4302: sub removeuserfile {
                   4303:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4304:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4305:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4306:     if ($result eq 'ok') {	
1.798     raeburn  4307:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4308:             my $metafile = $fname.'.meta';
                   4309:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4310: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4311:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4312:             my $sqlresult = 
1.823     albertel 4313:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4314:                                         'portfolio_metadata',$group,
                   4315:                                         'delete');
1.798     raeburn  4316:         }
                   4317:     }
                   4318:     return $result;
1.257     www      4319: }
1.15      www      4320: 
1.530     albertel 4321: sub mkdiruserfile {
                   4322:     my ($docuname,$docudom,$dir)=@_;
                   4323:     my $home=&homeserver($docuname,$docudom);
                   4324:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4325: }
                   4326: 
1.531     albertel 4327: sub renameuserfile {
                   4328:     my ($docuname,$docudom,$old,$new)=@_;
                   4329:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4330:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4331:                         &escape("$old").':'.&escape("$new"),$home);
                   4332:     if ($result eq 'ok') {
                   4333:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4334:             my $oldmeta = $old.'.meta';
                   4335:             my $newmeta = $new.'.meta';
                   4336:             my $metaresult = 
                   4337:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4338: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4339:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4340:             my $sqlresult = 
1.823     albertel 4341:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4342:                                         'portfolio_metadata',$group,
                   4343:                                         'delete');
1.798     raeburn  4344:         }
                   4345:     }
                   4346:     return $result;
1.531     albertel 4347: }
                   4348: 
1.14      www      4349: # ------------------------------------------------------------------------- Log
                   4350: 
                   4351: sub log {
                   4352:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4353:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4354: }
                   4355: 
                   4356: # ------------------------------------------------------------------ Course Log
1.352     www      4357: #
                   4358: # This routine flushes several buffers of non-mission-critical nature
                   4359: #
1.157     www      4360: 
                   4361: sub flushcourselogs {
1.352     www      4362:     &logthis('Flushing log buffers');
                   4363: #
                   4364: # course logs
                   4365: # This is a log of all transactions in a course, which can be used
                   4366: # for data mining purposes
                   4367: #
                   4368: # It also collects the courseid database, which lists last transaction
                   4369: # times and course titles for all courseids
                   4370: #
                   4371:     my %courseidbuffer=();
1.921     raeburn  4372:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4373:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4374: 		          &escape($courselogs{$crsid}),
                   4375: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4376: 	    delete $courselogs{$crsid};
                   4377:         } else {
                   4378:             &logthis('Failed to flush log buffer for '.$crsid);
                   4379:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4380:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4381:                         " exceeded maximum size, deleting.</font>");
                   4382:                delete $courselogs{$crsid};
                   4383:             }
1.352     www      4384:         }
1.920     raeburn  4385:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4386:             'description' => $coursedescrbuf{$crsid},
                   4387:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4388:             'type'        => $coursetypebuf{$crsid},
                   4389:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4390:         };
1.191     harris41 4391:     }
1.352     www      4392: #
                   4393: # Write course id database (reverse lookup) to homeserver of courses 
                   4394: # Is used in pickcourse
                   4395: #
1.840     albertel 4396:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4397:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4398:                                     $courseidbuffer{$crs_home},
                   4399:                                     $crs_home,'timeonly');
1.352     www      4400:     }
                   4401: #
                   4402: # File accesses
                   4403: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4404: #
1.449     matthew  4405:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4406:         if ($entry =~ /___count$/) {
                   4407:             my ($dom,$name);
1.807     albertel 4408:             ($dom,$name,undef)=
1.811     albertel 4409: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4410:             if (! defined($dom) || $dom eq '' || 
                   4411:                 ! defined($name) || $name eq '') {
1.620     albertel 4412:                 my $cid = $env{'request.course.id'};
                   4413:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4414:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4415:             }
1.450     matthew  4416:             my $value = $accesshash{$entry};
                   4417:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4418:             my %temphash=($url => $value);
1.449     matthew  4419:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4420:             if ($result eq 'ok') {
                   4421:                 delete $accesshash{$entry};
                   4422:             }
                   4423:         } else {
1.811     albertel 4424:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4425:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4426:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4427:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4428:                 delete $accesshash{$entry};
                   4429:             }
1.185     www      4430:         }
1.191     harris41 4431:     }
1.352     www      4432: #
                   4433: # Roles
                   4434: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4435: #
1.800     albertel 4436:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4437:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4438: 	    split(/\:/,$entry);
                   4439:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4440:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4441:                 $rudom,$runame) eq 'ok') {
                   4442: 	    delete $userrolehash{$entry};
                   4443:         }
                   4444:     }
1.662     raeburn  4445: #
1.1334    raeburn  4446: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4447: #
                   4448:     my %domrolebuffer = ();
1.1000    raeburn  4449:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4450:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4451:         if ($domrolebuffer{$rudom}) {
                   4452:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4453:                       '='.&escape($domainrolehash{$entry});
                   4454:         } else {
                   4455:             $domrolebuffer{$rudom}.=&escape($entry).
                   4456:                       '='.&escape($domainrolehash{$entry});
                   4457:         }
                   4458:         delete $domainrolehash{$entry};
                   4459:     }
                   4460:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4461: 	my %servers;
                   4462: 	if (defined(&domain($dom,'primary'))) {
                   4463: 	    my $primary=&domain($dom,'primary');
                   4464: 	    my $hostname=&hostname($primary);
                   4465: 	    $servers{$primary} = $hostname;
                   4466: 	} else { 
                   4467: 	    %servers = &get_servers($dom,'library');
                   4468: 	}
1.841     albertel 4469: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4470: 	    if (&reply('domroleput:'.$dom.':'.
                   4471: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4472: 		last;
                   4473: 	    } else {  
1.841     albertel 4474: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4475: 	    }
1.662     raeburn  4476:         }
                   4477:     }
1.186     www      4478:     $dumpcount++;
1.157     www      4479: }
                   4480: 
                   4481: sub courselog {
                   4482:     my $what=shift;
1.158     www      4483:     $what=time.':'.$what;
1.620     albertel 4484:     unless ($env{'request.course.id'}) { return ''; }
                   4485:     $coursedombuf{$env{'request.course.id'}}=
                   4486:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4487:     $coursenumbuf{$env{'request.course.id'}}=
                   4488:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4489:     $coursehombuf{$env{'request.course.id'}}=
                   4490:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4491:     $coursedescrbuf{$env{'request.course.id'}}=
                   4492:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4493:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4494:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4495:     $courseownerbuf{$env{'request.course.id'}}=
                   4496:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4497:     $coursetypebuf{$env{'request.course.id'}}=
                   4498:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4499:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4500: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4501:     } else {
1.620     albertel 4502: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4503:     }
1.620     albertel 4504:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4505: 	&flushcourselogs();
                   4506:     }
1.158     www      4507: }
                   4508: 
                   4509: sub courseacclog {
                   4510:     my $fnsymb=shift;
1.620     albertel 4511:     unless ($env{'request.course.id'}) { return ''; }
                   4512:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4513:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4514:         $what.=':POST';
1.583     matthew  4515:         # FIXME: Probably ought to escape things....
1.800     albertel 4516: 	foreach my $key (keys(%env)) {
                   4517:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4518:                 my $formitem = $1;
                   4519:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4520:                     $what.=':'.$formitem.'='.$env{$key};
                   4521:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4522:                     $what.=':'.$formitem.'='.$env{$key};
                   4523:                 }
1.158     www      4524:             }
1.191     harris41 4525:         }
1.583     matthew  4526:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4527:         # FIXME: We should not be depending on a form parameter that someone
                   4528:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4529:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4530:             $what.= ':POST';
                   4531:             # FIXME: Probably ought to escape things....
                   4532:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4533:                                  'crsdiscuss') {
1.620     albertel 4534:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4535:             }
                   4536:         }
1.158     www      4537:     }
                   4538:     &courselog($what);
1.149     www      4539: }
                   4540: 
1.185     www      4541: sub countacc {
                   4542:     my $url=&declutter(shift);
1.458     matthew  4543:     return if (! defined($url) || $url eq '');
1.620     albertel 4544:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4545: #
                   4546: # Mark that this url was used in this course
                   4547: #
1.620     albertel 4548:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4549: #
                   4550: # Increase the access count for this resource in this child process
                   4551: #
1.281     www      4552:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4553:     $accesshash{$key}++;
1.185     www      4554: }
1.349     www      4555: 
1.361     www      4556: sub linklog {
                   4557:     my ($from,$to)=@_;
                   4558:     $from=&declutter($from);
                   4559:     $to=&declutter($to);
                   4560:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4561:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4562: }
1.1160    www      4563: 
                   4564: sub statslog {
                   4565:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4566:     if ($users<2) { return; }
                   4567:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4568:             'course'       => $env{'request.course.id'},
                   4569:             'sections'     => '"all"',
                   4570:             'num_students' => $users,
                   4571:             'part'         => $part,
                   4572:             'symb'         => $symb,
                   4573:             'mean_tries'   => $av_attempts,
                   4574:             'deg_of_diff'  => $degdiff});
                   4575:     foreach my $key (keys(%dynstore)) {
                   4576:         $accesshash{$key}=$dynstore{$key};
                   4577:     }
                   4578: }
1.361     www      4579:   
1.349     www      4580: sub userrolelog {
                   4581:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4582:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4583:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4584:        $userrolehash
                   4585:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4586:                     =$tend.':'.$tstart;
1.662     raeburn  4587:     }
1.1169    droeschl 4588:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4589:        $userrolehash
                   4590:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4591:                     =$tend.':'.$tstart;
                   4592:     }
1.1334    raeburn  4593:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4594:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4595:        $domainrolehash
                   4596:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4597:                     = $tend.':'.$tstart;
                   4598:     }
1.351     www      4599: }
                   4600: 
1.957     raeburn  4601: sub courserolelog {
                   4602:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4603:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4604:         my $cdom = $1;
                   4605:         my $cnum = $2;
                   4606:         my $sec = $3;
                   4607:         my $namespace = 'rolelog';
                   4608:         my %storehash = (
                   4609:                            role    => $trole,
                   4610:                            start   => $tstart,
                   4611:                            end     => $tend,
                   4612:                            selfenroll => $selfenroll,
                   4613:                            context    => $context,
                   4614:                         );
                   4615:         if ($trole eq 'gr') {
                   4616:             $namespace = 'groupslog';
                   4617:             $storehash{'group'} = $sec;
                   4618:         } else {
                   4619:             $storehash{'section'} = $sec;
                   4620:         }
1.1188    raeburn  4621:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4622:                    $domain,$cnum,$cdom);
1.1184    raeburn  4623:         if (($trole ne 'st') || ($sec ne '')) {
                   4624:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4625:         }
                   4626:     }
                   4627:     return;
                   4628: }
                   4629: 
1.1184    raeburn  4630: sub domainrolelog {
                   4631:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4632:     if ($area =~ m{^/($match_domain)/$}) {
                   4633:         my $cdom = $1;
                   4634:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4635:         my $namespace = 'rolelog';
                   4636:         my %storehash = (
                   4637:                            role    => $trole,
                   4638:                            start   => $tstart,
                   4639:                            end     => $tend,
                   4640:                            context => $context,
                   4641:                         );
1.1188    raeburn  4642:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4643:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4644:     }
                   4645:     return;
                   4646: 
                   4647: }
                   4648: 
                   4649: sub coauthorrolelog {
                   4650:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4651:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4652:         my $audom = $1;
                   4653:         my $auname = $2;
                   4654:         my $namespace = 'rolelog';
                   4655:         my %storehash = (
                   4656:                            role    => $trole,
                   4657:                            start   => $tstart,
                   4658:                            end     => $tend,
                   4659:                            context => $context,
                   4660:                         );
1.1188    raeburn  4661:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4662:                    $domain,$auname,$audom);
1.1184    raeburn  4663:     }
                   4664:     return;
                   4665: }
                   4666: 
1.351     www      4667: sub get_course_adv_roles {
1.948     raeburn  4668:     my ($cid,$codes) = @_;
1.620     albertel 4669:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4670:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4671:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4672:     my %nothide=();
1.800     albertel 4673:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4674:         if ($user !~ /:/) {
                   4675: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4676:         } else {
                   4677:             $nothide{$user}=1;
                   4678:         }
1.470     www      4679:     }
1.1219    raeburn  4680:     my @possdoms = ($coursehash{'domain'});
                   4681:     if ($coursehash{'checkforpriv'}) {
                   4682:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4683:     }
1.351     www      4684:     my %returnhash=();
                   4685:     my %dumphash=
                   4686:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4687:     my $now=time;
1.997     raeburn  4688:     my %privileged;
1.1000    raeburn  4689:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4690: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4691:         if (($tstart) && ($tstart<0)) { next; }
                   4692:         if (($tend) && ($tend<$now)) { next; }
                   4693:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4694:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4695: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4696:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4697:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4698: 	if ($role eq 'cr') { next; }
1.948     raeburn  4699:         if ($codes) {
                   4700:             if ($section) { $role .= ':'.$section; }
                   4701:             if ($returnhash{$role}) {
                   4702:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4703:             } else {
                   4704:                 $returnhash{$role}=$username.':'.$domain;
                   4705:             }
1.351     www      4706:         } else {
1.988     raeburn  4707:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4708:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4709:             if ($returnhash{$key}) {
                   4710: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4711:             } else {
                   4712:                 $returnhash{$key}=$username.':'.$domain;
                   4713:             }
1.351     www      4714:         }
1.948     raeburn  4715:     }
1.400     www      4716:     return %returnhash;
                   4717: }
                   4718: 
                   4719: sub get_my_roles {
1.937     raeburn  4720:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4721:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4722:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4723:     my (%dumphash,%nothide);
1.1086    raeburn  4724:     if ($context eq 'userroles') {
1.1166    raeburn  4725:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4726:     } else {
1.1219    raeburn  4727:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4728:         if ($hidepriv) {
                   4729:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4730:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4731:                 if ($user !~ /:/) {
                   4732:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4733:                 } else {
                   4734:                     $nothide{$user} = 1;
                   4735:                 }
                   4736:             }
                   4737:         }
1.858     raeburn  4738:     }
1.400     www      4739:     my %returnhash=();
                   4740:     my $now=time;
1.999     raeburn  4741:     my %privileged;
1.800     albertel 4742:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4743:         my ($role,$tend,$tstart);
                   4744:         if ($context eq 'userroles') {
1.1149    raeburn  4745:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4746: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4747:         } else {
                   4748:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4749:         }
1.400     www      4750:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4751:         my $status = 'active';
1.939     raeburn  4752:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4753:             $status = 'previous';
                   4754:         } 
                   4755:         if (($tstart) && ($now<$tstart)) {
                   4756:             $status = 'future';
                   4757:         }
                   4758:         if (ref($types) eq 'ARRAY') {
                   4759:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4760:                 next;
                   4761:             } 
                   4762:         } else {
                   4763:             if ($status ne 'active') {
                   4764:                 next;
                   4765:             }
                   4766:         }
1.867     raeburn  4767:         my ($rolecode,$username,$domain,$section,$area);
                   4768:         if ($context eq 'userroles') {
1.1186    raeburn  4769:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4770:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4771:         } else {
                   4772:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4773:         }
1.832     raeburn  4774:         if (ref($roledoms) eq 'ARRAY') {
                   4775:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4776:                 next;
                   4777:             }
                   4778:         }
                   4779:         if (ref($roles) eq 'ARRAY') {
                   4780:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4781:                 if ($role =~ /^cr\//) {
                   4782:                     if (!grep(/^cr$/,@{$roles})) {
                   4783:                         next;
                   4784:                     }
1.1104    raeburn  4785:                 } elsif ($role =~ /^gr\//) {
                   4786:                     if (!grep(/^gr$/,@{$roles})) {
                   4787:                         next;
                   4788:                     }
1.922     raeburn  4789:                 } else {
                   4790:                     next;
                   4791:                 }
1.832     raeburn  4792:             }
1.867     raeburn  4793:         }
1.937     raeburn  4794:         if ($hidepriv) {
1.1219    raeburn  4795:             my @privroles = ('dc','su');
1.999     raeburn  4796:             if ($context eq 'userroles') {
1.1219    raeburn  4797:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4798:             } else {
1.1219    raeburn  4799:                 my $possdoms = [$domain];
                   4800:                 if (ref($roledoms) eq 'ARRAY') {
                   4801:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4802:                 }
1.1219    raeburn  4803:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4804:                     if (!$nothide{$username.':'.$domain}) {
                   4805:                         next;
                   4806:                     }
                   4807:                 }
1.937     raeburn  4808:             }
                   4809:         }
1.933     raeburn  4810:         if ($withsec) {
                   4811:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4812:                 $tstart.':'.$tend;
                   4813:         } else {
                   4814:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4815:         }
1.832     raeburn  4816:     }
1.373     www      4817:     return %returnhash;
1.399     www      4818: }
                   4819: 
1.1333    raeburn  4820: sub get_all_adhocroles {
                   4821:     my ($dom) = @_;
                   4822:     my @roles_by_num = ();
                   4823:     my %domdefaults = &get_domain_defaults($dom);
                   4824:     my (%description,%access_in_dom,%access_info);
                   4825:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4826:         my $count = 0;
                   4827:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4828:         my %ordered;
                   4829:         foreach my $role (sort(keys(%domcurrent))) {
                   4830:             my ($order,$desc,$access_in_dom);
                   4831:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4832:                 $order = $domcurrent{$role}{'order'};
                   4833:                 $desc = $domcurrent{$role}{'desc'};
                   4834:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4835:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4836:             }
                   4837:             if ($order eq '') {
                   4838:                 $order = $count;
                   4839:             }
                   4840:             $ordered{$order} = $role;
                   4841:             if ($desc ne '') {
                   4842:                 $description{$role} = $desc;
                   4843:             } else {
                   4844:                 $description{$role}= $role;
                   4845:             }
                   4846:             $count++;
                   4847:         }
                   4848:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4849:             push(@roles_by_num,$ordered{$item});
                   4850:         }
                   4851:     }
                   4852:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4853: }
                   4854: 
1.1332    raeburn  4855: sub get_my_adhocroles {
1.1333    raeburn  4856:     my ($cid,$checkreg) = @_;
                   4857:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4858:     if ($env{'request.course.id'} eq $cid) {
                   4859:         $cdom = $env{'course.'.$cid.'.domain'};
                   4860:         $cnum = $env{'course.'.$cid.'.num'};
                   4861:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4862:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4863:         $cdom = $1;
                   4864:         $cnum = $2;
                   4865:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4866:                                      $cdom,$cnum);
                   4867:     }
                   4868:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4869:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4870:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4871:         if ($rosterhash{$user} ne '') {
                   4872:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4873:             return ([],{}) if ($type eq 'auto');
                   4874:         }
                   4875:     }
                   4876:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4877:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4878:             my $then=$env{'user.login.time'};
                   4879:             my $update=$env{'user.update.time'};
1.1335    raeburn  4880:             if (!$update) {
                   4881:                 $update = $then;
                   4882:             }
                   4883:             my @liveroles;
1.1334    raeburn  4884:             foreach my $role ('dh','da') {
                   4885:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4886:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4887:                     my $limit = $update;
                   4888:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4889:                         $limit = $then;
                   4890:                     }
1.1335    raeburn  4891:                     my $activerole = 1;
                   4892:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4893:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4894:                     if ($activerole) {
                   4895:                         push(@liveroles,$role);
                   4896:                     }
1.1334    raeburn  4897:                 }
1.1332    raeburn  4898:             }
1.1335    raeburn  4899:             if (@liveroles) {
1.1332    raeburn  4900:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4901:                     my ($accessref,$accessinfo,%access_in_dom);
                   4902:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4903:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4904:                         if (@{$roles_by_num}) {
1.1332    raeburn  4905:                             my %settings;
                   4906:                             if ($env{'request.course.id'} eq $cid) {
                   4907:                                 foreach my $envkey (keys(%env)) {
                   4908:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4909:                                         $settings{$1} = $env{$envkey};
                   4910:                                     }
                   4911:                                 }
                   4912:                             } else {
                   4913:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4914:                             }
                   4915:                             my %setincrs;
                   4916:                             if ($settings{'internal.adhocaccess'}) {
                   4917:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4918:                             }
                   4919:                             my @statuses;
                   4920:                             if ($env{'environment.inststatus'}) {
                   4921:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4922:                             }
                   4923:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4924:                             if (ref($accessref) eq 'HASH') {
                   4925:                                 %access_in_dom = %{$accessref};
                   4926:                             }
                   4927:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4928:                                 my ($curraccess,@okstatus,@personnel);
                   4929:                                 if ($setincrs{$role}) {
                   4930:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4931:                                     if ($curraccess eq 'status') {
                   4932:                                         @okstatus = split(/\&/,$rest);
                   4933:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4934:                                         @personnel = split(/\&/,$rest);
                   4935:                                     }
                   4936:                                 } else {
                   4937:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4938:                                     if (ref($accessinfo) eq 'HASH') {
                   4939:                                         if ($curraccess eq 'status') {
                   4940:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4941:                                                 @okstatus = @{$accessinfo->{$role}};
                   4942:                                             }
                   4943:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4944:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4945:                                                 @personnel = @{$accessinfo->{$role}};
                   4946:                                             }
1.1332    raeburn  4947:                                         }
                   4948:                                     }
                   4949:                                 }
                   4950:                                 if ($curraccess eq 'none') {
                   4951:                                     next;
                   4952:                                 } elsif ($curraccess eq 'all') {
                   4953:                                     push(@possroles,$role);
1.1336    raeburn  4954:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4955:                                     if (grep(/^dh$/,@liveroles)) {
                   4956:                                         push(@possroles,$role);
                   4957:                                     } else {
                   4958:                                         next;
                   4959:                                     }
1.1336    raeburn  4960:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4961:                                     if (grep(/^da$/,@liveroles)) {
                   4962:                                         push(@possroles,$role);
                   4963:                                     } else {
                   4964:                                         next;
                   4965:                                     }
1.1332    raeburn  4966:                                 } elsif ($curraccess eq 'status') {
                   4967:                                     if (@okstatus) {
                   4968:                                         if (!@statuses) {
                   4969:                                             if (grep(/^default$/,@okstatus)) {
                   4970:                                                 push(@possroles,$role);
                   4971:                                             }
                   4972:                                         } else {
                   4973:                                             foreach my $status (@okstatus) {
                   4974:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4975:                                                     push(@possroles,$role);
                   4976:                                                     last;
                   4977:                                                 }
                   4978:                                             }
                   4979:                                         }
                   4980:                                     }
                   4981:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4982:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4983:                                         if ($curraccess eq 'exc') {
                   4984:                                             push(@possroles,$role);
                   4985:                                         }
                   4986:                                     } elsif ($curraccess eq 'inc') {
                   4987:                                         push(@possroles,$role);
                   4988:                                     }
                   4989:                                 }
                   4990:                             }
                   4991:                         }
                   4992:                     }
                   4993:                 }
                   4994:             }
                   4995:         }
                   4996:     }
1.1333    raeburn  4997:     unless (ref($description) eq 'HASH') {
                   4998:         if (ref($roles_by_num) eq 'ARRAY') {
                   4999:             my %desc;
                   5000:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5001:             $description = \%desc;
                   5002:         } else {
                   5003:             $description = {};
                   5004:         }
                   5005:     }
                   5006:     return (\@possroles,$description);
1.1332    raeburn  5007: }
                   5008: 
1.399     www      5009: # ----------------------------------------------------- Frontpage Announcements
                   5010: #
                   5011: #
                   5012: 
                   5013: sub postannounce {
                   5014:     my ($server,$text)=@_;
1.844     albertel 5015:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5016:     unless ($text=~/\w/) { $text=''; }
                   5017:     return &reply('setannounce:'.&escape($text),$server);
                   5018: }
                   5019: 
                   5020: sub getannounce {
1.448     albertel 5021: 
1.1359    raeburn  5022:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5023: 	my $announcement='';
1.800     albertel 5024: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5025: 	close($fh);
1.399     www      5026: 	if ($announcement=~/\w/) { 
                   5027: 	    return 
                   5028:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5029:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5030: 	} else {
                   5031: 	    return '';
                   5032: 	}
                   5033:     } else {
                   5034: 	return '';
                   5035:     }
1.351     www      5036: }
1.353     www      5037: 
                   5038: # ---------------------------------------------------------- Course ID routines
                   5039: # Deal with domain's nohist_courseid.db files
                   5040: #
                   5041: 
                   5042: sub courseidput {
1.921     raeburn  5043:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5044:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5045:     my $outcome;
                   5046:     if ($caller eq 'timeonly') {
                   5047:         my $cids = '';
                   5048:         foreach my $item (keys(%$storehash)) {
                   5049:             $cids.=&escape($item).'&';
                   5050:         }
                   5051:         $cids=~s/\&$//;
                   5052:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5053:                           $coursehome);       
                   5054:     } else {
                   5055:         my $items = '';
                   5056:         foreach my $item (keys(%$storehash)) {
                   5057:             $items.= &escape($item).'='.
                   5058:                      &freeze_escape($$storehash{$item}).'&';
                   5059:         }
                   5060:         $items=~s/\&$//;
                   5061:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5062:                           $coursehome);
1.918     raeburn  5063:     }
                   5064:     if ($outcome eq 'unknown_cmd') {
                   5065:         my $what;
                   5066:         foreach my $cid (keys(%$storehash)) {
                   5067:             $what .= &escape($cid).'=';
1.921     raeburn  5068:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5069:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5070:             }
                   5071:             $what =~ s/\:$/&/;
                   5072:         }
                   5073:         $what =~ s/\&$//;  
                   5074:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5075:     } else {
                   5076:         return $outcome;
                   5077:     }
1.353     www      5078: }
                   5079: 
                   5080: sub courseiddump {
1.921     raeburn  5081:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5082:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5083:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5084:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5085:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5086:     my $as_hash = 1;
                   5087:     my %returnhash;
                   5088:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5089:     my %libserv = &all_library();
                   5090:     foreach my $tryserver (keys(%libserv)) {
                   5091:         if ( (  $hostidflag == 1 
                   5092: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5093: 	     || (!defined($hostidflag)) ) {
                   5094: 
1.918     raeburn  5095: 	    if (($domfilter eq '') ||
                   5096: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5097:                 my $rep;
                   5098:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5099:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5100:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5101:                                 &escape($descfilter), &escape($instcodefilter), 
                   5102:                                 &escape($ownerfilter), &escape($coursefilter),
                   5103:                                 &escape($typefilter), &escape($regexp_ok), 
                   5104:                                 $as_hash, &escape($selfenrollonly), 
                   5105:                                 &escape($catfilter), $showhidden, $caller, 
                   5106:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5107:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5108:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5109:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5110:                 } else {
                   5111:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5112:                              $sincefilter.':'.&escape($descfilter).':'.
                   5113:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5114:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5115:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5116:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5117:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5118:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5119:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5120:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5121:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5122:                 }
                   5123:                      
1.918     raeburn  5124:                 my @pairs=split(/\&/,$rep);
                   5125:                 foreach my $item (@pairs) {
                   5126:                     my ($key,$value)=split(/\=/,$item,2);
                   5127:                     $key = &unescape($key);
                   5128:                     next if ($key =~ /^error: 2 /);
                   5129:                     my $result = &thaw_unescape($value);
                   5130:                     if (ref($result) eq 'HASH') {
                   5131:                         $returnhash{$key}=$result;
                   5132:                     } else {
1.921     raeburn  5133:                         my @responses = split(/:/,$value);
                   5134:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5135:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5136:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5137:                         }
1.1008    raeburn  5138:                     }
1.353     www      5139:                 }
                   5140:             }
                   5141:         }
                   5142:     }
                   5143:     return %returnhash;
                   5144: }
                   5145: 
1.1055    raeburn  5146: sub courselastaccess {
                   5147:     my ($cdom,$cnum,$hostidref) = @_;
                   5148:     my %returnhash;
                   5149:     if ($cdom && $cnum) {
                   5150:         my $chome = &homeserver($cnum,$cdom);
                   5151:         if ($chome ne 'no_host') {
                   5152:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5153:             &extract_lastaccess(\%returnhash,$rep);
                   5154:         }
                   5155:     } else {
                   5156:         if (!$cdom) { $cdom=''; }
                   5157:         my %libserv = &all_library();
                   5158:         foreach my $tryserver (keys(%libserv)) {
                   5159:             if (ref($hostidref) eq 'ARRAY') {
                   5160:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5161:             } 
                   5162:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5163:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5164:                 &extract_lastaccess(\%returnhash,$rep);
                   5165:             }
                   5166:         }
                   5167:     }
                   5168:     return %returnhash;
                   5169: }
                   5170: 
                   5171: sub extract_lastaccess {
                   5172:     my ($returnhash,$rep) = @_;
                   5173:     if (ref($returnhash) eq 'HASH') {
                   5174:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5175:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5176:                  $rep eq '') {
                   5177:             my @pairs=split(/\&/,$rep);
                   5178:             foreach my $item (@pairs) {
                   5179:                 my ($key,$value)=split(/\=/,$item,2);
                   5180:                 $key = &unescape($key);
                   5181:                 next if ($key =~ /^error: 2 /);
                   5182:                 $returnhash->{$key} = &thaw_unescape($value);
                   5183:             }
                   5184:         }
                   5185:     }
                   5186:     return;
                   5187: }
                   5188: 
1.658     raeburn  5189: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5190: 
                   5191: sub dcmailput {
1.685     raeburn  5192:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5193:     my $status = &Apache::lonnet::critical(
1.740     www      5194:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5195:        &escape($message),$server);
1.662     raeburn  5196:     return $status;
                   5197: }
                   5198: 
1.658     raeburn  5199: sub dcmaildump {
                   5200:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5201:     my %returnhash=();
1.846     albertel 5202: 
                   5203:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5204:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5205:                                                          &escape($enddate).':';
                   5206: 	my @esc_senders=map { &escape($_)} @$senders;
                   5207: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5208: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5209:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5210:             if (($key) && ($value)) {
                   5211:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5212:             }
                   5213:         }
                   5214:     }
                   5215:     return %returnhash;
                   5216: }
1.662     raeburn  5217: # ---------------------------------------------------------- Domain roles
                   5218: 
                   5219: sub get_domain_roles {
                   5220:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5221:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5222:         $startdate = '.';
                   5223:     }
1.1018    raeburn  5224:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5225:         $enddate = '.';
                   5226:     }
1.922     raeburn  5227:     my $rolelist;
                   5228:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5229:         $rolelist = join('&',@{$roles});
1.922     raeburn  5230:     }
1.662     raeburn  5231:     my %personnel = ();
1.841     albertel 5232: 
                   5233:     my %servers = &get_servers($dom,'library');
                   5234:     foreach my $tryserver (keys(%servers)) {
                   5235: 	%{$personnel{$tryserver}}=();
                   5236: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5237: 					    &escape($startdate).':'.
                   5238: 					    &escape($enddate).':'.
                   5239: 					    &escape($rolelist), $tryserver))) {
                   5240: 	    my ($key,$value) = split(/\=/,$line,2);
                   5241: 	    if (($key) && ($value)) {
                   5242: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5243: 	    }
                   5244: 	}
1.662     raeburn  5245:     }
                   5246:     return %personnel;
                   5247: }
1.658     raeburn  5248: 
1.1332    raeburn  5249: sub get_active_domroles {
                   5250:     my ($dom,$roles) = @_;
                   5251:     return () unless (ref($roles) eq 'ARRAY');
                   5252:     my $now = time;
                   5253:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5254:     my %domroles;
                   5255:     foreach my $server (keys(%dompersonnel)) {
                   5256:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5257:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5258:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5259:         }
                   5260:     }
                   5261:     return %domroles;
                   5262: }
                   5263: 
1.1057    www      5264: # ----------------------------------------------------------- Interval timing 
1.149     www      5265: 
1.1153    www      5266: {
                   5267: # Caches needed for speedup of navmaps
                   5268: # We don't want to cache this for very long at all (5 seconds at most)
                   5269: # 
                   5270: # The user for whom we cache
                   5271: my $cachedkey='';
                   5272: # The cached times for this user
                   5273: my %cachedtimes=();
                   5274: # When this was last done
1.1282    raeburn  5275: my $cachedtime='';
1.1153    www      5276: 
                   5277: sub load_all_first_access {
1.1308    raeburn  5278:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5279:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5280:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5281:         (!$ignorecache)) {
1.1154    raeburn  5282:         return;
                   5283:     }
                   5284:     $cachedtime=time;
                   5285:     $cachedkey=$uname.':'.$udom;
                   5286:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5287: }
                   5288: 
1.504     albertel 5289: sub get_first_access {
1.1308    raeburn  5290:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5291:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5292:     if ($argsymb) { $symb=$argsymb; }
                   5293:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5294:     if ($argmap) { $map = $argmap; }
1.926     albertel 5295:     if ($type eq 'course') {
                   5296: 	$res='course';
                   5297:     } elsif ($type eq 'map') {
1.588     albertel 5298: 	$res=&symbread($map);
                   5299:     } else {
                   5300: 	$res=$symb;
                   5301:     }
1.1308    raeburn  5302:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5303:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5304: }
                   5305: 
                   5306: sub set_first_access {
1.1162    raeburn  5307:     my ($type,$interval)=@_;
1.790     albertel 5308:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5309:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5310:     if ($type eq 'course') {
                   5311: 	$res='course';
                   5312:     } elsif ($type eq 'map') {
1.588     albertel 5313: 	$res=&symbread($map);
                   5314:     } else {
                   5315: 	$res=$symb;
                   5316:     }
1.1153    www      5317:     $cachedkey='';
1.1162    raeburn  5318:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5319:     if ($firstaccess) {
                   5320:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5321:                  "to set new value (type: $type, extent: $res) for $uname:$udom ". 
                   5322:                  "in $courseid"); 
                   5323:         return 'already_set';
                   5324:     } else {
1.1162    raeburn  5325:         my $start = time;
                   5326: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5327:                           $udom,$uname);
                   5328:         if ($putres eq 'ok') {
                   5329:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5330:                  $udom,$uname); 
                   5331:             &appenv(
                   5332:                      {
                   5333:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5334:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5335:                      }
                   5336:                   );
1.1365    raeburn  5337:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5338:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5339:             }
1.1386    raeburn  5340:         } elsif ($putres ne 'refused') {
                   5341:             &logthis("Result: $putres when attempting to set first access time ".
                   5342:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5343:         }
                   5344:         return $putres;
1.505     albertel 5345:     }
                   5346:     return 'already_set';
1.504     albertel 5347: }
1.1153    www      5348: }
1.1282    raeburn  5349: 
1.110     www      5350: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5351: 
                   5352: sub expirespread {
                   5353:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5354:     my $cid=$env{'request.course.id'}; 
1.110     www      5355:     if ($cid) {
                   5356:        my $now=time;
                   5357:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5358:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5359:                             $env{'course.'.$cid.'.num'}.
1.110     www      5360: 	        	    ':nohist_expirationdates:'.
                   5361:                             &escape($key).'='.$now,
1.620     albertel 5362:                             $env{'course.'.$cid.'.home'})
1.110     www      5363:     }
                   5364:     return 'ok';
1.14      www      5365: }
                   5366: 
1.109     www      5367: # ----------------------------------------------------- Devalidate Spreadsheets
                   5368: 
                   5369: sub devalidate {
1.325     www      5370:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5371:     my $cid=$env{'request.course.id'}; 
1.109     www      5372:     if ($cid) {
1.391     matthew  5373:         # delete the stored spreadsheets for
                   5374:         # - the student level sheet of this user in course's homespace
                   5375:         # - the assessment level sheet for this resource 
                   5376:         #   for this user in user's homespace
1.553     albertel 5377: 	# - current conditional state info
1.325     www      5378: 	my $key=$uname.':'.$udom.':';
1.109     www      5379:         my $status=
1.299     matthew  5380: 	    &del('nohist_calculatedsheets',
1.391     matthew  5381: 		 [$key.'studentcalc:'],
1.620     albertel 5382: 		 $env{'course.'.$cid.'.domain'},
                   5383: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5384: 		.' '.
                   5385: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5386: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5387:         unless ($status eq 'ok ok') {
                   5388:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5389:                     $uname.' at '.$udom.' for '.
1.109     www      5390: 		    $symb.': '.$status);
1.133     albertel 5391:         }
1.553     albertel 5392: 	&delenv('user.state.'.$cid);
1.109     www      5393:     }
                   5394: }
                   5395: 
1.265     albertel 5396: sub get_scalar {
                   5397:     my ($string,$end) = @_;
                   5398:     my $value;
                   5399:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5400: 	$value = $1;
                   5401:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5402: 	$value = $1;
                   5403:     }
                   5404:     return &unescape($value);
                   5405: }
                   5406: 
                   5407: sub array2str {
                   5408:   my (@array) = @_;
                   5409:   my $result=&arrayref2str(\@array);
                   5410:   $result=~s/^__ARRAY_REF__//;
                   5411:   $result=~s/__END_ARRAY_REF__$//;
                   5412:   return $result;
                   5413: }
                   5414: 
1.204     albertel 5415: sub arrayref2str {
                   5416:   my ($arrayref) = @_;
1.265     albertel 5417:   my $result='__ARRAY_REF__';
1.204     albertel 5418:   foreach my $elem (@$arrayref) {
1.265     albertel 5419:     if(ref($elem) eq 'ARRAY') {
                   5420:       $result.=&arrayref2str($elem).'&';
                   5421:     } elsif(ref($elem) eq 'HASH') {
                   5422:       $result.=&hashref2str($elem).'&';
                   5423:     } elsif(ref($elem)) {
                   5424:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5425:     } else {
                   5426:       $result.=&escape($elem).'&';
                   5427:     }
                   5428:   }
                   5429:   $result=~s/\&$//;
1.265     albertel 5430:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5431:   return $result;
                   5432: }
                   5433: 
1.168     albertel 5434: sub hash2str {
1.204     albertel 5435:   my (%hash) = @_;
                   5436:   my $result=&hashref2str(\%hash);
1.265     albertel 5437:   $result=~s/^__HASH_REF__//;
                   5438:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5439:   return $result;
                   5440: }
                   5441: 
                   5442: sub hashref2str {
                   5443:   my ($hashref)=@_;
1.265     albertel 5444:   my $result='__HASH_REF__';
1.800     albertel 5445:   foreach my $key (sort(keys(%$hashref))) {
                   5446:     if (ref($key) eq 'ARRAY') {
                   5447:       $result.=&arrayref2str($key).'=';
                   5448:     } elsif (ref($key) eq 'HASH') {
                   5449:       $result.=&hashref2str($key).'=';
                   5450:     } elsif (ref($key)) {
1.265     albertel 5451:       $result.='=';
1.800     albertel 5452:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5453:     } else {
1.1132    raeburn  5454: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5455:     }
                   5456: 
1.800     albertel 5457:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5458:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5459:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5460:       $result.=&hashref2str($hashref->{$key}).'&';
                   5461:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5462:        $result.='&';
1.800     albertel 5463:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5464:     } else {
1.800     albertel 5465:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5466:     }
                   5467:   }
1.168     albertel 5468:   $result=~s/\&$//;
1.265     albertel 5469:   $result .= '__END_HASH_REF__';
1.168     albertel 5470:   return $result;
                   5471: }
                   5472: 
                   5473: sub str2hash {
1.265     albertel 5474:     my ($string)=@_;
                   5475:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5476:     return %$hash;
                   5477: }
                   5478: 
                   5479: sub str2hashref {
1.168     albertel 5480:   my ($string) = @_;
1.265     albertel 5481: 
                   5482:   my %hash;
                   5483: 
                   5484:   if($string !~ /^__HASH_REF__/) {
                   5485:       if (! ($string eq '' || !defined($string))) {
                   5486: 	  $hash{'error'}='Not hash reference';
                   5487:       }
                   5488:       return (\%hash, $string);
                   5489:   }
                   5490: 
                   5491:   $string =~ s/^__HASH_REF__//;
                   5492: 
                   5493:   while($string !~ /^__END_HASH_REF__/) {
                   5494:       #key
                   5495:       my $key='';
                   5496:       if($string =~ /^__HASH_REF__/) {
                   5497:           ($key, $string)=&str2hashref($string);
                   5498:           if(defined($key->{'error'})) {
                   5499:               $hash{'error'}='Bad data';
                   5500:               return (\%hash, $string);
                   5501:           }
                   5502:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5503:           ($key, $string)=&str2arrayref($string);
                   5504:           if($key->[0] eq 'Array reference error') {
                   5505:               $hash{'error'}='Bad data';
                   5506:               return (\%hash, $string);
                   5507:           }
                   5508:       } else {
                   5509:           $string =~ s/^(.*?)=//;
1.267     albertel 5510: 	  $key=&unescape($1);
1.265     albertel 5511:       }
                   5512:       $string =~ s/^=//;
                   5513: 
                   5514:       #value
                   5515:       my $value='';
                   5516:       if($string =~ /^__HASH_REF__/) {
                   5517:           ($value, $string)=&str2hashref($string);
                   5518:           if(defined($value->{'error'})) {
                   5519:               $hash{'error'}='Bad data';
                   5520:               return (\%hash, $string);
                   5521:           }
                   5522:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5523:           ($value, $string)=&str2arrayref($string);
                   5524:           if($value->[0] eq 'Array reference error') {
                   5525:               $hash{'error'}='Bad data';
                   5526:               return (\%hash, $string);
                   5527:           }
                   5528:       } else {
                   5529: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5530:       }
                   5531:       $string =~ s/^&//;
                   5532: 
                   5533:       $hash{$key}=$value;
1.204     albertel 5534:   }
1.265     albertel 5535: 
                   5536:   $string =~ s/^__END_HASH_REF__//;
                   5537: 
                   5538:   return (\%hash, $string);
1.204     albertel 5539: }
                   5540: 
                   5541: sub str2array {
1.265     albertel 5542:     my ($string)=@_;
                   5543:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5544:     return @$array;
                   5545: }
                   5546: 
                   5547: sub str2arrayref {
1.204     albertel 5548:   my ($string) = @_;
1.265     albertel 5549:   my @array;
                   5550: 
                   5551:   if($string !~ /^__ARRAY_REF__/) {
                   5552:       if (! ($string eq '' || !defined($string))) {
                   5553: 	  $array[0]='Array reference error';
                   5554:       }
                   5555:       return (\@array, $string);
                   5556:   }
                   5557: 
                   5558:   $string =~ s/^__ARRAY_REF__//;
                   5559: 
                   5560:   while($string !~ /^__END_ARRAY_REF__/) {
                   5561:       my $value='';
                   5562:       if($string =~ /^__HASH_REF__/) {
                   5563:           ($value, $string)=&str2hashref($string);
                   5564:           if(defined($value->{'error'})) {
                   5565:               $array[0] ='Array reference error';
                   5566:               return (\@array, $string);
                   5567:           }
                   5568:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5569:           ($value, $string)=&str2arrayref($string);
                   5570:           if($value->[0] eq 'Array reference error') {
                   5571:               $array[0] ='Array reference error';
                   5572:               return (\@array, $string);
                   5573:           }
                   5574:       } else {
                   5575: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5576:       }
                   5577:       $string =~ s/^&//;
                   5578: 
                   5579:       push(@array, $value);
1.191     harris41 5580:   }
1.265     albertel 5581: 
                   5582:   $string =~ s/^__END_ARRAY_REF__//;
                   5583: 
                   5584:   return (\@array, $string);
1.168     albertel 5585: }
                   5586: 
1.167     albertel 5587: # -------------------------------------------------------------------Temp Store
                   5588: 
1.168     albertel 5589: sub tmpreset {
                   5590:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5591:   if (!$symb) {
                   5592:     $symb=&symbread();
1.620     albertel 5593:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5594:   }
                   5595:   $symb=escape($symb);
                   5596: 
1.620     albertel 5597:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5598:   $namespace=~s/\//\_/g;
                   5599:   $namespace=~s/\W//g;
                   5600: 
1.620     albertel 5601:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5602:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5603:   if ($domain eq 'public' && $stuname eq 'public') {
                   5604:       $stuname=$ENV{'REMOTE_ADDR'};
                   5605:   }
1.1117    foxr     5606:   my $path=LONCAPA::tempdir();
1.168     albertel 5607:   my %hash;
                   5608:   if (tie(%hash,'GDBM_File',
                   5609: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5610: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5611:     foreach my $key (keys(%hash)) {
1.180     albertel 5612:       if ($key=~ /:$symb/) {
1.168     albertel 5613: 	delete($hash{$key});
                   5614:       }
                   5615:     }
                   5616:   }
                   5617: }
                   5618: 
1.167     albertel 5619: sub tmpstore {
1.168     albertel 5620:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5621: 
                   5622:   if (!$symb) {
                   5623:     $symb=&symbread();
1.620     albertel 5624:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5625:   }
                   5626:   $symb=escape($symb);
                   5627: 
                   5628:   if (!$namespace) {
                   5629:     # I don't think we would ever want to store this for a course.
                   5630:     # it seems this will only be used if we don't have a course.
1.620     albertel 5631:     #$namespace=$env{'request.course.id'};
1.168     albertel 5632:     #if (!$namespace) {
1.620     albertel 5633:       $namespace=$env{'request.state'};
1.168     albertel 5634:     #}
                   5635:   }
                   5636:   $namespace=~s/\//\_/g;
                   5637:   $namespace=~s/\W//g;
1.620     albertel 5638:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5639:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5640:   if ($domain eq 'public' && $stuname eq 'public') {
                   5641:       $stuname=$ENV{'REMOTE_ADDR'};
                   5642:   }
1.168     albertel 5643:   my $now=time;
                   5644:   my %hash;
1.1117    foxr     5645:   my $path=LONCAPA::tempdir();
1.168     albertel 5646:   if (tie(%hash,'GDBM_File',
                   5647: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5648: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5649:     $hash{"version:$symb"}++;
                   5650:     my $version=$hash{"version:$symb"};
                   5651:     my $allkeys=''; 
                   5652:     foreach my $key (keys(%$storehash)) {
                   5653:       $allkeys.=$key.':';
1.591     albertel 5654:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5655:     }
                   5656:     $hash{"$version:$symb:timestamp"}=$now;
                   5657:     $allkeys.='timestamp';
                   5658:     $hash{"$version:keys:$symb"}=$allkeys;
                   5659:     if (untie(%hash)) {
                   5660:       return 'ok';
                   5661:     } else {
                   5662:       return "error:$!";
                   5663:     }
                   5664:   } else {
                   5665:     return "error:$!";
                   5666:   }
                   5667: }
1.167     albertel 5668: 
1.168     albertel 5669: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5670: 
1.168     albertel 5671: sub tmprestore {
                   5672:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5673: 
1.168     albertel 5674:   if (!$symb) {
                   5675:     $symb=&symbread();
1.620     albertel 5676:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5677:   }
                   5678:   $symb=escape($symb);
                   5679: 
1.620     albertel 5680:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5681: 
1.620     albertel 5682:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5683:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5684:   if ($domain eq 'public' && $stuname eq 'public') {
                   5685:       $stuname=$ENV{'REMOTE_ADDR'};
                   5686:   }
1.168     albertel 5687:   my %returnhash;
                   5688:   $namespace=~s/\//\_/g;
                   5689:   $namespace=~s/\W//g;
                   5690:   my %hash;
1.1117    foxr     5691:   my $path=LONCAPA::tempdir();
1.168     albertel 5692:   if (tie(%hash,'GDBM_File',
                   5693: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5694: 	  &GDBM_READER(),0640)) {
1.168     albertel 5695:     my $version=$hash{"version:$symb"};
                   5696:     $returnhash{'version'}=$version;
                   5697:     my $scope;
                   5698:     for ($scope=1;$scope<=$version;$scope++) {
                   5699:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5700:       my @keys=split(/:/,$vkeys);
                   5701:       my $key;
                   5702:       $returnhash{"$scope:keys"}=$vkeys;
                   5703:       foreach $key (@keys) {
1.591     albertel 5704: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5705: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5706:       }
                   5707:     }
1.168     albertel 5708:     if (!(untie(%hash))) {
                   5709:       return "error:$!";
                   5710:     }
                   5711:   } else {
                   5712:     return "error:$!";
                   5713:   }
                   5714:   return %returnhash;
1.167     albertel 5715: }
                   5716: 
1.9       www      5717: # ----------------------------------------------------------------------- Store
                   5718: 
                   5719: sub store {
1.1269    raeburn  5720:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5721:     my $home='';
                   5722: 
1.168     albertel 5723:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5724: 
1.213     www      5725:     $symb=&symbclean($symb);
1.122     albertel 5726:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5727: 
1.620     albertel 5728:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5729:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5730: 
                   5731:     &devalidate($symb,$stuname,$domain);
1.109     www      5732: 
                   5733:     $symb=escape($symb);
1.187     www      5734:     if (!$namespace) { 
1.620     albertel 5735:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5736:           return ''; 
                   5737:        } 
                   5738:     }
1.620     albertel 5739:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5740: 
                   5741:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5742:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5743: 
1.12      www      5744:     my $namevalue='';
1.800     albertel 5745:     foreach my $key (keys(%$storehash)) {
                   5746:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5747:     }
1.12      www      5748:     $namevalue=~s/\&$//;
1.187     www      5749:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5750:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5751: }
                   5752: 
1.47      www      5753: # -------------------------------------------------------------- Critical Store
                   5754: 
                   5755: sub cstore {
1.1269    raeburn  5756:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5757:     my $home='';
                   5758: 
1.168     albertel 5759:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5760: 
1.213     www      5761:     $symb=&symbclean($symb);
1.122     albertel 5762:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5763: 
1.620     albertel 5764:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5765:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5766: 
                   5767:     &devalidate($symb,$stuname,$domain);
1.109     www      5768: 
                   5769:     $symb=escape($symb);
1.187     www      5770:     if (!$namespace) { 
1.620     albertel 5771:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5772:           return ''; 
                   5773:        } 
                   5774:     }
1.620     albertel 5775:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5776: 
                   5777:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5778:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5779: 
1.47      www      5780:     my $namevalue='';
1.800     albertel 5781:     foreach my $key (keys(%$storehash)) {
                   5782:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5783:     }
1.47      www      5784:     $namevalue=~s/\&$//;
1.187     www      5785:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5786:     return critical
1.1269    raeburn  5787:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5788: }
                   5789: 
1.9       www      5790: # --------------------------------------------------------------------- Restore
                   5791: 
                   5792: sub restore {
1.124     www      5793:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5794:     my $home='';
                   5795: 
1.168     albertel 5796:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5797: 
1.122     albertel 5798:     if (!$symb) {
1.1224    raeburn  5799:         return if ($namespace eq 'courserequests');
                   5800:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5801:     } else {
1.1224    raeburn  5802:         unless ($namespace eq 'courserequests') {
                   5803:             $symb=&escape(&symbclean($symb));
                   5804:         }
1.122     albertel 5805:     }
1.188     www      5806:     if (!$namespace) { 
1.620     albertel 5807:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5808:           return ''; 
                   5809:        } 
                   5810:     }
1.620     albertel 5811:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5812:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5813:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5814:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5815: 
1.12      www      5816:     my %returnhash=();
1.800     albertel 5817:     foreach my $line (split(/\&/,$answer)) {
                   5818: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5819:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5820:     }
1.75      www      5821:     my $version;
                   5822:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5823:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5824:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5825:        }
1.75      www      5826:     }
1.13      www      5827:     return %returnhash;
1.34      www      5828: }
                   5829: 
                   5830: # ---------------------------------------------------------- Course Description
1.1118    foxr     5831: #
                   5832: #  
1.34      www      5833: 
                   5834: sub coursedescription {
1.731     albertel 5835:     my ($courseid,$args)=@_;
1.34      www      5836:     $courseid=~s/^\///;
1.49      www      5837:     $courseid=~s/\_/\//g;
1.34      www      5838:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5839:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5840:     my $normalid=$cdomain.'_'.$cnum;
                   5841:     # need to always cache even if we get errors otherwise we keep 
                   5842:     # trying and trying and trying to get the course description.
                   5843:     my %envhash=();
                   5844:     my %returnhash=();
1.731     albertel 5845:     
                   5846:     my $expiretime=600;
                   5847:     if ($env{'request.course.id'} eq $normalid) {
                   5848: 	$expiretime=120;
                   5849:     }
                   5850: 
                   5851:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5852:     if (!$args->{'freshen_cache'}
                   5853: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5854: 	foreach my $key (keys(%env)) {
                   5855: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5856: 	    my ($setting) = $1;
                   5857: 	    $returnhash{$setting} = $env{$key};
                   5858: 	}
                   5859: 	return %returnhash;
                   5860:     }
                   5861: 
1.1118    foxr     5862:     # get the data again
                   5863: 
1.731     albertel 5864:     if (!$args->{'one_time'}) {
                   5865: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5866:     }
1.811     albertel 5867: 
1.34      www      5868:     if ($chome ne 'no_host') {
1.302     albertel 5869:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5870:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5871: 	   my $username = $env{'user.name'}; # Defult username
                   5872: 	   if(defined $args->{'user'}) {
                   5873: 	       $username = $args->{'user'};
                   5874: 	   }
1.129     albertel 5875:            $returnhash{'home'}= $chome;
                   5876: 	   $returnhash{'domain'} = $cdomain;
                   5877: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5878:            if (!defined($returnhash{'type'})) {
                   5879:                $returnhash{'type'} = 'Course';
                   5880:            }
1.130     albertel 5881:            while (my ($name,$value) = each %returnhash) {
1.53      www      5882:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5883:            }
1.270     www      5884:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5885:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5886: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5887:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5888:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5889:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5890:        }
                   5891:     }
1.731     albertel 5892:     if (!$args->{'one_time'}) {
1.949     raeburn  5893: 	&appenv(\%envhash);
1.731     albertel 5894:     }
1.302     albertel 5895:     return %returnhash;
1.461     www      5896: }
                   5897: 
1.1080    raeburn  5898: sub update_released_required {
                   5899:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5900:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5901:         $cid = $env{'request.course.id'};
                   5902:         $cdom = $env{'course.'.$cid.'.domain'};
                   5903:         $cnum = $env{'course.'.$cid.'.num'};
                   5904:         $chome = $env{'course.'.$cid.'.home'};
                   5905:     }
                   5906:     if ($needsrelease) {
                   5907:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5908:         my $needsupdate;
                   5909:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5910:             $needsupdate = 1;
                   5911:         } else {
                   5912:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5913:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5914:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5915:                 $needsupdate = 1;
                   5916:             }
                   5917:         }
                   5918:         if ($needsupdate) {
                   5919:             my %needshash = (
                   5920:                              'internal.releaserequired' => $needsrelease,
                   5921:                             );
                   5922:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5923:             if ($putresult eq 'ok') {
                   5924:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5925:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5926:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5927:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5928:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5929:                 }
                   5930:             }
                   5931:         }
                   5932:     }
                   5933:     return;
                   5934: }
                   5935: 
1.461     www      5936: # -------------------------------------------------See if a user is privileged
                   5937: 
                   5938: sub privileged {
1.1219    raeburn  5939:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5940:     my $now = time;
1.1219    raeburn  5941:     my $roles;
                   5942:     if (ref($possroles) eq 'ARRAY') {
                   5943:         $roles = $possroles; 
                   5944:     } else {
                   5945:         $roles = ['dc','su'];
                   5946:     }
                   5947:     if (ref($possdomains) eq 'ARRAY') {
                   5948:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5949:         foreach my $dom (@{$possdomains}) {
                   5950:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5951:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5952:                 foreach my $role (@{$roles}) {
                   5953:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5954:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5955:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5956:                             return 1 unless (($end && $end < $now) ||
                   5957:                                              ($start && $start > $now));
                   5958:                         }
                   5959:                     }
                   5960:                 }
                   5961:             }
                   5962:         }
                   5963:     } else {
                   5964:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5965:         my $now = time;
1.1170    droeschl 5966: 
1.1275    musolffc 5967:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5968:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5969:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5970:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5971:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5972:             }
1.1219    raeburn  5973:         }
                   5974:     }
                   5975:     return 0;
                   5976: }
1.1170    droeschl 5977: 
1.1219    raeburn  5978: sub privileged_by_domain {
                   5979:     my ($domains,$roles) = @_;
                   5980:     my %privileged = ();
                   5981:     my $cachetime = 60*60*24;
                   5982:     my $now = time;
                   5983:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5984:         return %privileged;
                   5985:     }
                   5986:     foreach my $dom (@{$domains}) {
                   5987:         next if (ref($privileged{$dom}) eq 'HASH');
                   5988:         my $needroles;
                   5989:         foreach my $role (@{$roles}) {
                   5990:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5991:             if (defined($cached)) {
                   5992:                 if (ref($result) eq 'HASH') {
                   5993:                     $privileged{$dom}{$role} = $result;
                   5994:                 }
                   5995:             } else {
                   5996:                 $needroles = 1;
                   5997:             }
                   5998:         }
                   5999:         if ($needroles) {
                   6000:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6001:             $privileged{$dom} = {};
                   6002:             foreach my $server (keys(%dompersonnel)) {
                   6003:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6004:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6005:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6006:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6007:                         next if ($end && $end < $now);
                   6008:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6009:                             $dompersonnel{$server}{$item};
                   6010:                     }
                   6011:                 }
                   6012:             }
                   6013:             if (ref($privileged{$dom}) eq 'HASH') {
                   6014:                 foreach my $role (@{$roles}) {
                   6015:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6016:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6017:                     } else {
                   6018:                         my %hash = ();
                   6019:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6020:                     }
                   6021:                 }
                   6022:             }
                   6023:         }
                   6024:     }
                   6025:     return %privileged;
1.9       www      6026: }
1.1       albertel 6027: 
1.103     harris41 6028: # -------------------------------------------------------- Get user privileges
1.11      www      6029: 
                   6030: sub rolesinit {
1.1169    droeschl 6031:     my ($domain, $username) = @_;
                   6032:     my %userroles = ('user.login.time' => time);
                   6033:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6034: 
                   6035:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6036:     # also, blocking can be triggered by an activating timer
                   6037:     # it's saved in the user's %env.
                   6038:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6039:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6040:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6041:         %timerintchk, %timerintenv);
                   6042: 
1.1162    raeburn  6043:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6044:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6045:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6046:     }
1.1169    droeschl 6047: 
1.1162    raeburn  6048:     foreach my $key (keys(%timerinterval)) {
                   6049:         my ($cid,$rest) = split(/\0/,$key);
                   6050:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6051:     }
1.1169    droeschl 6052: 
1.11      www      6053:     my %allroles=();
1.1162    raeburn  6054:     my %allgroups=();
1.11      www      6055: 
1.1274    raeburn  6056:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6057:         my $role = $rolesdump{$area};
                   6058:         $area =~ s/\_\w\w$//;
                   6059: 
                   6060:         my ($trole, $tend, $tstart, $group_privs);
                   6061: 
                   6062:         if ($role =~ /^cr/) {
                   6063:         # Custom role, defined by a user 
                   6064:         # e.g., user.role.cr/msu/smith/mynewrole
                   6065:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6066:                 $trole = $1;
                   6067:                 ($tend, $tstart) = split('_', $2);
                   6068:             } else {
                   6069:                 $trole = $role;
                   6070:             }
                   6071:         } elsif ($role =~ m|^gr/|) {
                   6072:         # Role of member in a group, defined within a course/community
                   6073:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6074:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6075:             next if $tstart eq '-1';
                   6076:             ($trole, $group_privs) = split(/\//, $trole);
                   6077:             $group_privs = &unescape($group_privs);
                   6078:         } else {
                   6079:         # Just a normal role, defined in roles.tab
                   6080:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6081:         }
                   6082: 
                   6083:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6084:                  $username);
                   6085:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6086: 
                   6087:         # role expired or not available yet?
                   6088:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6089:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6090: 
                   6091:         next if $area eq '' or $trole eq '';
                   6092: 
                   6093:         my $spec = "$trole.$area";
                   6094:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6095: 
                   6096:         if ($trole =~ /^cr\//) {
                   6097:         # Custom role, defined by a user
                   6098:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6099:         } elsif ($trole eq 'gr') {
                   6100:         # Role of a member in a group, defined within a course/community
                   6101:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6102:             next;
                   6103:         } else {
                   6104:         # Normal role, defined in roles.tab
                   6105:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6106:         }
                   6107: 
                   6108:         my $cid = $tdomain.'_'.$trest;
                   6109:         unless ($firstaccchk{$cid}) {
                   6110:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6111:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6112:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6113:                         $coursetimerstarts{$cid}{$item}; 
                   6114:                 }
                   6115:             }
                   6116:             $firstaccchk{$cid} = 1;
                   6117:         }
                   6118:         unless ($timerintchk{$cid}) {
                   6119:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6120:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6121:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6122:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6123:                 }
1.12      www      6124:             }
1.1169    droeschl 6125:             $timerintchk{$cid} = 1;
1.191     harris41 6126:         }
1.11      www      6127:     }
1.1169    droeschl 6128: 
1.1341    raeburn  6129:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6130:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6131:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6132:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6133: 
1.1162    raeburn  6134:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6135: }
                   6136: 
1.567     raeburn  6137: sub set_arearole {
1.1215    raeburn  6138:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6139:     unless ($nolog) {
1.567     raeburn  6140: # log the associated role with the area
1.1215    raeburn  6141:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6142:     }
1.743     albertel 6143:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6144: }
                   6145: 
                   6146: sub custom_roleprivs {
                   6147:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6148:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6149:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6150:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6151:         my ($rdummy,$roledef)=
                   6152:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6153:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6154:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6155:             if (defined($syspriv)) {
1.1043    raeburn  6156:                 if ($trest =~ /^$match_community$/) {
                   6157:                     $syspriv =~ s/bre\&S//; 
                   6158:                 }
1.567     raeburn  6159:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6160:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6161:             }
                   6162:             if ($tdomain ne '') {
                   6163:                 if (defined($dompriv)) {
                   6164:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6165:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6166:                 }
                   6167:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6168:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6169:                         my $rolename = $1;
                   6170:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6171:                     }
1.567     raeburn  6172:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6173:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6174:                 }
                   6175:             }
                   6176:         }
                   6177:     }
                   6178: }
                   6179: 
1.1332    raeburn  6180: sub course_adhocrole_privs {
                   6181:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6182:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6183:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6184:         my (%currprivs,%storeprivs);
                   6185:         foreach my $item (split(/:/,$coursepriv)) {
                   6186:             my ($priv,$restrict) = split(/\&/,$item);
                   6187:             $currprivs{$priv} = $restrict;
                   6188:         }
                   6189:         my (%possadd,%possremove,%full);
                   6190:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6191:             my ($priv,$restrict)=split(/\&/,$item);
                   6192:             $full{$priv} = $restrict;
                   6193:         }
                   6194:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6195:              next if ($item eq '');
                   6196:              my ($rule,$rest) = split(/=/,$item);
                   6197:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6198:              foreach my $priv (split(/:/,$rest)) {
                   6199:                  if ($priv ne '') {
                   6200:                      if ($rule eq 'off') {
                   6201:                          $possremove{$priv} = 1;
                   6202:                      } else {
                   6203:                          $possadd{$priv} = 1;
                   6204:                      }
                   6205:                  }
                   6206:              }
                   6207:          }
                   6208:          foreach my $priv (sort(keys(%full))) {
                   6209:              if (exists($currprivs{$priv})) {
                   6210:                  unless (exists($possremove{$priv})) {
                   6211:                      $storeprivs{$priv} = $currprivs{$priv};
                   6212:                  }
                   6213:              } elsif (exists($possadd{$priv})) {
                   6214:                  $storeprivs{$priv} = $full{$priv};
                   6215:              }
                   6216:          }
                   6217:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6218:      }
                   6219:      return $coursepriv;
                   6220: }
                   6221: 
1.678     raeburn  6222: sub group_roleprivs {
                   6223:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6224:     my $access = 1;
                   6225:     my $now = time;
                   6226:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6227:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6228:     if ($access) {
1.811     albertel 6229:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6230:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6231:     }
                   6232: }
1.567     raeburn  6233: 
                   6234: sub standard_roleprivs {
                   6235:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6236:     if (defined($pr{$trole.':s'})) {
                   6237:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6238:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6239:     }
                   6240:     if ($tdomain ne '') {
                   6241:         if (defined($pr{$trole.':d'})) {
                   6242:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6243:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6244:         }
                   6245:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6246:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6247:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6248:         }
                   6249:     }
                   6250: }
                   6251: 
                   6252: sub set_userprivs {
1.1064    raeburn  6253:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6254:     my $author=0;
                   6255:     my $adv=0;
1.1341    raeburn  6256:     my $rar=0;
1.678     raeburn  6257:     my %grouproles = ();
                   6258:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6259:         my @groupkeys; 
1.1000    raeburn  6260:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6261:             push(@groupkeys,$role);
                   6262:         }
                   6263:         if (ref($groups_roles) eq 'HASH') {
                   6264:             foreach my $key (keys(%{$groups_roles})) {
                   6265:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6266:                     push(@groupkeys,$key);
                   6267:                 }
                   6268:             }
                   6269:         }
                   6270:         if (@groupkeys > 0) {
                   6271:             foreach my $role (@groupkeys) {
                   6272:                 my ($trole,$area,$sec,$extendedarea);
                   6273:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6274:                     $trole = $1;
                   6275:                     $area = $2;
                   6276:                     $sec = $3;
                   6277:                     $extendedarea = $area.$sec;
                   6278:                     if (exists($$allgroups{$area})) {
                   6279:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6280:                             my $spec = $trole.'.'.$extendedarea;
                   6281:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6282:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6283:                         }
1.678     raeburn  6284:                     }
                   6285:                 }
                   6286:             }
                   6287:         }
                   6288:     }
1.800     albertel 6289:     foreach my $group (keys(%grouproles)) {
                   6290:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6291:     }
1.800     albertel 6292:     foreach my $role (keys(%{$allroles})) {
                   6293:         my %thesepriv;
1.941     raeburn  6294:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6295:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6296:             if ($item ne '') {
                   6297:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6298:                 if ($restrictions eq '') {
                   6299:                     $thesepriv{$privilege}='F';
                   6300:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6301:                     $thesepriv{$privilege}.=$restrictions;
                   6302:                 }
                   6303:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6304:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6305:             }
                   6306:         }
                   6307:         my $thesestr='';
1.1104    raeburn  6308:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6309: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6310: 	}
                   6311:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6312:     }
1.1341    raeburn  6313:     return ($author,$adv,$rar);
1.567     raeburn  6314: }
                   6315: 
1.994     raeburn  6316: sub role_status {
1.1104    raeburn  6317:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6318:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6319:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6320:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6321:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6322:             $$where = '/'.$two;
1.994     raeburn  6323:             $$trolecode=$$role.'.'.$$where;
                   6324:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6325:             $$tstatus='is';
1.1104    raeburn  6326:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6327:                 $$tstatus='future';
1.1034    raeburn  6328:                 if ($$tstart<$now) {
                   6329:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6330:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6331:                             my (%allroles,%allgroups,$group_privs,
                   6332:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6333:                             my %userroles = (
                   6334:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6335:                             );
1.1064    raeburn  6336:                             @rolecodes = ('cm'); 
1.1002    raeburn  6337:                             my $spec=$$role.'.'.$$where;
                   6338:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6339:                             if ($$role =~ /^cr\//) {
                   6340:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6341:                                 push(@rolecodes,'cr');
1.1002    raeburn  6342:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6343:                                 push(@rolecodes,$$role);
1.1002    raeburn  6344:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6345:                                                     $env{'user.name'});
1.1064    raeburn  6346:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6347:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6348:                                 $group_privs = &unescape($group_privs);
                   6349:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6350:                                 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  6351:                                 &get_groups_roles($tdomain,$trest,
                   6352:                                                   \%course_roles,\@rolecodes,
                   6353:                                                   \%groups_roles);
1.1002    raeburn  6354:                             } else {
1.1064    raeburn  6355:                                 push(@rolecodes,$$role);
1.1002    raeburn  6356:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6357:                             }
1.1341    raeburn  6358:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6359:                                                                    \%groups_roles);
1.1064    raeburn  6360:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6361:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6362:                         }
                   6363:                     }
1.1034    raeburn  6364:                     $$tstatus = 'is';
1.1002    raeburn  6365:                 }
1.994     raeburn  6366:             }
                   6367:             if ($$tend) {
1.1104    raeburn  6368:                 if ($$tend<$update) {
1.994     raeburn  6369:                     $$tstatus='expired';
                   6370:                 } elsif ($$tend<$now) {
                   6371:                     $$tstatus='will_not';
                   6372:                 }
                   6373:             }
                   6374:         }
                   6375:     }
                   6376: }
                   6377: 
1.1104    raeburn  6378: sub get_groups_roles {
                   6379:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6380:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6381:                   (ref($rolecodes) eq 'ARRAY') && 
                   6382:                   (ref($groups_roles) eq 'HASH')); 
                   6383:     if (keys(%{$cdom_courseroles}) > 0) {
                   6384:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6385:         if ($cdom ne '' && $cnum ne '') {
                   6386:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6387:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6388:                     my $crsrole = $1;
                   6389:                     my $crssec = $2;
                   6390:                     if ($crsrole =~ /^cr/) {
                   6391:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6392:                             push(@{$rolecodes},'cr');
                   6393:                         }
                   6394:                     } else {
                   6395:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6396:                             push(@{$rolecodes},$crsrole);
                   6397:                         }
                   6398:                     }
                   6399:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6400:                     if ($crssec ne '') {
                   6401:                         $rolekey .= "/$crssec";
                   6402:                     }
                   6403:                     $rolekey .= './';
                   6404:                     $groups_roles->{$rolekey} = $rolecodes;
                   6405:                 }
                   6406:             }
                   6407:         }
                   6408:     }
                   6409:     return;
                   6410: }
                   6411: 
                   6412: sub delete_env_groupprivs {
                   6413:     my ($where,$courseroles,$possroles) = @_;
                   6414:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6415:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6416:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6417:         %{$courseroles->{$udom}} =
                   6418:             &get_my_roles('','','userroles',['active'],
                   6419:                           $possroles,[$udom],1);
                   6420:     }
                   6421:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6422:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6423:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6424:             my $area = '/'.$cdom.'/'.$cnum;
                   6425:             my $privkey = "user.priv.$crsrole.$area";
                   6426:             if ($crssec ne '') {
                   6427:                 $privkey .= '/'.$crssec;
                   6428:             }
                   6429:             $privkey .= ".$area/$group";
                   6430:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6431:         }
                   6432:     }
                   6433:     return;
                   6434: }
                   6435: 
1.994     raeburn  6436: sub check_adhoc_privs {
1.1329    raeburn  6437:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6438:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6439:     if ($sec) {
                   6440:         $cckey .= '/'.$sec;
                   6441:     } 
1.1185    raeburn  6442:     my $setprivs;
1.994     raeburn  6443:     if ($env{$cckey}) {
                   6444:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6445:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6446:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6447:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6448:             $setprivs = 1;
1.994     raeburn  6449:         }
                   6450:     } else {
1.1330    raeburn  6451:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6452:         $setprivs = 1;
1.994     raeburn  6453:     }
1.1185    raeburn  6454:     return $setprivs;
1.994     raeburn  6455: }
                   6456: 
                   6457: sub set_adhoc_privileges {
1.1326    raeburn  6458: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6459:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6460:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6461:     if ($sec ne '') {
                   6462:         $area .= '/'.$sec;
                   6463:     }
1.994     raeburn  6464:     my $spec = $role.'.'.$area;
                   6465:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6466:                                   $env{'user.name'},1);
1.1326    raeburn  6467:     my %rolehash = ();
1.1332    raeburn  6468:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6469:         my $rolename = $1;
1.1326    raeburn  6470:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6471:         my %domdef = &get_domain_defaults($dcdom);
                   6472:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6473:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6474:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6475:             }
                   6476:         }
1.1326    raeburn  6477:     } else {
                   6478:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6479:     }
1.1341    raeburn  6480:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6481:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6482:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6483:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6484:         &appenv( {'request.role'        => $spec,
                   6485:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6486:                   'request.course.sec'  => $sec,
1.1088    raeburn  6487:                  }
                   6488:                );
                   6489:         my $tadv=0;
                   6490:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6491:         &appenv({'request.role.adv'    => $tadv});
                   6492:     }
1.994     raeburn  6493: }
                   6494: 
1.12      www      6495: # --------------------------------------------------------------- get interface
                   6496: 
                   6497: sub get {
1.131     albertel 6498:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6499:    my $items='';
1.800     albertel 6500:    foreach my $item (@$storearr) {
                   6501:        $items.=&escape($item).'&';
1.191     harris41 6502:    }
1.12      www      6503:    $items=~s/\&$//;
1.620     albertel 6504:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6505:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6506:    my $uhome=&homeserver($uname,$udomain);
                   6507: 
1.133     albertel 6508:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6509:    my @pairs=split(/\&/,$rep);
1.273     albertel 6510:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6511:      return @pairs;
                   6512:    }
1.15      www      6513:    my %returnhash=();
1.42      www      6514:    my $i=0;
1.800     albertel 6515:    foreach my $item (@$storearr) {
                   6516:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6517:       $i++;
1.191     harris41 6518:    }
1.15      www      6519:    return %returnhash;
1.27      www      6520: }
                   6521: 
                   6522: # --------------------------------------------------------------- del interface
                   6523: 
                   6524: sub del {
1.133     albertel 6525:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6526:    my $items='';
1.800     albertel 6527:    foreach my $item (@$storearr) {
                   6528:        $items.=&escape($item).'&';
1.191     harris41 6529:    }
1.984     neumanie 6530: 
1.27      www      6531:    $items=~s/\&$//;
1.620     albertel 6532:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6533:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6534:    my $uhome=&homeserver($uname,$udomain);
                   6535:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6536: }
                   6537: 
                   6538: # -------------------------------------------------------------- dump interface
                   6539: 
1.1180    droeschl 6540: sub unserialize {
                   6541:     my ($rep, $escapedkeys) = @_;
                   6542: 
                   6543:     return {} if $rep =~ /^error/;
                   6544: 
                   6545:     my %returnhash=();
1.1252    raeburn  6546: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6547: 	    my ($key, $value) = split(/=/, $item, 2);
                   6548: 	    $key = unescape($key) unless $escapedkeys;
                   6549: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6550: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6551: 	}
                   6552:     #return %returnhash;
                   6553:     return \%returnhash;
                   6554: }        
                   6555: 
                   6556: # see Lond::dump_with_regexp
                   6557: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6558: sub dump {
1.1180    droeschl 6559:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6560:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6561:     if (!$uname) { $uname=$env{'user.name'}; }
                   6562:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6563: 
1.1266    raeburn  6564:     if ($regexp) {
                   6565:         $regexp=&escape($regexp);
                   6566:     } else {
                   6567:         $regexp='.';
                   6568:     }
1.1180    droeschl 6569:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6570:         # user is hosted on this machine
1.1266    raeburn  6571:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6572:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6573:         return %{unserialize($reply, $escapedkeys)};
                   6574:     }
1.1166    raeburn  6575:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6576:     my @pairs=split(/\&/,$rep);
                   6577:     my %returnhash=();
1.1098    foxr     6578:     if (!($rep =~ /^error/ )) {
                   6579: 	foreach my $item (@pairs) {
                   6580: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6581:         $key = unescape($key) unless $escapedkeys;
                   6582:         #$key = &unescape($key);
1.1098    foxr     6583: 	    next if ($key =~ /^error: 2 /);
                   6584: 	    $returnhash{$key}=&thaw_unescape($value);
                   6585: 	}
1.755     albertel 6586:     }
                   6587:     return %returnhash;
1.407     www      6588: }
                   6589: 
1.1098    foxr     6590: 
1.717     albertel 6591: # --------------------------------------------------------- dumpstore interface
                   6592: 
                   6593: sub dumpstore {
                   6594:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6595:    # same as dump but keys must be escaped. They may contain colon separated
                   6596:    # lists of values that may themself contain colons (e.g. symbs).
                   6597:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6598: }
                   6599: 
1.407     www      6600: # -------------------------------------------------------------- keys interface
                   6601: 
                   6602: sub getkeys {
                   6603:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6604:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6605:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6606:    my $uhome=&homeserver($uname,$udomain);
                   6607:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6608:    my @keyarray=();
1.800     albertel 6609:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6610:       next if ($key =~ /^error: 2 /);
1.800     albertel 6611:       push(@keyarray,&unescape($key));
1.407     www      6612:    }
                   6613:    return @keyarray;
1.318     matthew  6614: }
                   6615: 
1.319     matthew  6616: # --------------------------------------------------------------- currentdump
                   6617: sub currentdump {
1.328     matthew  6618:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6619:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6620:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6621:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6622:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6623:    my $rep;
                   6624: 
                   6625:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6626:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6627:                    $courseid)));
                   6628:    } else {
                   6629:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6630:    }
                   6631: 
1.318     matthew  6632:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6633:    #
1.318     matthew  6634:    my %returnhash=();
1.319     matthew  6635:    #
1.1343    raeburn  6636:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6637:        # an old lond will not know currentdump
                   6638:        # Do a dump and make it look like a currentdump
1.822     albertel 6639:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6640:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6641:        my %hash = @tmp;
                   6642:        @tmp=();
1.424     matthew  6643:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6644:    } else {
                   6645:        my @pairs=split(/\&/,$rep);
1.800     albertel 6646:        foreach my $pair (@pairs) {
                   6647:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6648:            my ($symb,$param) = split(/:/,$key);
                   6649:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6650:                                                         &thaw_unescape($value);
1.319     matthew  6651:        }
1.191     harris41 6652:    }
1.12      www      6653:    return %returnhash;
1.424     matthew  6654: }
                   6655: 
                   6656: sub convert_dump_to_currentdump{
                   6657:     my %hash = %{shift()};
                   6658:     my %returnhash;
                   6659:     # Code ripped from lond, essentially.  The only difference
                   6660:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6661:     # we might run in to problems with parameter names =~ /^v\./
                   6662:     while (my ($key,$value) = each(%hash)) {
                   6663:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6664: 	$symb  = &unescape($symb);
                   6665: 	$param = &unescape($param);
1.424     matthew  6666:         next if ($v eq 'version' || $symb eq 'keys');
                   6667:         next if (exists($returnhash{$symb}) &&
                   6668:                  exists($returnhash{$symb}->{$param}) &&
                   6669:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6670:         $returnhash{$symb}->{$param}=$value;
                   6671:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6672:     }
                   6673:     #
                   6674:     # Remove all of the keys in the hashes which keep track of
                   6675:     # the version of the parameter.
                   6676:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6677:         # use a foreach because we are going to delete from the hash.
                   6678:         foreach my $key (keys(%$param_hash)) {
                   6679:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6680:         }
                   6681:     }
                   6682:     return \%returnhash;
1.12      www      6683: }
                   6684: 
1.627     albertel 6685: # ------------------------------------------------------ critical inc interface
                   6686: 
                   6687: sub cinc {
                   6688:     return &inc(@_,'critical');
                   6689: }
                   6690: 
1.449     matthew  6691: # --------------------------------------------------------------- inc interface
                   6692: 
                   6693: sub inc {
1.627     albertel 6694:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6695:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6696:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6697:     my $uhome=&homeserver($uname,$udomain);
                   6698:     my $items='';
                   6699:     if (! ref($store)) {
                   6700:         # got a single value, so use that instead
                   6701:         $items = &escape($store).'=&';
                   6702:     } elsif (ref($store) eq 'SCALAR') {
                   6703:         $items = &escape($$store).'=&';        
                   6704:     } elsif (ref($store) eq 'ARRAY') {
                   6705:         $items = join('=&',map {&escape($_);} @{$store});
                   6706:     } elsif (ref($store) eq 'HASH') {
                   6707:         while (my($key,$value) = each(%{$store})) {
                   6708:             $items.= &escape($key).'='.&escape($value).'&';
                   6709:         }
                   6710:     }
                   6711:     $items=~s/\&$//;
1.627     albertel 6712:     if ($critical) {
                   6713: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6714:     } else {
                   6715: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6716:     }
1.449     matthew  6717: }
                   6718: 
1.12      www      6719: # --------------------------------------------------------------- put interface
                   6720: 
                   6721: sub put {
1.134     albertel 6722:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6723:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6724:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6725:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6726:    my $items='';
1.800     albertel 6727:    foreach my $item (keys(%$storehash)) {
                   6728:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6729:    }
1.12      www      6730:    $items=~s/\&$//;
1.134     albertel 6731:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6732: }
                   6733: 
1.631     albertel 6734: # ------------------------------------------------------------ newput interface
                   6735: 
                   6736: sub newput {
                   6737:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6738:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6739:    if (!$uname) { $uname=$env{'user.name'}; }
                   6740:    my $uhome=&homeserver($uname,$udomain);
                   6741:    my $items='';
                   6742:    foreach my $key (keys(%$storehash)) {
                   6743:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6744:    }
                   6745:    $items=~s/\&$//;
                   6746:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6747: }
                   6748: 
                   6749: # ---------------------------------------------------------  putstore interface
                   6750: 
1.524     raeburn  6751: sub putstore {
1.1269    raeburn  6752:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6753:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6754:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6755:    my $uhome=&homeserver($uname,$udomain);
                   6756:    my $items='';
1.715     albertel 6757:    foreach my $key (keys(%$storehash)) {
                   6758:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6759:    }
1.715     albertel 6760:    $items=~s/\&$//;
1.716     albertel 6761:    my $esc_symb=&escape($symb);
                   6762:    my $esc_v=&escape($version);
1.715     albertel 6763:    my $reply =
1.716     albertel 6764:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6765: 	      $uhome);
1.1269    raeburn  6766:    if (($tolog) && ($reply eq 'ok')) {
                   6767:        my $namevalue='';
                   6768:        foreach my $key (keys(%{$storehash})) {
                   6769:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6770:        }
                   6771:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6772:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6773:                      '&version='.$esc_v.
                   6774:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6775:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6776:    }
1.715     albertel 6777:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6778:        # gfall back to way things use to be done
1.715     albertel 6779:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6780: 			    $uname);
1.524     raeburn  6781:    }
1.715     albertel 6782:    return $reply;
                   6783: }
                   6784: 
                   6785: sub old_putstore {
1.716     albertel 6786:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6787:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6788:     if (!$uname) { $uname=$env{'user.name'}; }
                   6789:     my $uhome=&homeserver($uname,$udomain);
                   6790:     my %newstorehash;
1.800     albertel 6791:     foreach my $item (keys(%$storehash)) {
                   6792: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6793: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6794:     }
                   6795:     my $items='';
                   6796:     my %allitems = ();
1.800     albertel 6797:     foreach my $item (keys(%newstorehash)) {
                   6798: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6799: 	    my $key = $1.':keys:'.$2;
                   6800: 	    $allitems{$key} .= $3.':';
                   6801: 	}
1.800     albertel 6802: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6803:     }
1.800     albertel 6804:     foreach my $item (keys(%allitems)) {
                   6805: 	$allitems{$item} =~ s/\:$//;
                   6806: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6807:     }
                   6808:     $items=~s/\&$//;
                   6809:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6810: }
                   6811: 
1.47      www      6812: # ------------------------------------------------------ critical put interface
                   6813: 
                   6814: sub cput {
1.134     albertel 6815:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6816:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6817:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6818:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6819:    my $items='';
1.800     albertel 6820:    foreach my $item (keys(%$storehash)) {
                   6821:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6822:    }
1.47      www      6823:    $items=~s/\&$//;
1.134     albertel 6824:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6825: }
                   6826: 
                   6827: # -------------------------------------------------------------- eget interface
                   6828: 
                   6829: sub eget {
1.133     albertel 6830:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6831:    my $items='';
1.800     albertel 6832:    foreach my $item (@$storearr) {
                   6833:        $items.=&escape($item).'&';
1.191     harris41 6834:    }
1.12      www      6835:    $items=~s/\&$//;
1.620     albertel 6836:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6837:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6838:    my $uhome=&homeserver($uname,$udomain);
                   6839:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6840:    my @pairs=split(/\&/,$rep);
                   6841:    my %returnhash=();
1.42      www      6842:    my $i=0;
1.800     albertel 6843:    foreach my $item (@$storearr) {
                   6844:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6845:       $i++;
1.191     harris41 6846:    }
1.12      www      6847:    return %returnhash;
                   6848: }
                   6849: 
1.667     albertel 6850: # ------------------------------------------------------------ tmpput interface
                   6851: sub tmpput {
1.802     raeburn  6852:     my ($storehash,$server,$context)=@_;
1.667     albertel 6853:     my $items='';
1.800     albertel 6854:     foreach my $item (keys(%$storehash)) {
                   6855: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6856:     }
                   6857:     $items=~s/\&$//;
1.802     raeburn  6858:     if (defined($context)) {
                   6859:         $items .= ':'.&escape($context);
                   6860:     }
1.667     albertel 6861:     return &reply("tmpput:$items",$server);
                   6862: }
                   6863: 
                   6864: # ------------------------------------------------------------ tmpget interface
                   6865: sub tmpget {
1.688     albertel 6866:     my ($token,$server)=@_;
                   6867:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6868:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6869:     my %returnhash;
1.1328    raeburn  6870:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6871:         return %returnhash;
                   6872:     }
1.667     albertel 6873:     foreach my $item (split(/\&/,$rep)) {
                   6874: 	my ($key,$value)=split(/=/,$item);
                   6875: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6876:     }
                   6877:     return %returnhash;
                   6878: }
                   6879: 
1.1113    raeburn  6880: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6881: sub tmpdel {
                   6882:     my ($token,$server)=@_;
                   6883:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6884:     return &reply("tmpdel:$token",$server);
                   6885: }
                   6886: 
1.1198    raeburn  6887: # ------------------------------------------------------------ get_timebased_id 
                   6888: 
                   6889: sub get_timebased_id {
                   6890:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6891:         $maxtries) = @_;
                   6892:     my ($newid,$error,$dellock);
                   6893:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6894:         return ('','ok','invalid call to get suffix');
                   6895:     }
                   6896: 
                   6897: # set defaults for any optional args for which values were not supplied
                   6898:     if ($who eq '') {
                   6899:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6900:     }
                   6901:     if (!$locktries) {
                   6902:         $locktries = 3;
                   6903:     }
                   6904:     if (!$maxtries) {
                   6905:         $maxtries = 10;
                   6906:     }
                   6907:     
                   6908:     if (($cdom eq '') || ($cnum eq '')) {
                   6909:         if ($env{'request.course.id'}) {
                   6910:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6911:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6912:         }
                   6913:         if (($cdom eq '') || ($cnum eq '')) {
                   6914:             return ('','ok','call to get suffix not in course context');
                   6915:         }
                   6916:     }
                   6917: 
                   6918: # construct locking item
                   6919:     my $lockhash = {
                   6920:                       $prefix."\0".'locked_'.$keyid => $who,
                   6921:                    };
                   6922:     my $tries = 0;
                   6923: 
                   6924: # attempt to get lock on nohist_$namespace file
                   6925:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6926:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6927:         $tries ++;
                   6928:         sleep 1;
                   6929:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6930:     }
                   6931: 
                   6932: # attempt to get unique identifier, based on current timestamp
                   6933:     if ($gotlock eq 'ok') {
                   6934:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6935:         my $id = time;
                   6936:         $newid = $id;
1.1268    raeburn  6937:         if ($idtype eq 'addcode') {
                   6938:             $newid .= &sixnum_code();
                   6939:         }
1.1198    raeburn  6940:         my $idtries = 0;
                   6941:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6942:             if ($idtype eq 'concat') {
                   6943:                 $newid = $id.$idtries;
1.1268    raeburn  6944:             } elsif ($idtype eq 'addcode') {
                   6945:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6946:             } else {
                   6947:                 $newid ++;
                   6948:             }
                   6949:             $idtries ++;
                   6950:         }
                   6951:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6952:             my %new_item =  (
                   6953:                               $prefix."\0".$newid => $who,
                   6954:                             );
                   6955:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6956:                                                  $cdom,$cnum);
                   6957:             if ($putresult ne 'ok') {
                   6958:                 undef($newid);
                   6959:                 $error = 'error saving new item: '.$putresult;
                   6960:             }
                   6961:         } else {
1.1268    raeburn  6962:              undef($newid);
1.1198    raeburn  6963:              $error = ('error: no unique suffix available for the new item ');
                   6964:         }
                   6965: #  remove lock
                   6966:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6967:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6968:     } else {
                   6969:         $error = "error: could not obtain lockfile\n";
                   6970:         $dellock = 'ok';
1.1276    raeburn  6971:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6972:             $dellock = 'nolock';
                   6973:         }
1.1198    raeburn  6974:     }
                   6975:     return ($newid,$dellock,$error);
                   6976: }
                   6977: 
1.1268    raeburn  6978: sub sixnum_code {
                   6979:     my $code;
                   6980:     for (0..6) {
                   6981:         $code .= int( rand(9) );
                   6982:     }
                   6983:     return $code;
                   6984: }
                   6985: 
1.765     albertel 6986: # -------------------------------------------------- portfolio access checking
                   6987: 
                   6988: sub portfolio_access {
1.1270    raeburn  6989:     my ($requrl,$clientip) = @_;
1.765     albertel 6990:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6991:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6992:     if ($result) {
                   6993:         my %setters;
                   6994:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6995:             my ($startblock,$endblock) =
                   6996:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6997:             if ($startblock && $endblock) {
                   6998:                 return 'B';
                   6999:             }
                   7000:         } else {
                   7001:             my ($startblock,$endblock) =
                   7002:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7003:             if ($startblock && $endblock) {
                   7004:                 return 'B';
                   7005:             }
                   7006:         }
                   7007:     }
1.765     albertel 7008:     if ($result eq 'ok') {
1.766     albertel 7009:        return 'F';
1.765     albertel 7010:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7011:        return 'A';
1.765     albertel 7012:     }
1.766     albertel 7013:     return '';
1.765     albertel 7014: }
                   7015: 
                   7016: sub get_portfolio_access {
1.1270    raeburn  7017:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7018: 
                   7019:     if (!ref($access_hash)) {
                   7020: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7021: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7022: 						   $file_name);
                   7023: 	$access_hash = $access_controls{$file_name};
                   7024:     }
                   7025: 
1.1270    raeburn  7026:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7027:     my $now = time;
                   7028:     if (ref($access_hash) eq 'HASH') {
                   7029:         foreach my $key (keys(%{$access_hash})) {
                   7030:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7031:             if ($start > $now) {
                   7032:                 next;
                   7033:             }
                   7034:             if ($end && $end<$now) {
                   7035:                 next;
                   7036:             }
                   7037:             if ($scope eq 'public') {
                   7038:                 $public = $key;
                   7039:                 last;
                   7040:             } elsif ($scope eq 'guest') {
                   7041:                 $guest = $key;
                   7042:             } elsif ($scope eq 'domains') {
                   7043:                 push(@domains,$key);
                   7044:             } elsif ($scope eq 'users') {
                   7045:                 push(@users,$key);
                   7046:             } elsif ($scope eq 'course') {
                   7047:                 push(@courses,$key);
                   7048:             } elsif ($scope eq 'group') {
                   7049:                 push(@groups,$key);
1.1270    raeburn  7050:             } elsif ($scope eq 'ip') {
                   7051:                 push(@ips,$key);
1.765     albertel 7052:             }
                   7053:         }
                   7054:         if ($public) {
                   7055:             return 'ok';
1.1270    raeburn  7056:         } elsif (@ips > 0) {
                   7057:             my $allowed;
                   7058:             foreach my $ipkey (@ips) {
                   7059:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7060:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7061:                         $allowed = 1;
                   7062:                         last; 
                   7063:                     }
                   7064:                 }
                   7065:             }
                   7066:             if ($allowed) {
                   7067:                 return 'ok';
                   7068:             }
1.765     albertel 7069:         }
                   7070:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7071:             if ($guest) {
                   7072:                 return $guest;
                   7073:             }
                   7074:         } else {
                   7075:             if (@domains > 0) {
                   7076:                 foreach my $domkey (@domains) {
                   7077:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7078:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7079:                             return 'ok';
                   7080:                         }
                   7081:                     }
                   7082:                 }
                   7083:             }
                   7084:             if (@users > 0) {
                   7085:                 foreach my $userkey (@users) {
1.865     raeburn  7086:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7087:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7088:                             if (ref($item) eq 'HASH') {
                   7089:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7090:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7091:                                     return 'ok';
                   7092:                                 }
                   7093:                             }
                   7094:                         }
                   7095:                     } 
1.765     albertel 7096:                 }
                   7097:             }
                   7098:             my %roleshash;
                   7099:             my @courses_and_groups = @courses;
                   7100:             push(@courses_and_groups,@groups); 
                   7101:             if (@courses_and_groups > 0) {
                   7102:                 my (%allgroups,%allroles); 
                   7103:                 my ($start,$end,$role,$sec,$group);
                   7104:                 foreach my $envkey (%env) {
1.1060    raeburn  7105:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7106:                         my $cid = $2.'_'.$3; 
                   7107:                         if ($1 eq 'gr') {
                   7108:                             $group = $4;
                   7109:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7110:                         } else {
                   7111:                             if ($4 eq '') {
                   7112:                                 $sec = 'none';
                   7113:                             } else {
                   7114:                                 $sec = $4;
                   7115:                             }
                   7116:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7117:                         }
1.811     albertel 7118:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7119:                         my $cid = $2.'_'.$3;
                   7120:                         if ($4 eq '') {
                   7121:                             $sec = 'none';
                   7122:                         } else {
                   7123:                             $sec = $4;
                   7124:                         }
                   7125:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7126:                     }
                   7127:                 }
                   7128:                 if (keys(%allroles) == 0) {
                   7129:                     return;
                   7130:                 }
                   7131:                 foreach my $key (@courses_and_groups) {
                   7132:                     my %content = %{$$access_hash{$key}};
                   7133:                     my $cnum = $content{'number'};
                   7134:                     my $cdom = $content{'domain'};
                   7135:                     my $cid = $cdom.'_'.$cnum;
                   7136:                     if (!exists($allroles{$cid})) {
                   7137:                         next;
                   7138:                     }    
                   7139:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7140:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7141:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7142:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7143:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7144:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7145:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7146:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7147:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7148:                                         if (grep/^all$/,@sections) {
                   7149:                                             return 'ok';
                   7150:                                         } else {
                   7151:                                             if (grep/^$sec$/,@sections) {
                   7152:                                                 return 'ok';
                   7153:                                             }
                   7154:                                         }
                   7155:                                     }
                   7156:                                 }
                   7157:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7158:                                     if (grep/^none$/,@groups) {
                   7159:                                         return 'ok';
                   7160:                                     }
                   7161:                                 } else {
                   7162:                                     if (grep/^all$/,@groups) {
                   7163:                                         return 'ok';
                   7164:                                     } 
                   7165:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7166:                                         if (grep/^$group$/,@groups) {
                   7167:                                             return 'ok';
                   7168:                                         }
                   7169:                                     }
                   7170:                                 } 
                   7171:                             }
                   7172:                         }
                   7173:                     }
                   7174:                 }
                   7175:             }
                   7176:             if ($guest) {
                   7177:                 return $guest;
                   7178:             }
                   7179:         }
                   7180:     }
                   7181:     return;
                   7182: }
                   7183: 
                   7184: sub course_group_datechecker {
                   7185:     my ($dates,$now,$status) = @_;
                   7186:     my ($start,$end) = split(/\./,$dates);
                   7187:     if (!$start && !$end) {
                   7188:         return 'ok';
                   7189:     }
                   7190:     if (grep/^active$/,@{$status}) {
                   7191:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7192:             return 'ok';
                   7193:         }
                   7194:     }
                   7195:     if (grep/^previous$/,@{$status}) {
                   7196:         if ($end > $now ) {
                   7197:             return 'ok';
                   7198:         }
                   7199:     }
                   7200:     if (grep/^future$/,@{$status}) {
                   7201:         if ($start > $now) {
                   7202:             return 'ok';
                   7203:         }
                   7204:     }
                   7205:     return; 
                   7206: }
                   7207: 
                   7208: sub parse_portfolio_url {
                   7209:     my ($url) = @_;
                   7210: 
                   7211:     my ($type,$udom,$unum,$group,$file_name);
                   7212:     
1.823     albertel 7213:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7214: 	$type = 1;
                   7215:         $udom = $1;
                   7216:         $unum = $2;
                   7217:         $file_name = $3;
1.823     albertel 7218:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7219: 	$type = 2;
                   7220:         $udom = $1;
                   7221:         $unum = $2;
                   7222:         $group = $3;
                   7223:         $file_name = $3.'/'.$4;
                   7224:     }
                   7225:     if (wantarray) {
                   7226: 	return ($type,$udom,$unum,$file_name,$group);
                   7227:     }
                   7228:     return $type;
                   7229: }
                   7230: 
                   7231: sub is_portfolio_url {
                   7232:     my ($url) = @_;
                   7233:     return scalar(&parse_portfolio_url($url));
                   7234: }
                   7235: 
1.798     raeburn  7236: sub is_portfolio_file {
                   7237:     my ($file) = @_;
1.820     raeburn  7238:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7239:         return 1;
                   7240:     }
                   7241:     return;
                   7242: }
                   7243: 
1.976     raeburn  7244: sub usertools_access {
1.1084    raeburn  7245:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7246:     my ($access,%tools);
                   7247:     if ($context eq '') {
                   7248:         $context = 'tools';
                   7249:     }
                   7250:     if ($context eq 'requestcourses') {
                   7251:         %tools = (
                   7252:                       official   => 1,
                   7253:                       unofficial => 1,
1.1006    raeburn  7254:                       community  => 1,
1.1246    raeburn  7255:                       textbook   => 1,
1.1305    raeburn  7256:                       placement  => 1,
1.1368    raeburn  7257:                       lti        => 1,
1.985     raeburn  7258:                  );
1.1183    raeburn  7259:     } elsif ($context eq 'requestauthor') {
                   7260:         %tools = (
                   7261:                       requestauthor => 1,
                   7262:                  );
1.985     raeburn  7263:     } else {
                   7264:         %tools = (
                   7265:                       aboutme   => 1,
                   7266:                       blog      => 1,
1.1177    raeburn  7267:                       webdav    => 1,
1.985     raeburn  7268:                       portfolio => 1,
                   7269:                  );
                   7270:     }
1.976     raeburn  7271:     return if (!defined($tools{$tool}));
                   7272: 
1.1242    raeburn  7273:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7274:         $udom = $env{'user.domain'};
                   7275:         $uname = $env{'user.name'};
                   7276:     }
                   7277: 
1.978     raeburn  7278:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7279:         if ($action ne 'reload') {
1.985     raeburn  7280:             if ($context eq 'requestcourses') {
                   7281:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7282:             } elsif ($context eq 'requestauthor') {
                   7283:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7284:             } else {
                   7285:                 return $env{'environment.availabletools.'.$tool};
                   7286:             }
                   7287:         }
1.976     raeburn  7288:     }
                   7289: 
1.1183    raeburn  7290:     my ($toolstatus,$inststatus,$envkey);
                   7291:     if ($context eq 'requestauthor') {
                   7292:         $envkey = $context; 
                   7293:     } else {
                   7294:         $envkey = $context.'.'.$tool;
                   7295:     }
1.976     raeburn  7296: 
1.985     raeburn  7297:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7298:          ($action ne 'reload')) {
1.1183    raeburn  7299:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7300:         $inststatus = $env{'environment.inststatus'};
                   7301:     } else {
1.1084    raeburn  7302:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7303:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7304:             $inststatus = $userenvref->{'inststatus'};
                   7305:         } else {
1.1183    raeburn  7306:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7307:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7308:             $inststatus = $userenv{'inststatus'};
                   7309:         }
1.976     raeburn  7310:     }
                   7311: 
                   7312:     if ($toolstatus ne '') {
                   7313:         if ($toolstatus) {
                   7314:             $access = 1;
                   7315:         } else {
                   7316:             $access = 0;
                   7317:         }
                   7318:         return $access;
                   7319:     }
                   7320: 
1.1084    raeburn  7321:     my ($is_adv,%domdef);
                   7322:     if (ref($is_advref) eq 'HASH') {
                   7323:         $is_adv = $is_advref->{'is_adv'};
                   7324:     } else {
                   7325:         $is_adv = &is_advanced_user($udom,$uname);
                   7326:     }
                   7327:     if (ref($domdefref) eq 'HASH') {
                   7328:         %domdef = %{$domdefref};
                   7329:     } else {
                   7330:         %domdef = &get_domain_defaults($udom);
                   7331:     }
1.976     raeburn  7332:     if (ref($domdef{$tool}) eq 'HASH') {
                   7333:         if ($is_adv) {
                   7334:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7335:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7336:                     $access = 1;
                   7337:                 } else {
                   7338:                     $access = 0;
                   7339:                 }
                   7340:                 return $access;
                   7341:             }
                   7342:         }
                   7343:         if ($inststatus ne '') {
                   7344:             my ($hasaccess,$hasnoaccess);
                   7345:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7346:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7347:                     if ($domdef{$tool}{$affiliation}) {
                   7348:                         $hasaccess = 1;
                   7349:                     } else {
                   7350:                         $hasnoaccess = 1;
                   7351:                     }
                   7352:                 }
                   7353:             }
                   7354:             if ($hasaccess || $hasnoaccess) {
                   7355:                 if ($hasaccess) {
                   7356:                     $access = 1;
                   7357:                 } elsif ($hasnoaccess) {
                   7358:                     $access = 0; 
                   7359:                 }
                   7360:                 return $access;
                   7361:             }
                   7362:         } else {
                   7363:             if ($domdef{$tool}{'default'} ne '') {
                   7364:                 if ($domdef{$tool}{'default'}) {
                   7365:                     $access = 1;
                   7366:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7367:                     $access = 0;
                   7368:                 }
                   7369:                 return $access;
                   7370:             }
                   7371:         }
                   7372:     } else {
1.1177    raeburn  7373:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7374:             $access = 1;
                   7375:         } else {
                   7376:             $access = 0;
                   7377:         }
1.976     raeburn  7378:         return $access;
                   7379:     }
                   7380: }
                   7381: 
1.1050    raeburn  7382: sub is_course_owner {
                   7383:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7384:     if (($udom eq '') || ($uname eq '')) {
                   7385:         $udom = $env{'user.domain'};
                   7386:         $uname = $env{'user.name'};
                   7387:     }
                   7388:     unless (($udom eq '') || ($uname eq '')) {
                   7389:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7390:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7391:                 return 1;
                   7392:             } else {
                   7393:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7394:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7395:                     return 1;
                   7396:                 }
                   7397:             }
                   7398:         }
                   7399:     }
                   7400:     return;
                   7401: }
                   7402: 
1.976     raeburn  7403: sub is_advanced_user {
                   7404:     my ($udom,$uname) = @_;
1.1085    raeburn  7405:     if ($udom ne '' && $uname ne '') {
                   7406:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7407:             if (wantarray) {
                   7408:                 return ($env{'user.adv'},$env{'user.author'});
                   7409:             } else {
                   7410:                 return $env{'user.adv'};
                   7411:             }
1.1085    raeburn  7412:         }
                   7413:     }
1.976     raeburn  7414:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7415:     my %allroles;
1.1128    raeburn  7416:     my ($is_adv,$is_author);
1.976     raeburn  7417:     foreach my $role (keys(%roleshash)) {
                   7418:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7419:         my $area = '/'.$tdomain.'/'.$trest;
                   7420:         if ($sec ne '') {
                   7421:             $area .= '/'.$sec;
                   7422:         }
                   7423:         if (($area ne '') && ($trole ne '')) {
                   7424:             my $spec=$trole.'.'.$area;
                   7425:             if ($trole =~ /^cr\//) {
                   7426:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7427:             } elsif ($trole ne 'gr') {
                   7428:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7429:             }
1.1128    raeburn  7430:             if ($trole eq 'au') {
                   7431:                 $is_author = 1;
                   7432:             }
1.976     raeburn  7433:         }
                   7434:     }
                   7435:     foreach my $role (keys(%allroles)) {
                   7436:         last if ($is_adv);
                   7437:         foreach my $item (split(/:/,$allroles{$role})) {
                   7438:             if ($item ne '') {
                   7439:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7440:                 if ($privilege eq 'adv') {
                   7441:                     $is_adv = 1;
                   7442:                     last;
                   7443:                 }
                   7444:             }
                   7445:         }
                   7446:     }
1.1128    raeburn  7447:     if (wantarray) {
                   7448:         return ($is_adv,$is_author);
                   7449:     }
1.976     raeburn  7450:     return $is_adv;
                   7451: }
1.798     raeburn  7452: 
1.1035    raeburn  7453: sub check_can_request {
1.1368    raeburn  7454:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7455:     my $canreq = 0;
1.1368    raeburn  7456:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7457:         $uname = $env{'user.name'};
                   7458:         $udom = $env{'user.domain'};
                   7459:     }
1.1035    raeburn  7460:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7461:     my @options = ('approval','validate','autolimit');
                   7462:     my $optregex = join('|',@options);
                   7463:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7464:         foreach my $type (@{$types}) {
1.1368    raeburn  7465:             if (&usertools_access($uname,$udom,$type,undef,
                   7466:                                   'requestcourses')) {
1.1035    raeburn  7467:                 $canreq ++;
1.1036    raeburn  7468:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7469:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7470:                 }
1.1368    raeburn  7471:                 if ($dom eq $udom) {
1.1035    raeburn  7472:                     $can_request->{$type} = 1;
                   7473:                 }
                   7474:             }
1.1368    raeburn  7475:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7476:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7477:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7478:                 if (@curr > 0) {
1.1036    raeburn  7479:                     foreach my $item (@curr) {
                   7480:                         if (ref($request_domains) eq 'HASH') {
                   7481:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7482:                             if ($otherdom ne '') {
                   7483:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7484:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7485:                                         push(@{$request_domains->{$type}},$otherdom);
                   7486:                                     }
                   7487:                                 } else {
                   7488:                                     push(@{$request_domains->{$type}},$otherdom);
                   7489:                                 }
                   7490:                             }
                   7491:                         }
                   7492:                     }
1.1368    raeburn  7493:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7494:                         $canreq ++;
1.1035    raeburn  7495:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7496:                             $can_request->{$type} = 1;
                   7497:                         }
                   7498:                     }
                   7499:                 }
                   7500:             }
                   7501:         }
                   7502:     }
                   7503:     return $canreq;
                   7504: }
                   7505: 
1.341     www      7506: # ---------------------------------------------- Custom access rule evaluation
                   7507: 
                   7508: sub customaccess {
                   7509:     my ($priv,$uri)=@_;
1.807     albertel 7510:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7511:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7512:     $udom = &LONCAPA::clean_domain($udom);
                   7513:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7514:     my $access=0;
1.800     albertel 7515:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7516: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7517: 	if ($type eq 'user') {
                   7518: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7519: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7520: 		if ($tdom) {
                   7521: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7522: 		}
1.896     albertel 7523: 		if ($tuname) {
                   7524: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7525: 		}
                   7526: 		$access=($effect eq 'allow');
                   7527: 		last;
                   7528: 	    }
                   7529: 	} else {
                   7530: 	    if ($role) {
                   7531: 		if ($role ne $urole) { next; }
                   7532: 	    }
                   7533: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7534: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7535: 		if ($tdom) {
                   7536: 		    if ($tdom ne $udom) { next; }
                   7537: 		}
                   7538: 		if ($tcrs) {
                   7539: 		    if ($tcrs ne $ucrs) { next; }
                   7540: 		}
                   7541: 		if ($tsec) {
                   7542: 		    if ($tsec ne $usec) { next; }
                   7543: 		}
                   7544: 		$access=($effect eq 'allow');
                   7545: 		last;
                   7546: 	    }
                   7547: 	    if ($realm eq '' && $role eq '') {
                   7548: 		$access=($effect eq 'allow');
                   7549: 	    }
1.402     bowersj2 7550: 	}
1.341     www      7551:     }
                   7552:     return $access;
                   7553: }
                   7554: 
1.103     harris41 7555: # ------------------------------------------------- Check for a user privilege
1.12      www      7556: 
                   7557: sub allowed {
1.1281    raeburn  7558:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7559:     my $ver_orguri=$uri;
1.439     www      7560:     $uri=&deversion($uri);
1.152     www      7561:     my $orguri=$uri;
1.52      www      7562:     $uri=&declutter($uri);
1.809     raeburn  7563: 
1.810     raeburn  7564:     if ($priv eq 'evb') {
                   7565: # Evade communication block restrictions for specified role in a course
                   7566:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7567:             return $1;
                   7568:         } else {
                   7569:             return;
                   7570:         }
                   7571:     }
                   7572: 
1.620     albertel 7573:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7574: # Free bre access to adm and meta resources
1.1343    raeburn  7575:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7576: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7577: 	&& ($priv eq 'bre')) {
1.14      www      7578: 	return 'F';
1.159     www      7579:     }
                   7580: 
1.545     banghart 7581: # Free bre access to user's own portfolio contents
1.714     raeburn  7582:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7583:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7584: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7585:         my %setters;
                   7586:         my ($startblock,$endblock) = 
                   7587:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7588:         if ($startblock && $endblock) {
                   7589:             return 'B';
                   7590:         } else {
                   7591:             return 'F';
                   7592:         }
1.545     banghart 7593:     }
                   7594: 
1.762     raeburn  7595: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7596:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7597:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7598:         if (exists($env{'request.course.id'})) {
                   7599:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7600:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7601:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7602:                 my $courseprivid=$env{'request.course.id'};
                   7603:                 $courseprivid=~s/\_/\//;
                   7604:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7605:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7606:                     return $1; 
1.762     raeburn  7607:                 } else {
                   7608:                     if ($env{'request.course.sec'}) {
                   7609:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7610:                     }
                   7611:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7612:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7613:                         return $2;
                   7614:                     }
1.714     raeburn  7615:                 }
                   7616:             }
                   7617:         }
                   7618:     }
                   7619: 
1.159     www      7620: # Free bre to public access
                   7621: 
                   7622:     if ($priv eq 'bre') {
1.1362    raeburn  7623:         my $copyright;
                   7624:         unless ($uri =~ /ext\.tool/) {
                   7625:             $copyright=&metadata($uri,'copyright');
                   7626:         }
1.620     albertel 7627: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7628:            return 'F'; 
                   7629:         }
1.238     www      7630:         if ($copyright eq 'priv') {
                   7631:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7632: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7633: 		return '';
                   7634:             }
                   7635:         }
                   7636:         if ($copyright eq 'domain') {
                   7637:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7638: 	    unless (($env{'user.domain'} eq $1) ||
                   7639:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7640: 		return '';
                   7641:             }
1.262     matthew  7642:         }
1.620     albertel 7643:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7644:             # Library role, so allow browsing of resources in this domain.
                   7645:             return 'F';
1.238     www      7646:         }
1.341     www      7647:         if ($copyright eq 'custom') {
                   7648: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7649:         }
1.14      www      7650:     }
1.264     matthew  7651:     # Domain coordinator is trying to create a course
1.620     albertel 7652:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7653:         # uri is the requested domain in this case.
                   7654:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7655:         # a role of dc for the domain in question.
1.620     albertel 7656:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7657:     }
1.29      www      7658: 
1.52      www      7659:     my $thisallowed='';
                   7660:     my $statecond=0;
                   7661:     my $courseprivid='';
                   7662: 
1.1039    raeburn  7663:     my $ownaccess;
1.1043    raeburn  7664:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7665:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7666:         if ($uri eq '') {
                   7667:             $ownaccess = 1;
                   7668:         } else {
                   7669:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7670:                 my $udom = $env{'user.domain'};
                   7671:                 my $uname = $env{'user.name'};
                   7672:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7673:                     $ownaccess = 1;
1.1040    raeburn  7674:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7675:                     unless ($uri =~ m{\.\./}) {
                   7676:                         $ownaccess = 1;
                   7677:                     }
                   7678:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7679:                     my $now = time;
                   7680:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7681:                         my $adom = $1;
                   7682:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7683:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7684:                                 my ($start,$end) = split('.',$env{$key});
                   7685:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7686:                                     $ownaccess = 1;
                   7687:                                     last;
                   7688:                                 }
                   7689:                             }
                   7690:                         }
                   7691:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7692:                         my $adom = $1;
                   7693:                         my $aname = $2;
1.1042    raeburn  7694:                         foreach my $role ('ca','aa') { 
                   7695:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7696:                                 my ($start,$end) =
                   7697:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7698:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7699:                                     $ownaccess = 1;
                   7700:                                     last;
                   7701:                                 }
1.1039    raeburn  7702:                             }
                   7703:                         }
                   7704:                     }
                   7705:                 }
                   7706:             }
                   7707:         }
                   7708:     }
                   7709: 
1.52      www      7710: # Course
                   7711: 
1.620     albertel 7712:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7713:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7714:             $thisallowed.=$1;
                   7715:         }
1.52      www      7716:     }
1.29      www      7717: 
1.52      www      7718: # Domain
                   7719: 
1.620     albertel 7720:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7721:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7722:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7723:             $thisallowed.=$1;
                   7724:         }
1.12      www      7725:     }
1.52      www      7726: 
1.1141    raeburn  7727: # User who is not author or co-author might still be able to edit
                   7728: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7729:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7730:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7731:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7732:             $thisallowed.=$1;
                   7733:         }
                   7734:     }
                   7735: 
1.52      www      7736: # Course: uri itself is a course
1.66      www      7737:     my $courseuri=$uri;
                   7738:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7739:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7740: 
1.620     albertel 7741:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7742:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7743:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7744:             $thisallowed.=$1;
                   7745:         }
1.12      www      7746:     }
1.29      www      7747: 
1.665     albertel 7748: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7749: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7750:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7751: 	$thisallowed='';
1.671     raeburn  7752:         my ($match)=&is_on_map($uri);
                   7753:         if ($match) {
                   7754:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7755:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7756:                 my $value = $1;
                   7757:                 if ($noblockcheck) {
                   7758:                     $thisallowed.=$value;
1.1162    raeburn  7759:                 } else {
1.1281    raeburn  7760:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7761:                     if (@blockers > 0) {
                   7762:                         $thisallowed = 'B';
                   7763:                     } else {
                   7764:                         $thisallowed.=$value;
                   7765:                     }
1.1162    raeburn  7766:                 }
1.671     raeburn  7767:             }
                   7768:         } else {
1.705     albertel 7769:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7770:             if ($refuri) {
                   7771:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7772:                     $thisallowed='F';
1.671     raeburn  7773:                 } else {
                   7774:                     $refuri=&declutter($refuri);
                   7775:                     my ($match) = &is_on_map($refuri);
                   7776:                     if ($match) {
1.1281    raeburn  7777:                         if ($noblockcheck) {
                   7778:                             $thisallowed='F';
1.1162    raeburn  7779:                         } else {
1.1281    raeburn  7780:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7781:                             if (@blockers > 0) {
                   7782:                                 $thisallowed = 'B';
                   7783:                             } else {
                   7784:                                 $thisallowed='F';
                   7785:                             }
1.1162    raeburn  7786:                         }
1.671     raeburn  7787:                     }
1.669     raeburn  7788:                 }
1.671     raeburn  7789:             }
                   7790:         }
1.314     www      7791:     }
1.492     albertel 7792: 
1.766     albertel 7793:     if ($priv eq 'bre'
                   7794: 	&& $thisallowed ne 'F' 
                   7795: 	&& $thisallowed ne '2'
                   7796: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7797: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7798:     }
1.1250    raeburn  7799: 
1.52      www      7800: # Full access at system, domain or course-wide level? Exit.
1.29      www      7801:     if ($thisallowed=~/F/) {
                   7802: 	return 'F';
                   7803:     }
                   7804: 
1.52      www      7805: # If this is generating or modifying users, exit with special codes
1.29      www      7806: 
1.643     www      7807:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7808: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7809: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7810: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7811: 	    unless ($auname) { return $thisallowed; }
                   7812: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7813: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7814: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7815: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7816: 	}
1.52      www      7817: 	return $thisallowed;
                   7818:     }
                   7819: #
1.103     harris41 7820: # Gathered so far: system, domain and course wide privileges
1.52      www      7821: #
                   7822: # Course: See if uri or referer is an individual resource that is part of 
                   7823: # the course
                   7824: 
1.620     albertel 7825:     if ($env{'request.course.id'}) {
1.232     www      7826: 
1.620     albertel 7827:        $courseprivid=$env{'request.course.id'};
                   7828:        if ($env{'request.course.sec'}) {
                   7829:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7830:        }
                   7831:        $courseprivid=~s/\_/\//;
                   7832:        my $checkreferer=1;
1.232     www      7833:        my ($match,$cond)=&is_on_map($uri);
                   7834:        if ($match) {
                   7835:            $statecond=$cond;
1.620     albertel 7836:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7837:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7838:                my $value = $1;
                   7839:                if ($priv eq 'bre') {
1.1281    raeburn  7840:                    if ($noblockcheck) {
                   7841:                        $thisallowed.=$value;
1.1162    raeburn  7842:                    } else {
1.1281    raeburn  7843:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7844:                        if (@blockers > 0) {
                   7845:                            $thisallowed = 'B';
                   7846:                        } else {
                   7847:                            $thisallowed.=$value;
                   7848:                        }
1.1162    raeburn  7849:                    }
                   7850:                } else {
                   7851:                    $thisallowed.=$value;
                   7852:                }
1.52      www      7853:                $checkreferer=0;
                   7854:            }
1.29      www      7855:        }
1.83      www      7856:        
1.148     www      7857:        if ($checkreferer) {
1.620     albertel 7858: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7859:             unless ($refuri) {
1.800     albertel 7860:                 foreach my $key (keys(%env)) {
                   7861: 		    if ($key=~/^httpref\..*\*/) {
                   7862: 			my $pattern=$key;
1.156     www      7863:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7864:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7865:                         $pattern=~s/\//\\\//g;
1.152     www      7866:                         if ($orguri=~/$pattern/) {
1.800     albertel 7867: 			    $refuri=$env{$key};
1.148     www      7868:                         }
                   7869:                     }
1.191     harris41 7870:                 }
1.148     www      7871:             }
1.232     www      7872: 
1.148     www      7873:          if ($refuri) { 
1.152     www      7874: 	  $refuri=&declutter($refuri);
1.232     www      7875:           my ($match,$cond)=&is_on_map($refuri);
                   7876:             if ($match) {
                   7877:               my $refstatecond=$cond;
1.620     albertel 7878:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7879:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7880:                   my $value = $1;
                   7881:                   if ($priv eq 'bre') {
1.1281    raeburn  7882:                       if ($noblockcheck) {
                   7883:                           $thisallowed.=$value;
1.1162    raeburn  7884:                       } else {
1.1281    raeburn  7885:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7886:                           if (@blockers > 0) {
                   7887:                               $thisallowed = 'B';
                   7888:                           } else {
                   7889:                               $thisallowed.=$value;
                   7890:                           }
1.1162    raeburn  7891:                       }
                   7892:                   } else {
                   7893:                       $thisallowed.=$value;
                   7894:                   }
1.53      www      7895:                   $uri=$refuri;
                   7896:                   $statecond=$refstatecond;
1.52      www      7897:               }
                   7898:           }
1.148     www      7899:         }
1.29      www      7900:        }
1.52      www      7901:    }
1.29      www      7902: 
1.52      www      7903: #
1.103     harris41 7904: # Gathered now: all privileges that could apply, and condition number
1.52      www      7905: # 
                   7906: #
                   7907: # Full or no access?
                   7908: #
1.29      www      7909: 
1.52      www      7910:     if ($thisallowed=~/F/) {
                   7911: 	return 'F';
                   7912:     }
1.29      www      7913: 
1.52      www      7914:     unless ($thisallowed) {
                   7915:         return '';
                   7916:     }
1.29      www      7917: 
1.52      www      7918: # Restrictions exist, deal with them
                   7919: #
                   7920: #   C:according to course preferences
                   7921: #   R:according to resource settings
                   7922: #   L:unless locked
                   7923: #   X:according to user session state
                   7924: #
                   7925: 
                   7926: # Possibly locked functionality, check all courses
1.54      www      7927: # Locks might take effect only after 10 minutes cache expiration for other
                   7928: # courses, and 2 minutes for current course
1.52      www      7929: 
                   7930:     my $envkey;
                   7931:     if ($thisallowed=~/L/) {
1.1000    raeburn  7932:         foreach $envkey (keys(%env)) {
1.54      www      7933:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7934:                my $courseid=$2;
                   7935:                my $roleid=$1.'.'.$2;
1.92      www      7936:                $courseid=~s/^\///;
1.54      www      7937:                my $expiretime=600;
1.620     albertel 7938:                if ($env{'request.role'} eq $roleid) {
1.54      www      7939: 		  $expiretime=120;
                   7940:                }
                   7941: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7942:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7943:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7944: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7945:                }
1.620     albertel 7946:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7947:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7948: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7949:                        &log($env{'user.domain'},$env{'user.name'},
                   7950:                             $env{'user.home'},
1.57      www      7951:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7952:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7953:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7954: 		       return '';
                   7955:                    }
                   7956:                }
1.620     albertel 7957:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7958:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7959: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7960:                        &log($env{'user.domain'},$env{'user.name'},
                   7961:                             $env{'user.home'},
1.57      www      7962:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7963:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7964:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7965: 		       return '';
                   7966:                    }
                   7967:                }
                   7968: 	   }
1.29      www      7969:        }
1.52      www      7970:     }
                   7971:    
                   7972: #
                   7973: # Rest of the restrictions depend on selected course
                   7974: #
                   7975: 
1.620     albertel 7976:     unless ($env{'request.course.id'}) {
1.766     albertel 7977: 	if ($thisallowed eq 'A') {
                   7978: 	    return 'A';
1.814     raeburn  7979:         } elsif ($thisallowed eq 'B') {
                   7980:             return 'B';
1.766     albertel 7981: 	} else {
                   7982: 	    return '1';
                   7983: 	}
1.52      www      7984:     }
1.29      www      7985: 
1.52      www      7986: #
                   7987: # Now user is definitely in a course
                   7988: #
1.53      www      7989: 
                   7990: 
                   7991: # Course preferences
                   7992: 
                   7993:    if ($thisallowed=~/C/) {
1.620     albertel 7994:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7995:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7996:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7997: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7998: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7999: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8000: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8001: 			$env{'request.course.id'});
                   8002: 	   }
1.237     www      8003:            return '';
                   8004:        }
                   8005: 
1.620     albertel 8006:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8007: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8008: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8009: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8010: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8011: 			$env{'request.course.id'});
                   8012: 	   }
1.54      www      8013:            return '';
                   8014:        }
1.53      www      8015:    }
                   8016: 
                   8017: # Resource preferences
                   8018: 
                   8019:    if ($thisallowed=~/R/) {
1.620     albertel 8020:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8021:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8022: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8023: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8024: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8025: 	   }
                   8026: 	   return '';
1.54      www      8027:        }
1.53      www      8028:    }
1.30      www      8029: 
1.246     www      8030: # Restricted by state or randomout?
1.30      www      8031: 
1.52      www      8032:    if ($thisallowed=~/X/) {
1.620     albertel 8033:       if ($env{'acc.randomout'}) {
1.579     albertel 8034: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8035:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8036:             return ''; 
                   8037:          }
1.247     www      8038:       }
                   8039:       if (&condval($statecond)) {
1.52      www      8040: 	 return '2';
                   8041:       } else {
                   8042:          return '';
                   8043:       }
                   8044:    }
1.30      www      8045: 
1.766     albertel 8046:     if ($thisallowed eq 'A') {
                   8047: 	return 'A';
1.814     raeburn  8048:     } elsif ($thisallowed eq 'B') {
                   8049:         return 'B';
1.766     albertel 8050:     }
1.52      www      8051:    return 'F';
1.232     www      8052: }
1.1162    raeburn  8053: 
1.1192    raeburn  8054: # ------------------------------------------- Check construction space access
                   8055: 
                   8056: sub constructaccess {
                   8057:     my ($url,$setpriv)=@_;
                   8058: 
                   8059: # We do not allow editing of previous versions of files
                   8060:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8061: 
                   8062: # Get username and domain from URL
                   8063:     my ($ownername,$ownerdomain,$ownerhome);
                   8064: 
                   8065:     ($ownerdomain,$ownername) =
1.1325    raeburn  8066:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8067: 
                   8068: # The URL does not really point to any authorspace, forget it
                   8069:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8070: 
                   8071: # Now we need to see if the user has access to the authorspace of
                   8072: # $ownername at $ownerdomain
                   8073: 
                   8074:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8075: # Real author for this?
                   8076:        $ownerhome = $env{'user.home'};
                   8077:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8078:           return ($ownername,$ownerdomain,$ownerhome);
                   8079:        }
                   8080:     } else {
                   8081: # Co-author for this?
                   8082:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8083:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8084:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8085:             return ($ownername,$ownerdomain,$ownerhome);
                   8086:         }
1.1312    raeburn  8087:         if ($env{'request.course.id'}) {
                   8088:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8089:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8090:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8091:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8092:                     return ($ownername,$ownerdomain,$ownerhome);
                   8093:                 }
                   8094:             }
                   8095:         }
1.1192    raeburn  8096:     }
                   8097: 
                   8098: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8099: # we might as well leave
                   8100:    unless ($setpriv) { return ''; }
                   8101: 
                   8102: # Backdoor access?
                   8103:     my $allowed=&allowed('eco',$ownerdomain);
                   8104: # Nope
                   8105:     unless ($allowed) { return ''; }
                   8106: # Looks like we may have access, but could be locked by the owner of the construction space
                   8107:     if ($allowed eq 'U') {
                   8108:         my %blocked=&get('environment',['domcoord.author'],
                   8109:                          $ownerdomain,$ownername);
                   8110: # Is blocked by owner
                   8111:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8112:     }
                   8113:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8114: # Grant temporary access
                   8115:         my $then=$env{'user.login.time'};
1.1209    raeburn  8116:         my $update=$env{'user.update.time'};
1.1192    raeburn  8117:         if (!$update) { $update = $then; }
                   8118:         my $refresh=$env{'user.refresh.time'};
                   8119:         if (!$refresh) { $refresh = $update; }
                   8120:         my $now = time;
                   8121:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8122:                            $now,'ca','constructaccess');
                   8123:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8124:         return($ownername,$ownerdomain,$ownerhome);
                   8125:     }
                   8126: # No business here
                   8127:     return '';
                   8128: }
                   8129: 
1.1282    raeburn  8130: # ----------------------------------------------------------- Content Blocking
                   8131: 
                   8132: {
                   8133: # Caches for faster Course Contents display where content blocking
                   8134: # is in operation (i.e., interval param set) for timed quiz.
                   8135: #
                   8136: # User for whom data are being temporarily cached.
                   8137: my $cacheduser='';
                   8138: # Cached blockers for this user (a hash of blocking items). 
                   8139: my %cachedblockers=();
                   8140: # When the data were last cached.
                   8141: my $cachedlast='';
                   8142: 
                   8143: sub load_all_blockers {
                   8144:     my ($uname,$udom,$blocks)=@_;
                   8145:     if (($uname ne '') && ($udom ne '')) { 
                   8146:         if (($cacheduser eq $uname.':'.$udom) &&
                   8147:             (abs($cachedlast-time)<5)) {
                   8148:             return;
                   8149:         }
                   8150:     }
                   8151:     $cachedlast=time;
                   8152:     $cacheduser=$uname.':'.$udom;
                   8153:     %cachedblockers = &get_commblock_resources($blocks);
                   8154: }
                   8155: 
1.1162    raeburn  8156: sub get_comm_blocks {
                   8157:     my ($cdom,$cnum) = @_;
                   8158:     if ($cdom eq '' || $cnum eq '') {
                   8159:         return unless ($env{'request.course.id'});
                   8160:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8161:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8162:     }
                   8163:     my %commblocks;
                   8164:     my $hashid=$cdom.'_'.$cnum;
                   8165:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8166:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8167:         %commblocks = %{$blocksref};
                   8168:     } else {
                   8169:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8170:         my $cachetime = 600;
                   8171:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8172:     }
                   8173:     return %commblocks;
                   8174: }
                   8175: 
1.1282    raeburn  8176: sub get_commblock_resources {
                   8177:     my ($blocks) = @_;
                   8178:     my %blockers = ();
                   8179:     return %blockers unless ($env{'request.course.id'});
                   8180:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8181:     my %commblocks;
                   8182:     if (ref($blocks) eq 'HASH') {
                   8183:         %commblocks = %{$blocks};
                   8184:     } else {
                   8185:         %commblocks = &get_comm_blocks();
                   8186:     }
1.1282    raeburn  8187:     return %blockers unless (keys(%commblocks) > 0); 
                   8188:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8189:     return %blockers unless (ref($navmap));
1.1162    raeburn  8190:     my $now = time;
                   8191:     foreach my $block (keys(%commblocks)) {
                   8192:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8193:             my ($start,$end) = ($1,$2);
                   8194:             if ($start <= $now && $end >= $now) {
                   8195:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8196:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8197:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8198:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8199:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8200:                             }
                   8201:                         }
                   8202:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8203:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8204:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8205:                             }
                   8206:                         }
                   8207:                     }
                   8208:                 }
                   8209:             }
                   8210:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8211:             my $item = $1;
1.1163    raeburn  8212:             my @to_test;
1.1162    raeburn  8213:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8214:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8215:                     my @interval;
                   8216:                     my $type = 'map';
                   8217:                     if ($item eq 'course') {
                   8218:                         $type = 'course';
                   8219:                         @interval=&EXT("resource.0.interval");
                   8220:                     } else {
                   8221:                         if ($item =~ /___\d+___/) {
                   8222:                             $type = 'resource';
                   8223:                             @interval=&EXT("resource.0.interval",$item);
                   8224:                             if (ref($navmap)) {                        
                   8225:                                 my $res = $navmap->getBySymb($item); 
                   8226:                                 push(@to_test,$res);
                   8227:                             }
1.1162    raeburn  8228:                         } else {
1.1282    raeburn  8229:                             my $mapsymb = &symbread($item,1);
                   8230:                             if ($mapsymb) {
                   8231:                                 if (ref($navmap)) {
                   8232:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8233:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8234:                                     foreach my $res (@to_test) {
                   8235:                                         my $symb = $res->symb();
                   8236:                                         next if ($symb eq $mapsymb);
                   8237:                                         if ($symb ne '') {
                   8238:                                             @interval=&EXT("resource.0.interval",$symb);
                   8239:                                             if ($interval[1] eq 'map') {
                   8240:                                                 last;
1.1162    raeburn  8241:                                             }
                   8242:                                         }
                   8243:                                     }
                   8244:                                 }
                   8245:                             }
                   8246:                         }
1.1282    raeburn  8247:                     }
1.1310    raeburn  8248:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8249:                         my $timelimit = $1; 
1.1282    raeburn  8250:                         my $first_access;
                   8251:                         if ($type eq 'resource') {
                   8252:                             $first_access=&get_first_access($interval[1],$item);
                   8253:                         } elsif ($type eq 'map') {
                   8254:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8255:                         } else {
                   8256:                             $first_access=&get_first_access($interval[1]);
                   8257:                         }
                   8258:                         if ($first_access) {
1.1292    raeburn  8259:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8260:                             if ($timesup > $now) {
                   8261:                                 my $activeblock;
                   8262:                                 foreach my $res (@to_test) {
1.1283    raeburn  8263:                                     if ($res->answerable()) {
1.1282    raeburn  8264:                                         $activeblock = 1;
                   8265:                                         last;
                   8266:                                     }
                   8267:                                 }
                   8268:                                 if ($activeblock) {
                   8269:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8270:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8271:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8272:                                          }
                   8273:                                     }
                   8274:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8275:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8276:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8277:                                         }
1.1162    raeburn  8278:                                     }
                   8279:                                 }
                   8280:                             }
                   8281:                         }
                   8282:                     }
                   8283:                 }
                   8284:             }
                   8285:         }
                   8286:     }
1.1282    raeburn  8287:     return %blockers;
1.1162    raeburn  8288: }
                   8289: 
1.1282    raeburn  8290: sub has_comm_blocking {
                   8291:     my ($priv,$symb,$uri,$blocks) = @_;
                   8292:     my @blockers;
                   8293:     return unless ($env{'request.course.id'});
                   8294:     return unless ($priv eq 'bre');
                   8295:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8296:     return if ($env{'request.state'} eq 'construct');
                   8297:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8298:     return unless (keys(%cachedblockers) > 0);
                   8299:     my (%possibles,@symbs);
                   8300:     if (!$symb) {
                   8301:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8302:     }
1.1282    raeburn  8303:     if ($symb) {
                   8304:         @symbs = ($symb);
                   8305:     } elsif (keys(%possibles)) { 
                   8306:         @symbs = keys(%possibles);
                   8307:     }
                   8308:     my $noblock;
                   8309:     foreach my $symb (@symbs) {
                   8310:         last if ($noblock);
                   8311:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8312:         foreach my $block (keys(%cachedblockers)) {
                   8313:             if ($block =~ /^firstaccess____(.+)$/) {
                   8314:                 my $item = $1;
                   8315:                 if (($item eq $map) || ($item eq $symb)) {
                   8316:                     $noblock = 1;
                   8317:                     last;
                   8318:                 }
                   8319:             }
                   8320:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8321:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8322:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8323:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8324:                             push(@blockers,$block);
                   8325:                         }
                   8326:                     }
                   8327:                 }
1.1162    raeburn  8328:             }
1.1282    raeburn  8329:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8330:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8331:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8332:                         push(@blockers,$block);
                   8333:                     }
                   8334:                 }
1.1162    raeburn  8335:             }
                   8336:         }
                   8337:     }
1.1282    raeburn  8338:     return if ($noblock);
                   8339:     return @blockers;
                   8340: }
1.1162    raeburn  8341: }
                   8342: 
1.1282    raeburn  8343: # -------------------------------- Deversion and split uri into path an filename   
                   8344: 
1.1133    foxr     8345: #
1.1282    raeburn  8346: #   Removes the version from a URI and
1.1133    foxr     8347: #   splits it in to its filename and path to the filename.
                   8348: #   Seems like File::Basename could have done this more clearly.
                   8349: #   Parameters:
                   8350: #      $uri   - input URI
                   8351: #   Returns:
                   8352: #     Two element list consisting of 
                   8353: #     $pathname  - the URI up to and excluding the trailing /
                   8354: #     $filename  - The part of the URI following the last /
                   8355: #  NOTE:
                   8356: #    Another realization of this is simply:
                   8357: #    use File::Basename;
                   8358: #    ...
                   8359: #    $uri = shift;
                   8360: #    $filename = basename($uri);
                   8361: #    $path     = dirname($uri);
                   8362: #    return ($filename, $path);
                   8363: #
                   8364: #     The implementation below is probably faster however.
                   8365: #
1.710     albertel 8366: sub split_uri_for_cond {
                   8367:     my $uri=&deversion(&declutter(shift));
                   8368:     my @uriparts=split(/\//,$uri);
                   8369:     my $filename=pop(@uriparts);
                   8370:     my $pathname=join('/',@uriparts);
                   8371:     return ($pathname,$filename);
                   8372: }
1.232     www      8373: # --------------------------------------------------- Is a resource on the map?
                   8374: 
                   8375: sub is_on_map {
1.710     albertel 8376:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8377:     #Trying to find the conditional for the file
1.620     albertel 8378:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8379: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8380:     if ($match) {
1.289     bowersj2 8381: 	return (1,$1);
                   8382:     } else {
1.434     www      8383: 	return (0,0);
1.289     bowersj2 8384:     }
1.12      www      8385: }
                   8386: 
1.427     www      8387: # --------------------------------------------------------- Get symb from alias
                   8388: 
                   8389: sub get_symb_from_alias {
                   8390:     my $symb=shift;
                   8391:     my ($map,$resid,$url)=&decode_symb($symb);
                   8392: # Already is a symb
                   8393:     if ($url) { return $symb; }
                   8394: # Must be an alias
                   8395:     my $aliassymb='';
                   8396:     my %bighash;
1.620     albertel 8397:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8398:                             &GDBM_READER(),0640)) {
                   8399:         my $rid=$bighash{'mapalias_'.$symb};
                   8400: 	if ($rid) {
                   8401: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8402: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8403: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8404: 	}
                   8405:         untie %bighash;
                   8406:     }
                   8407:     return $aliassymb;
                   8408: }
                   8409: 
1.12      www      8410: # ----------------------------------------------------------------- Define Role
                   8411: 
                   8412: sub definerole {
                   8413:   if (allowed('mcr','/')) {
1.1326    raeburn  8414:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8415:     foreach my $role (split(':',$sysrole)) {
                   8416: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8417:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8418:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8419: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8420:                return "refused:s:$crole&$cqual"; 
                   8421:             }
                   8422:         }
1.191     harris41 8423:     }
1.800     albertel 8424:     foreach my $role (split(':',$domrole)) {
                   8425: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8426:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8427:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8428: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8429:                return "refused:d:$crole&$cqual"; 
                   8430:             }
                   8431:         }
1.191     harris41 8432:     }
1.800     albertel 8433:     foreach my $role (split(':',$courole)) {
                   8434: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8435:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8436:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8437: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8438:                return "refused:c:$crole&$cqual"; 
                   8439:             }
                   8440:         }
1.191     harris41 8441:     }
1.1326    raeburn  8442:     my $uhome;
                   8443:     if (($uname ne '') && ($udom ne '')) {
                   8444:         $uhome = &homeserver($uname,$udom);
                   8445:         return $uhome if ($uhome eq 'no_host');
                   8446:     } else {
                   8447:         $uname = $env{'user.name'};
                   8448:         $udom = $env{'user.domain'};
                   8449:         $uhome = $env{'user.home'};
                   8450:     }
1.620     albertel 8451:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8452:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8453:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8454:     return reply($command,$uhome);
1.12      www      8455:   } else {
                   8456:     return 'refused';
                   8457:   }
1.105     harris41 8458: }
                   8459: 
                   8460: # ---------------- Make a metadata query against the network of library servers
                   8461: 
                   8462: sub metadata_query {
1.1237    raeburn  8463:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8464:     my %rhash;
1.845     albertel 8465:     my %libserv = &all_library();
1.244     matthew  8466:     my @server_list = (defined($server_array) ? @$server_array
                   8467:                                               : keys(%libserv) );
                   8468:     for my $server (@server_list) {
1.1237    raeburn  8469:         my $domains = ''; 
                   8470:         if (ref($domains_hash) eq 'HASH') {
                   8471:             $domains = $domains_hash->{$server}; 
                   8472:         }
1.118     harris41 8473: 	unless ($custom or $customshow) {
1.1237    raeburn  8474: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8475: 	    $rhash{$server}=$reply;
                   8476: 	}
                   8477: 	else {
                   8478: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8479: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8480: 			     $server);
                   8481: 	    $rhash{$server}=$reply;
                   8482: 	}
1.112     harris41 8483:     }
1.118     harris41 8484:     return \%rhash;
1.240     www      8485: }
                   8486: 
                   8487: # ----------------------------------------- Send log queries and wait for reply
                   8488: 
                   8489: sub log_query {
                   8490:     my ($uname,$udom,$query,%filters)=@_;
                   8491:     my $uhome=&homeserver($uname,$udom);
                   8492:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8493:     my $uhost=&hostname($uhome);
1.800     albertel 8494:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8495:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8496:                        $uhome);
1.479     albertel 8497:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8498:     return get_query_reply($queryid);
                   8499: }
                   8500: 
1.818     raeburn  8501: # -------------------------- Update MySQL table for portfolio file
                   8502: 
                   8503: sub update_portfolio_table {
1.821     raeburn  8504:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8505:     if ($group ne '') {
                   8506:         $file_name =~s /^\Q$group\E//;
                   8507:     }
1.818     raeburn  8508:     my $homeserver = &homeserver($uname,$udom);
                   8509:     my $queryid=
1.821     raeburn  8510:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8511:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8512:     my $reply = &get_query_reply($queryid);
                   8513:     return $reply;
                   8514: }
                   8515: 
1.899     raeburn  8516: # -------------------------- Update MySQL allusers table
                   8517: 
                   8518: sub update_allusers_table {
                   8519:     my ($uname,$udom,$names) = @_;
                   8520:     my $homeserver = &homeserver($uname,$udom);
                   8521:     my $queryid=
                   8522:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8523:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8524:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8525:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8526:                'generation='.&escape($names->{'generation'}).'%%'.
                   8527:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8528:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8529:     return;
1.899     raeburn  8530: }
                   8531: 
1.508     raeburn  8532: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8533: 
                   8534: sub fetch_enrollment_query {
1.511     raeburn  8535:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8536:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8537:     my $maxtries = 1;
1.508     raeburn  8538:     if ($context eq 'automated') {
                   8539:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8540:         $sleep = 2;
                   8541:         $loopmax = 100;
1.547     raeburn  8542:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8543:     } else {
                   8544:         $homeserver = &homeserver($cnum,$dom);
                   8545:     }
1.838     albertel 8546:     my $host=&hostname($homeserver);
1.506     raeburn  8547:     my $cmd = '';
1.1000    raeburn  8548:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8549:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8550:     }
                   8551:     $cmd =~ s/%%$//;
                   8552:     $cmd = &escape($cmd);
                   8553:     my $query = 'fetchenrollment';
1.620     albertel 8554:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8555:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8556:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8557:         return 'error: '.$queryid;
                   8558:     }
1.1317    raeburn  8559:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8560:     my $tries = 1;
                   8561:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8562:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8563:         $tries ++;
                   8564:     }
1.526     raeburn  8565:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8566:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8567:     } else {
1.901     albertel 8568:         my @responses = split(/:/,$reply);
1.1322    raeburn  8569:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8570:             foreach my $line (@responses) {
                   8571:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8572:                 $$replyref{$key} = $value;
                   8573:             }
                   8574:         } else {
1.1117    foxr     8575:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8576:             foreach my $line (@responses) {
                   8577:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8578:                 $$replyref{$key} = $value;
                   8579:                 if ($value > 0) {
1.800     albertel 8580:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8581:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8582:                         my $destname = $pathname.'/'.$filename;
                   8583:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8584:                         if ($xml_classlist =~ /^error/) {
                   8585:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8586:                         } else {
1.1359    raeburn  8587:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8588:                                 print FILE &unescape($xml_classlist);
                   8589:                                 close(FILE);
1.526     raeburn  8590:                             } else {
                   8591:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8592:                             }
                   8593:                         }
                   8594:                     }
                   8595:                 }
                   8596:             }
                   8597:         }
                   8598:         return 'ok';
                   8599:     }
                   8600:     return 'error';
                   8601: }
                   8602: 
1.242     www      8603: sub get_query_reply {
1.1317    raeburn  8604:     my ($queryid,$sleep,$loopmax) = @_;;
                   8605:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8606:         $sleep = 0.2;
                   8607:     }
                   8608:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8609:         $loopmax = 100;
                   8610:     }
1.1117    foxr     8611:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8612:     my $reply='';
1.1317    raeburn  8613:     for (1..$loopmax) {
                   8614: 	sleep($sleep);
1.240     www      8615:         if (-e $replyfile.'.end') {
1.1359    raeburn  8616: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8617: 		$reply = join('',<$fh>);
                   8618: 		close($fh);
1.240     www      8619: 	   } else { return 'error: reply_file_error'; }
1.242     www      8620:            return &unescape($reply);
                   8621: 	}
1.240     www      8622:     }
1.242     www      8623:     return 'timeout:'.$queryid;
1.240     www      8624: }
                   8625: 
                   8626: sub courselog_query {
1.241     www      8627: #
                   8628: # possible filters:
                   8629: # url: url or symb
                   8630: # username
                   8631: # domain
                   8632: # action: view, submit, grade
                   8633: # start: timestamp
                   8634: # end: timestamp
                   8635: #
1.240     www      8636:     my (%filters)=@_;
1.620     albertel 8637:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8638:     if ($filters{'url'}) {
                   8639: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8640:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8641:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8642:     }
1.620     albertel 8643:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8644:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8645:     return &log_query($cname,$cdom,'courselog',%filters);
                   8646: }
                   8647: 
                   8648: sub userlog_query {
1.858     raeburn  8649: #
                   8650: # possible filters:
                   8651: # action: log check role
                   8652: # start: timestamp
                   8653: # end: timestamp
                   8654: #
1.240     www      8655:     my ($uname,$udom,%filters)=@_;
                   8656:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8657: }
                   8658: 
1.506     raeburn  8659: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8660: 
                   8661: sub auto_run {
1.508     raeburn  8662:     my ($cnum,$cdom) = @_;
1.876     raeburn  8663:     my $response = 0;
                   8664:     my $settings;
                   8665:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8666:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8667:         $settings = $domconfig{'autoenroll'};
                   8668:         if ($settings->{'run'} eq '1') {
                   8669:             $response = 1;
                   8670:         }
                   8671:     } else {
1.934     raeburn  8672:         my $homeserver;
                   8673:         if (&is_course($cdom,$cnum)) {
                   8674:             $homeserver = &homeserver($cnum,$cdom);
                   8675:         } else {
                   8676:             $homeserver = &domain($cdom,'primary');
                   8677:         }
                   8678:         if ($homeserver ne 'no_host') {
                   8679:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8680:         }
1.876     raeburn  8681:     }
1.506     raeburn  8682:     return $response;
                   8683: }
1.776     albertel 8684: 
1.506     raeburn  8685: sub auto_get_sections {
1.508     raeburn  8686:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8687:     my $homeserver;
                   8688:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8689:         $homeserver = &homeserver($cnum,$cdom);
                   8690:     }
                   8691:     if (!defined($homeserver)) { 
                   8692:         if ($cdom =~ /^$match_domain$/) {
                   8693:             $homeserver = &domain($cdom,'primary');
                   8694:         }
                   8695:     }
                   8696:     my @secs;
                   8697:     if (defined($homeserver)) {
                   8698:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8699:         unless ($response eq 'refused') {
                   8700:             @secs = split(/:/,$response);
                   8701:         }
1.506     raeburn  8702:     }
                   8703:     return @secs;
                   8704: }
1.776     albertel 8705: 
1.506     raeburn  8706: sub auto_new_course {
1.1099    raeburn  8707:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8708:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8709:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8710:     return $response;
                   8711: }
1.776     albertel 8712: 
1.506     raeburn  8713: sub auto_validate_courseID {
1.508     raeburn  8714:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8715:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8716:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8717:     return $response;
                   8718: }
1.776     albertel 8719: 
1.1007    raeburn  8720: sub auto_validate_instcode {
1.1020    raeburn  8721:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8722:     my ($homeserver,$response);
                   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:     }
1.1065    raeburn  8731:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8732:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8733:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8734:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8735: }
                   8736: 
1.506     raeburn  8737: sub auto_create_password {
1.873     raeburn  8738:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8739:     my ($homeserver,$response);
1.506     raeburn  8740:     my $create_passwd = 0;
                   8741:     my $authchk = '';
1.873     raeburn  8742:     if ($udom =~ /^$match_domain$/) {
                   8743:         $homeserver = &domain($udom,'primary');
                   8744:     }
                   8745:     if ($homeserver eq '') {
                   8746:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8747:             $homeserver = &homeserver($cnum,$cdom);
                   8748:         }
                   8749:     }
                   8750:     if ($homeserver eq '') {
                   8751:         $authchk = 'nodomain';
1.506     raeburn  8752:     } else {
1.873     raeburn  8753:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8754:         if ($response eq 'refused') {
                   8755:             $authchk = 'refused';
                   8756:         } else {
1.901     albertel 8757:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8758:         }
1.506     raeburn  8759:     }
                   8760:     return ($authparam,$create_passwd,$authchk);
                   8761: }
                   8762: 
1.706     raeburn  8763: sub auto_photo_permission {
                   8764:     my ($cnum,$cdom,$students) = @_;
                   8765:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8766:     my ($outcome,$perm_reqd,$conditions) = 
                   8767: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8768:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8769: 	return (undef,undef);
                   8770:     }
1.706     raeburn  8771:     return ($outcome,$perm_reqd,$conditions);
                   8772: }
                   8773: 
                   8774: sub auto_checkphotos {
                   8775:     my ($uname,$udom,$pid) = @_;
                   8776:     my $homeserver = &homeserver($uname,$udom);
                   8777:     my ($result,$resulttype);
                   8778:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8779: 				   &escape($uname).':'.&escape($pid),
                   8780: 				   $homeserver));
1.709     albertel 8781:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8782: 	return (undef,undef);
                   8783:     }
1.706     raeburn  8784:     if ($outcome) {
                   8785:         ($result,$resulttype) = split(/:/,$outcome);
                   8786:     } 
                   8787:     return ($result,$resulttype);
                   8788: }
                   8789: 
                   8790: sub auto_photochoice {
                   8791:     my ($cnum,$cdom) = @_;
                   8792:     my $homeserver = &homeserver($cnum,$cdom);
                   8793:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8794: 						       &escape($cdom),
                   8795: 						       $homeserver)));
1.709     albertel 8796:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8797: 	return (undef,undef);
                   8798:     }
1.706     raeburn  8799:     return ($update,$comment);
                   8800: }
                   8801: 
                   8802: sub auto_photoupdate {
                   8803:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8804:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8805:     my $host=&hostname($homeserver);
1.706     raeburn  8806:     my $cmd = '';
                   8807:     my $maxtries = 1;
1.800     albertel 8808:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8809:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8810:     }
                   8811:     $cmd =~ s/%%$//;
                   8812:     $cmd = &escape($cmd);
                   8813:     my $query = 'institutionalphotos';
                   8814:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8815:     unless ($queryid=~/^\Q$host\E\_/) {
                   8816:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8817:         return 'error: '.$queryid;
                   8818:     }
                   8819:     my $reply = &get_query_reply($queryid);
                   8820:     my $tries = 1;
                   8821:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8822:         $reply = &get_query_reply($queryid);
                   8823:         $tries ++;
                   8824:     }
                   8825:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8826:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8827:     } else {
                   8828:         my @responses = split(/:/,$reply);
                   8829:         my $outcome = shift(@responses); 
                   8830:         foreach my $item (@responses) {
                   8831:             my ($key,$value) = split(/=/,$item);
                   8832:             $$photo{$key} = $value;
                   8833:         }
                   8834:         return $outcome;
                   8835:     }
                   8836:     return 'error';
                   8837: }
                   8838: 
1.521     raeburn  8839: sub auto_instcode_format {
1.793     albertel 8840:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8841: 	$cat_order) = @_;
1.521     raeburn  8842:     my $courses = '';
1.772     raeburn  8843:     my @homeservers;
1.521     raeburn  8844:     if ($caller eq 'global') {
1.841     albertel 8845: 	my %servers = &get_servers($codedom,'library');
                   8846: 	foreach my $tryserver (keys(%servers)) {
                   8847: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8848: 		push(@homeservers,$tryserver);
                   8849: 	    }
1.584     raeburn  8850:         }
1.1022    raeburn  8851:     } elsif ($caller eq 'requests') {
                   8852:         if ($codedom =~ /^$match_domain$/) {
                   8853:             my $chome = &domain($codedom,'primary');
                   8854:             unless ($chome eq 'no_host') {
                   8855:                 push(@homeservers,$chome);
                   8856:             }
                   8857:         }
1.521     raeburn  8858:     } else {
1.772     raeburn  8859:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8860:     }
1.793     albertel 8861:     foreach my $code (keys(%{$instcodes})) {
                   8862:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8863:     }
                   8864:     chop($courses);
1.772     raeburn  8865:     my $ok_response = 0;
                   8866:     my $response;
                   8867:     while (@homeservers > 0 && $ok_response == 0) {
                   8868:         my $server = shift(@homeservers); 
                   8869:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8870:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8871:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8872: 		split(/:/,$response);
1.772     raeburn  8873:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8874:             push(@{$codetitles},&str2array($codetitles_str));
                   8875:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8876:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8877:             $ok_response = 1;
                   8878:         }
                   8879:     }
                   8880:     if ($ok_response) {
1.521     raeburn  8881:         return 'ok';
1.772     raeburn  8882:     } else {
                   8883:         return $response;
1.521     raeburn  8884:     }
                   8885: }
                   8886: 
1.792     raeburn  8887: sub auto_instcode_defaults {
                   8888:     my ($domain,$returnhash,$code_order) = @_;
                   8889:     my @homeservers;
1.841     albertel 8890: 
                   8891:     my %servers = &get_servers($domain,'library');
                   8892:     foreach my $tryserver (keys(%servers)) {
                   8893: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8894: 	    push(@homeservers,$tryserver);
                   8895: 	}
1.792     raeburn  8896:     }
1.841     albertel 8897: 
1.792     raeburn  8898:     my $response;
1.841     albertel 8899:     foreach my $server (@homeservers) {
1.792     raeburn  8900:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8901:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8902: 	
                   8903: 	foreach my $pair (split(/\&/,$response)) {
                   8904: 	    my ($name,$value)=split(/\=/,$pair);
                   8905: 	    if ($name eq 'code_order') {
                   8906: 		@{$code_order} = split(/\&/,&unescape($value));
                   8907: 	    } else {
                   8908: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8909: 	    }
                   8910: 	}
                   8911: 	return 'ok';
1.792     raeburn  8912:     }
1.841     albertel 8913: 
                   8914:     return $response;
1.1003    raeburn  8915: }
                   8916: 
                   8917: sub auto_possible_instcodes {
1.1007    raeburn  8918:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8919:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8920:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8921:         return;
                   8922:     }
1.1003    raeburn  8923:     my (@homeservers,$uhome);
                   8924:     if (defined(&domain($domain,'primary'))) {
                   8925:         $uhome=&domain($domain,'primary');
                   8926:         push(@homeservers,&domain($domain,'primary'));
                   8927:     } else {
                   8928:         my %servers = &get_servers($domain,'library');
                   8929:         foreach my $tryserver (keys(%servers)) {
                   8930:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8931:                 push(@homeservers,$tryserver);
                   8932:             }
                   8933:         }
                   8934:     }
                   8935:     my $response;
                   8936:     foreach my $server (@homeservers) {
                   8937:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8938:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8939:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8940:             split(':',$response);
                   8941:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8942:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8943:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8944:             my ($name,$value)=split('=',$item);
                   8945:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8946:         }
                   8947:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8948:             my ($name,$value)=split('=',$item);
                   8949:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8950:         }
                   8951:         return 'ok';
                   8952:     }
                   8953:     return $response;
                   8954: }
1.792     raeburn  8955: 
1.1010    raeburn  8956: sub auto_courserequest_checks {
                   8957:     my ($dom) = @_;
1.1020    raeburn  8958:     my ($homeserver,%validations);
                   8959:     if ($dom =~ /^$match_domain$/) {
                   8960:         $homeserver = &domain($dom,'primary');
                   8961:     }
                   8962:     unless ($homeserver eq 'no_host') {
                   8963:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8964:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8965:             my @items = split(/&/,$response);
                   8966:             foreach my $item (@items) {
                   8967:                 my ($key,$value) = split('=',$item);
                   8968:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8969:             }
                   8970:         }
                   8971:     }
1.1010    raeburn  8972:     return %validations; 
                   8973: }
                   8974: 
1.1020    raeburn  8975: sub auto_courserequest_validation {
1.1255    raeburn  8976:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8977:     my ($homeserver,$response);
                   8978:     if ($dom =~ /^$match_domain$/) {
                   8979:         $homeserver = &domain($dom,'primary');
                   8980:     }
1.1255    raeburn  8981:     unless ($homeserver eq 'no_host') {
                   8982:         my $customdata;
                   8983:         if (ref($custominfo) eq 'HASH') {
                   8984:             $customdata = &freeze_escape($custominfo);
                   8985:         }
1.1020    raeburn  8986:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8987:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8988:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8989:                                     $customdata,$homeserver));
1.1020    raeburn  8990:     }
                   8991:     return $response;
                   8992: }
                   8993: 
1.777     albertel 8994: sub auto_validate_class_sec {
1.918     raeburn  8995:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8996:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8997:     my $ownerlist;
                   8998:     if (ref($owners) eq 'ARRAY') {
                   8999:         $ownerlist = join(',',@{$owners});
                   9000:     } else {
                   9001:         $ownerlist = $owners;
                   9002:     }
1.773     raeburn  9003:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9004:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9005:     return $response;
                   9006: }
                   9007: 
1.1367    raeburn  9008: sub auto_validate_instclasses {
                   9009:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9010:     my ($homeserver,%validations);
                   9011:     $homeserver = &homeserver($cnum,$cdom);
                   9012:     unless ($homeserver eq 'no_host') {
                   9013:         my $ownerlist;
                   9014:         if (ref($owners) eq 'ARRAY') {
                   9015:             $ownerlist = join(',',@{$owners});
                   9016:         } else {
                   9017:             $ownerlist = $owners;
                   9018:         }
                   9019:         if (ref($classesref) eq 'HASH') {
                   9020:             my $classes = &freeze_escape($classesref);
                   9021:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9022:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9023:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9024:                 my @items = split(/&/,$response);
                   9025:                 foreach my $item (@items) {
                   9026:                     my ($key,$value) = split('=',$item);
                   9027:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9028:                 }
                   9029:             }
                   9030:         }
                   9031:     }
                   9032:     return %validations;
                   9033: }
                   9034: 
1.1248    raeburn  9035: sub auto_crsreq_update {
                   9036:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9037:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9038:     my ($homeserver,%crsreqresponse);
                   9039:     if ($cdom =~ /^$match_domain$/) {
                   9040:         $homeserver = &domain($cdom,'primary');
                   9041:     }
                   9042:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9043:         my $info;
                   9044:         if (ref($inbound) eq 'HASH') {
                   9045:             $info = &freeze_escape($inbound);
                   9046:         }
                   9047:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9048:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9049:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9050:                             &escape($title).':'.&escape($code).':'.
                   9051:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9052:                             $homeserver);
1.1248    raeburn  9053:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9054:             my @items = split(/&/,$response);
                   9055:             foreach my $item (@items) {
                   9056:                 my ($key,$value) = split('=',$item);
                   9057:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9058:             }
                   9059:         }
                   9060:     }
                   9061:     return \%crsreqresponse;
                   9062: }
                   9063: 
1.1305    raeburn  9064: sub auto_export_grades {
1.1309    raeburn  9065:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9066:     my ($homeserver,%exportresponse);
                   9067:     if ($cdom =~ /^$match_domain$/) {
                   9068:         $homeserver = &domain($cdom,'primary');
                   9069:     }
                   9070:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9071:         my $info;
                   9072:         if (ref($inforef) eq 'HASH') {
                   9073:             $info = &freeze_escape($inforef);
                   9074:         }
                   9075:         if (ref($gradesref) eq 'HASH') {
                   9076:             my $grades = &freeze_escape($gradesref);
                   9077:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9078:                                 $info.':'.$grades,$homeserver);
                   9079:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9080:                 my @items = split(/&/,$response);
                   9081:                 foreach my $item (@items) {
                   9082:                     my ($key,$value) = split('=',$item);
                   9083:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9084:                 }
                   9085:             }
                   9086:         }
                   9087:     }
                   9088:     return \%exportresponse;
1.1305    raeburn  9089: }
                   9090: 
1.1287    raeburn  9091: sub check_instcode_cloning {
                   9092:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9093:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9094:         return;
                   9095:     }
                   9096:     my $canclone;
                   9097:     if (@{$code_order} > 0) {
                   9098:         my $instcoderegexp ='^';
                   9099:         my @clonecodes = split(/\&/,$cloner);
                   9100:         foreach my $item (@{$code_order}) {
                   9101:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9102:                 foreach my $pair (@clonecodes) {
                   9103:                     my ($key,$val) = split(/\=/,$pair,2);
                   9104:                     $val = &unescape($val);
                   9105:                     if ($key eq $item) {
                   9106:                         $instcoderegexp .= '('.$val.')';
                   9107:                         last;
                   9108:                     }
                   9109:                 }
                   9110:             } else {
                   9111:                 $instcoderegexp .= $codedefaults->{$item};
                   9112:             }
                   9113:         }
                   9114:         $instcoderegexp .= '$';
                   9115:         my (@from,@to);
                   9116:         eval {
                   9117:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9118:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9119:         };
                   9120:         if ((@from > 0) && (@to > 0)) {
                   9121:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9122:             if (!@diffs) {
                   9123:                 $canclone = 1;
                   9124:             }
                   9125:         }
                   9126:     }
                   9127:     return $canclone;
                   9128: }
                   9129: 
                   9130: sub default_instcode_cloning {
                   9131:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9132:     my (%codedefaults,@code_order,$canclone);
                   9133:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9134:         %codedefaults = %{$codedefaultsref};
                   9135:         @code_order = @{$codeorderref};
                   9136:     } elsif ($clonedom) {
                   9137:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9138:     }
                   9139:     if (($domdefclone) && (@code_order)) {
                   9140:         my @clonecodes = split(/\+/,$domdefclone);
                   9141:         my $instcoderegexp ='^';
                   9142:         foreach my $item (@code_order) {
                   9143:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9144:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   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: 
1.679     raeburn  9165: # ------------------------------------------------------- Course Group routines
                   9166: 
                   9167: sub get_coursegroups {
1.809     raeburn  9168:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9169:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9170: }
                   9171: 
1.679     raeburn  9172: sub modify_coursegroup {
                   9173:     my ($cdom,$cnum,$groupsettings) = @_;
                   9174:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9175: }
                   9176: 
1.809     raeburn  9177: sub toggle_coursegroup_status {
                   9178:     my ($cdom,$cnum,$group,$action) = @_;
                   9179:     my ($from_namespace,$to_namespace);
                   9180:     if ($action eq 'delete') {
                   9181:         $from_namespace = 'coursegroups';
                   9182:         $to_namespace = 'deleted_groups';
                   9183:     } else {
                   9184:         $from_namespace = 'deleted_groups';
                   9185:         $to_namespace = 'coursegroups';
                   9186:     }
                   9187:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9188:     if (my $tmp = &error(%curr_group)) {
                   9189:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9190:         return ('read error',$tmp);
                   9191:     } else {
                   9192:         my %savedsettings = %curr_group; 
1.809     raeburn  9193:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9194:         my $deloutcome;
                   9195:         if ($result eq 'ok') {
1.809     raeburn  9196:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9197:         } else {
                   9198:             return ('write error',$result);
                   9199:         }
                   9200:         if ($deloutcome eq 'ok') {
                   9201:             return 'ok';
                   9202:         } else {
                   9203:             return ('delete error',$deloutcome);
                   9204:         }
                   9205:     }
                   9206: }
                   9207: 
1.679     raeburn  9208: sub modify_group_roles {
1.957     raeburn  9209:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9210:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9211:     my $role = 'gr/'.&escape($userprivs);
                   9212:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9213:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9214:     if ($result eq 'ok') {
                   9215:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9216:     }
1.679     raeburn  9217:     return $result;
                   9218: }
                   9219: 
                   9220: sub modify_coursegroup_membership {
                   9221:     my ($cdom,$cnum,$membership) = @_;
                   9222:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9223:     return $result;
                   9224: }
                   9225: 
1.682     raeburn  9226: sub get_active_groups {
                   9227:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9228:     my $now = time;
                   9229:     my %groups = ();
                   9230:     foreach my $key (keys(%env)) {
1.811     albertel 9231:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9232:             my ($start,$end) = split(/\./,$env{$key});
                   9233:             if (($end!=0) && ($end<$now)) { next; }
                   9234:             if (($start!=0) && ($start>$now)) { next; }
                   9235:             if ($1 eq $cdom && $2 eq $cnum) {
                   9236:                 $groups{$3} = $env{$key} ;
                   9237:             }
                   9238:         }
                   9239:     }
                   9240:     return %groups;
                   9241: }
                   9242: 
1.683     raeburn  9243: sub get_group_membership {
                   9244:     my ($cdom,$cnum,$group) = @_;
                   9245:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9246: }
                   9247: 
                   9248: sub get_users_groups {
                   9249:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9250:     my @usersgroups;
1.683     raeburn  9251:     my $cachetime=1800;
                   9252: 
                   9253:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9254:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9255:     if (defined($cached)) {
1.734     albertel 9256:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9257:     } else {  
                   9258:         $grouplist = '';
1.816     raeburn  9259:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9260:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9261:         my $access_end = $env{'course.'.$courseid.
                   9262:                               '.default_enrollment_end_date'};
                   9263:         my $now = time;
                   9264:         foreach my $key (keys(%roleshash)) {
                   9265:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9266:                 my $group = $1;
                   9267:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9268:                     my $start = $2;
                   9269:                     my $end = $1;
                   9270:                     if ($start == -1) { next; } # deleted from group
                   9271:                     if (($start!=0) && ($start>$now)) { next; }
                   9272:                     if (($end!=0) && ($end<$now)) {
                   9273:                         if ($access_end && $access_end < $now) {
                   9274:                             if ($access_end - $end < 86400) {
                   9275:                                 push(@usersgroups,$group);
1.733     raeburn  9276:                             }
                   9277:                         }
1.817     raeburn  9278:                         next;
1.733     raeburn  9279:                     }
1.817     raeburn  9280:                     push(@usersgroups,$group);
1.683     raeburn  9281:                 }
                   9282:             }
                   9283:         }
1.817     raeburn  9284:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9285:         $grouplist = join(':',@usersgroups);
                   9286:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9287:     }
1.733     raeburn  9288:     return @usersgroups;
1.683     raeburn  9289: }
                   9290: 
                   9291: sub devalidate_getgroups_cache {
                   9292:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9293:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9294: 
1.683     raeburn  9295:     my $hashid="$udom:$uname:$courseid";
                   9296:     &devalidate_cache_new('getgroups',$hashid);
                   9297: }
                   9298: 
1.12      www      9299: # ------------------------------------------------------------------ Plain Text
                   9300: 
                   9301: sub plaintext {
1.988     raeburn  9302:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9303:     if ($short =~ m{^cr/}) {
1.758     albertel 9304: 	return (split('/',$short))[-1];
                   9305:     }
1.742     raeburn  9306:     if (!defined($cid)) {
                   9307:         $cid = $env{'request.course.id'};
                   9308:     }
                   9309:     my %rolenames = (
1.1008    raeburn  9310:                       Course    => 'std',
                   9311:                       Community => 'alt1',
1.1305    raeburn  9312:                       Placement => 'std',
1.742     raeburn  9313:                     );
1.1037    raeburn  9314:     if ($cid ne '') {
                   9315:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9316:             unless ($forcedefault) {
                   9317:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9318:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9319:                 return &Apache::lonlocal::mt($roletext);
                   9320:             }
                   9321:         }
                   9322:     }
                   9323:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9324:         (defined($rolenames{$type})) && 
                   9325:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9326:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9327:     } elsif ($cid ne '') {
                   9328:         my $crstype = $env{'course.'.$cid.'.type'};
                   9329:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9330:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9331:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9332:         }
1.742     raeburn  9333:     }
1.1037    raeburn  9334:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9335: }
                   9336: 
                   9337: # ----------------------------------------------------------------- Assign Role
                   9338: 
                   9339: sub assignrole {
1.957     raeburn  9340:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9341:         $context)=@_;
1.21      www      9342:     my $mrole;
                   9343:     if ($role =~ /^cr\//) {
1.393     www      9344:         my $cwosec=$url;
1.811     albertel 9345:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9346: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9347:            my $refused = 1;
                   9348:            if ($context eq 'requestcourses') {
                   9349:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9350:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9351:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9352:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9353:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9354:                            if ($crsenv{'internal.courseowner'} eq
                   9355:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9356:                                $refused = '';
                   9357:                            }
                   9358:                        }
                   9359:                    }
                   9360:                }
                   9361:            }
                   9362:            if ($refused) {
                   9363:                &logthis('Refused custom assignrole: '.
                   9364:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9365:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9366:                return 'refused';
                   9367:            }
1.104     www      9368:         }
1.21      www      9369:         $mrole='cr';
1.678     raeburn  9370:     } elsif ($role =~ /^gr\//) {
                   9371:         my $cwogrp=$url;
1.811     albertel 9372:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9373:         unless (&allowed('mdg',$cwogrp)) {
                   9374:             &logthis('Refused group assignrole: '.
                   9375:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9376:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9377:             return 'refused';
                   9378:         }
                   9379:         $mrole='gr';
1.21      www      9380:     } else {
1.82      www      9381:         my $cwosec=$url;
1.811     albertel 9382:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9383:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9384:             my $refused;
                   9385:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9386:                 if (!(&allowed('c'.$role,$url))) {
                   9387:                     $refused = 1;
                   9388:                 }
                   9389:             } else {
                   9390:                 $refused = 1;
                   9391:             }
1.947     raeburn  9392:             if ($refused) {
1.1045    raeburn  9393:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9394:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9395:                     my %crsenv;
                   9396:                     if ($role eq 'cc' || $role eq 'co') {
                   9397:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9398:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9399:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9400:                                 if ($crsenv{'internal.courseowner'} eq 
                   9401:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9402:                                     $refused = '';
                   9403:                                 }
                   9404:                             }
                   9405:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9406:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9407:                                 if ($crsenv{'internal.courseowner'} eq 
                   9408:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9409:                                     $refused = '';
                   9410:                                 }
                   9411:                             }
                   9412:                         }
                   9413:                     }
1.1368    raeburn  9414:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9415:                     if ($role eq 'st') {
                   9416:                         $refused = '';
1.1377    raeburn  9417:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9418:                         $refused = '';
                   9419:                     }
1.1017    raeburn  9420:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9421:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9422:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9423:                         my $wrongcc;
                   9424:                         if ($cnum =~ /^$match_community$/) {
                   9425:                             $wrongcc = 1 if ($role eq 'cc');
                   9426:                         } else {
                   9427:                             $wrongcc = 1 if ($role eq 'co');
                   9428:                         }
                   9429:                         unless ($wrongcc) {
                   9430:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9431:                             if ($crsenv{'internal.courseowner'} eq 
                   9432:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9433:                                 $refused = '';
                   9434:                             }
1.1017    raeburn  9435:                         }
                   9436:                     }
1.1183    raeburn  9437:                 } elsif ($context eq 'requestauthor') {
                   9438:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9439:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9440:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9441:                             $refused = '';
                   9442:                         } else {
                   9443:                             my %domdefaults = &get_domain_defaults($udom);
                   9444:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9445:                                 my $checkbystatus;
                   9446:                                 if ($env{'user.adv'}) { 
                   9447:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9448:                                     if ($disposition eq 'automatic') {
                   9449:                                         $refused = '';
                   9450:                                     } elsif ($disposition eq '') {
                   9451:                                         $checkbystatus = 1;
                   9452:                                     } 
                   9453:                                 } else {
                   9454:                                     $checkbystatus = 1;
                   9455:                                 }
                   9456:                                 if ($checkbystatus) {
                   9457:                                     if ($env{'environment.inststatus'}) {
                   9458:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9459:                                         foreach my $type (@inststatuses) {
                   9460:                                             if (($type ne '') &&
                   9461:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9462:                                                 $refused = '';
                   9463:                                             }
                   9464:                                         }
                   9465:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9466:                                         $refused = '';
                   9467:                                     }
                   9468:                                 }
                   9469:                             }
                   9470:                         }
                   9471:                     }
1.1017    raeburn  9472:                 }
                   9473:                 if ($refused) {
1.947     raeburn  9474:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9475:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9476: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9477:                     return 'refused';
                   9478:                 }
1.932     raeburn  9479:             }
1.1131    raeburn  9480:         } elsif ($role eq 'au') {
                   9481:             if ($url ne '/'.$udom.'/') {
                   9482:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9483:                          ' to assign author role for '.$uname.':'.$udom.
                   9484:                          ' in domain: '.$url.' refused (wrong domain).');
                   9485:                 return 'refused';
                   9486:             }
1.104     www      9487:         }
1.21      www      9488:         $mrole=$role;
                   9489:     }
1.620     albertel 9490:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9491:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9492:     if ($end) { $command.='_'.$end; }
1.21      www      9493:     if ($start) {
                   9494: 	if ($end) { 
1.81      www      9495:            $command.='_'.$start; 
1.21      www      9496:         } else {
1.81      www      9497:            $command.='_0_'.$start;
1.21      www      9498:         }
                   9499:     }
1.739     raeburn  9500:     my $origstart = $start;
                   9501:     my $origend = $end;
1.957     raeburn  9502:     my $delflag;
1.357     www      9503: # actually delete
                   9504:     if ($deleteflag) {
1.373     www      9505: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9506: # modify command to delete the role
1.620     albertel 9507:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9508:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9509: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9510: # set start and finish to negative values for userrolelog
                   9511:            $start=-1;
                   9512:            $end=-1;
1.957     raeburn  9513:            $delflag = 1;
1.357     www      9514:         }
                   9515:     }
                   9516: # send command
1.349     www      9517:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9518: # log new user role if status is ok
1.349     www      9519:     if ($answer eq 'ok') {
1.663     raeburn  9520: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9521:         if (($role eq 'cc') || ($role eq 'in') ||
                   9522:             ($role eq 'ep') || ($role eq 'ad') ||
                   9523:             ($role eq 'ta') || ($role eq 'st') ||
                   9524:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9525:             ($role eq 'co')) {
1.1200    raeburn  9526: # for course roles, perform group memberships changes triggered by role change.
                   9527:             unless ($role =~ /^gr/) {
                   9528:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9529:                                                  $origstart,$selfenroll,$context);
                   9530:             }
1.1184    raeburn  9531:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9532:                            $selfenroll,$context);
                   9533:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9534:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9535:                  ($role eq 'da')) {
1.1184    raeburn  9536:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9537:                            $context);
                   9538:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9539:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9540:                              $context); 
                   9541:         }
1.1053    raeburn  9542:         if ($role eq 'cc') {
                   9543:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9544:         }
1.349     www      9545:     }
                   9546:     return $answer;
1.169     harris41 9547: }
                   9548: 
1.1053    raeburn  9549: sub autoupdate_coowners {
                   9550:     my ($url,$end,$start,$uname,$udom) = @_;
                   9551:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9552:     if (($cdom ne '') && ($cnum ne '')) {
                   9553:         my $now = time;
                   9554:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9555:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9556:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9557:             my $instcode = $coursehash{'internal.coursecode'};
                   9558:             if ($instcode ne '') {
1.1056    raeburn  9559:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9560:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9561:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9562:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9563:                         if ($result eq 'valid') {
                   9564:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9565:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9566:                                     push(@newcoowners,$coowner);
                   9567:                                 }
                   9568:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9569:                                     push(@newcoowners,$uname.':'.$udom);
                   9570:                                 }
                   9571:                                 @newcoowners = sort(@newcoowners);
                   9572:                             } else {
                   9573:                                 push(@newcoowners,$uname.':'.$udom);
                   9574:                             }
                   9575:                         } else {
                   9576:                             if ($coursehash{'internal.co-owners'}) {
                   9577:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9578:                                     unless ($coowner eq $uname.':'.$udom) {
                   9579:                                         push(@newcoowners,$coowner);
                   9580:                                     }
                   9581:                                 }
                   9582:                                 unless (@newcoowners > 0) {
                   9583:                                     $delcoowners = 1;
                   9584:                                     $coowners = '';
                   9585:                                 }
                   9586:                             }
                   9587:                         }
                   9588:                         if (@newcoowners || $delcoowners) {
                   9589:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9590:                                             $delcoowners,@newcoowners);
                   9591:                         }
                   9592:                     }
                   9593:                 }
                   9594:             }
                   9595:         }
                   9596:     }
                   9597: }
                   9598: 
                   9599: sub store_coowners {
                   9600:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9601:     my $cid = $cdom.'_'.$cnum;
                   9602:     my ($coowners,$delresult,$putresult);
                   9603:     if (@newcoowners) {
                   9604:         $coowners = join(',',@newcoowners);
                   9605:         my %coownershash = (
                   9606:                             'internal.co-owners' => $coowners,
                   9607:                            );
                   9608:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9609:         if ($putresult eq 'ok') {
                   9610:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9611:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9612:             }
                   9613:         }
                   9614:     }
                   9615:     if ($delcoowners) {
                   9616:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9617:         if ($delresult eq 'ok') {
                   9618:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9619:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9620:             }
                   9621:         }
                   9622:     }
                   9623:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9624:         my %crsinfo =
                   9625:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9626:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9627:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9628:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9629:         }
                   9630:     }
                   9631: }
                   9632: 
1.169     harris41 9633: # -------------------------------------------------- Modify user authentication
1.197     www      9634: # Overrides without validation
                   9635: 
1.169     harris41 9636: sub modifyuserauth {
                   9637:     my ($udom,$uname,$umode,$upass)=@_;
                   9638:     my $uhome=&homeserver($uname,$udom);
1.197     www      9639:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9640:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9641:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9642:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9643:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9644: 		     &escape($upass),$uhome);
1.620     albertel 9645:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9646:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9647:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9648:     &log($udom,,$uname,$uhome,
1.620     albertel 9649:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9650:                                      $env{'user.name'}.', '.$umode.
1.197     www      9651:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9652:     unless ($reply eq 'ok') {
1.197     www      9653:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9654: 	return 'error: '.$reply;
                   9655:     }   
1.170     harris41 9656:     return 'ok';
1.80      www      9657: }
                   9658: 
1.81      www      9659: # --------------------------------------------------------------- Modify a user
1.80      www      9660: 
1.81      www      9661: sub modifyuser {
1.206     matthew  9662:     my ($udom,    $uname, $uid,
                   9663:         $umode,   $upass, $first,
                   9664:         $middle,  $last,  $gene,
1.1058    raeburn  9665:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9666:     $udom= &LONCAPA::clean_domain($udom);
                   9667:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9668:     my $showcandelete = 'none';
                   9669:     if (ref($candelete) eq 'ARRAY') {
                   9670:         if (@{$candelete} > 0) {
                   9671:             $showcandelete = join(', ',@{$candelete});
                   9672:         }
                   9673:     }
1.81      www      9674:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9675:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9676: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9677:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9678:                                      ' desiredhome not specified'). 
1.620     albertel 9679:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9680:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9681:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9682:     my $newuser;
                   9683:     if ($uhome eq 'no_host') {
                   9684:         $newuser = 1;
1.1368    raeburn  9685:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9686:                 ($umode eq 'lti')) {
                   9687:             return 'error: more information needed to create new user';
                   9688:         }
1.1075    raeburn  9689:     }
1.80      www      9690: # ----------------------------------------------------------------- Create User
1.406     albertel 9691:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9692: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9693:         my $unhome='';
1.844     albertel 9694:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9695:             $unhome = $desiredhome;
1.620     albertel 9696: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9697: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9698:         } else { # load balancing routine for determining $unhome
1.81      www      9699:             my $loadm=10000000;
1.841     albertel 9700: 	    my %servers = &get_servers($udom,'library');
                   9701: 	    foreach my $tryserver (keys(%servers)) {
                   9702: 		my $answer=reply('load',$tryserver);
                   9703: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9704: 		    $loadm=$answer;
                   9705: 		    $unhome=$tryserver;
                   9706: 		}
1.80      www      9707: 	    }
                   9708:         }
                   9709:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9710: 	    return 'error: unable to find a home server for '.$uname.
                   9711:                    ' in domain '.$udom;
1.80      www      9712:         }
                   9713:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9714:                          &escape($upass),$unhome);
                   9715: 	unless ($reply eq 'ok') {
                   9716:             return 'error: '.$reply;
                   9717:         }   
1.230     stredwic 9718:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9719:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9720: 	    return 'error: unable verify users home machine.';
1.80      www      9721:         }
1.209     matthew  9722:     }   # End of creation of new user
1.80      www      9723: # ---------------------------------------------------------------------- Add ID
                   9724:     if ($uid) {
                   9725:        $uid=~tr/A-Z/a-z/;
                   9726:        my %uidhash=&idrget($udom,$uname);
1.196     www      9727:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9728:          && (!$forceid)) {
1.80      www      9729: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9730: 	      return 'error: user id "'.$uid.'" does not match '.
                   9731:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9732:           }
                   9733:        } else {
1.1300    raeburn  9734: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9735:        }
                   9736:     }
                   9737: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9738:     my @tmp=&get('environment',
1.899     raeburn  9739: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9740:                     'permanentemail','inststatus'],
1.134     albertel 9741: 		   $udom,$uname);
1.1075    raeburn  9742:     my (%names,%oldnames);
1.313     matthew  9743:     if ($tmp[0] =~ m/^error:.*/) { 
                   9744:         %names=(); 
                   9745:     } else {
                   9746:         %names = @tmp;
1.1075    raeburn  9747:         %oldnames = %names;
1.313     matthew  9748:     }
1.388     www      9749: #
1.1058    raeburn  9750: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9751: # of users did not contain them), do not overwrite existing values
                   9752: # unless field is in $candelete array ref.  
                   9753: #
                   9754: 
                   9755:     my @fields = ('firstname','middlename','lastname','generation',
                   9756:                   'permanentemail','id');
                   9757:     my %newvalues;
                   9758:     if (ref($candelete) eq 'ARRAY') {
                   9759:         foreach my $field (@fields) {
                   9760:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9761:                 if ($field eq 'firstname') {
                   9762:                     $names{$field} = $first;
                   9763:                 } elsif ($field eq 'middlename') {
                   9764:                     $names{$field} = $middle;
                   9765:                 } elsif ($field eq 'lastname') {
                   9766:                     $names{$field} = $last;
                   9767:                 } elsif ($field eq 'generation') { 
                   9768:                     $names{$field} = $gene;
                   9769:                 } elsif ($field eq 'permanentemail') {
                   9770:                     $names{$field} = $email;
                   9771:                 } elsif ($field eq 'id') {
                   9772:                     $names{$field}  = $uid;
                   9773:                 }
                   9774:             }
                   9775:         }
                   9776:     }
1.388     www      9777:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9778:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9779:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9780:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9781:     if ($email) {
                   9782:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9783:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9784:     }
1.899     raeburn  9785:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9786:     if (defined($inststatus)) {
                   9787:         $names{'inststatus'} = '';
                   9788:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9789:         if (ref($usertypes) eq 'HASH') {
                   9790:             my @okstatuses; 
                   9791:             foreach my $item (split(/:/,$inststatus)) {
                   9792:                 if (defined($usertypes->{$item})) {
                   9793:                     push(@okstatuses,$item);  
                   9794:                 }
                   9795:             }
                   9796:             if (@okstatuses) {
                   9797:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9798:             }
                   9799:         }
                   9800:     }
1.1075    raeburn  9801:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9802:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9803:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9804:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9805:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9806:     } else {
                   9807:         $logmsg .= ' during self creation';
                   9808:     }
1.1075    raeburn  9809:     my $changed;
                   9810:     if ($newuser) {
                   9811:         $changed = 1;
                   9812:     } else {
                   9813:         foreach my $field (@fields) {
                   9814:             if ($names{$field} ne $oldnames{$field}) {
                   9815:                 $changed = 1;
                   9816:                 last;
                   9817:             }
                   9818:         }
                   9819:     }
                   9820:     unless ($changed) {
                   9821:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9822:         &logthis($logmsg);
                   9823:         return 'ok';
                   9824:     }
                   9825:     my $reply = &put('environment', \%names, $udom,$uname);
                   9826:     if ($reply ne 'ok') { 
                   9827:         return 'error: '.$reply;
                   9828:     }
1.1087    raeburn  9829:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9830:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9831:     }
1.1075    raeburn  9832:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9833:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9834:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9835:     &logthis($logmsg);
1.134     albertel 9836:     return 'ok';
1.80      www      9837: }
                   9838: 
1.81      www      9839: # -------------------------------------------------------------- Modify student
1.80      www      9840: 
1.81      www      9841: sub modifystudent {
                   9842:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9843:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9844:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9845:     if (!$cid) {
1.620     albertel 9846: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9847: 	    return 'not_in_class';
                   9848: 	}
1.80      www      9849:     }
                   9850: # --------------------------------------------------------------- Make the user
1.81      www      9851:     my $reply=&modifyuser
1.209     matthew  9852: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9853:          $desiredhome,$email,$inststatus);
1.80      www      9854:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9855:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9856:     # student's environment
1.297     matthew  9857:     $uid = undef if (!$forceid);
1.455     albertel 9858:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9859:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9860:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9861:     return $reply;
                   9862: }
                   9863: 
                   9864: sub modify_student_enrollment {
1.1216    raeburn  9865:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9866:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9867:     my ($cdom,$cnum,$chome);
                   9868:     if (!$cid) {
1.620     albertel 9869: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9870: 	    return 'not_in_class';
                   9871: 	}
1.620     albertel 9872: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9873: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9874:     } else {
                   9875: 	($cdom,$cnum)=split(/_/,$cid);
                   9876:     }
1.620     albertel 9877:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9878:     if (!$chome) {
1.457     raeburn  9879: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9880:     }
1.455     albertel 9881:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9882:     # Make sure the user exists
1.81      www      9883:     my $uhome=&homeserver($uname,$udom);
                   9884:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9885: 	return 'error: no such user';
                   9886:     }
1.297     matthew  9887:     # Get student data if we were not given enough information
                   9888:     if (!defined($first)  || $first  eq '' || 
                   9889:         !defined($last)   || $last   eq '' || 
                   9890:         !defined($uid)    || $uid    eq '' || 
                   9891:         !defined($middle) || $middle eq '' || 
                   9892:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9893:         # They did not supply us with enough data to enroll the student, so
                   9894:         # we need to pick up more information.
1.297     matthew  9895:         my %tmp = &get('environment',
1.294     matthew  9896:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9897:                        ,$udom,$uname);
                   9898: 
1.800     albertel 9899:         #foreach my $key (keys(%tmp)) {
                   9900:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9901:         #}
1.294     matthew  9902:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9903:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9904:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9905:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9906:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9907:     }
1.556     albertel 9908:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9909:     my $user = "$uname:$udom";
                   9910:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9911:     my $reply=cput('classlist',
1.1148    raeburn  9912: 		   {$user => 
1.1314    raeburn  9913: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9914: 		   $cdom,$cnum);
1.1148    raeburn  9915:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9916:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9917:     } else { 
1.81      www      9918: 	return 'error: '.$reply;
                   9919:     }
1.297     matthew  9920:     # Add student role to user
1.83      www      9921:     my $uurl='/'.$cid;
1.81      www      9922:     $uurl=~s/\_/\//g;
                   9923:     if ($usec) {
                   9924: 	$uurl.='/'.$usec;
                   9925:     }
1.1148    raeburn  9926:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9927:                              $selfenroll,$context);
                   9928:     if ($result ne 'ok') {
                   9929:         if ($old_entry{$user} ne '') {
                   9930:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9931:         } else {
                   9932:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9933:         }
                   9934:     }
                   9935:     return $result; 
1.21      www      9936: }
                   9937: 
1.556     albertel 9938: sub format_name {
                   9939:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9940:     my $name;
                   9941:     if ($first ne 'lastname') {
                   9942: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9943:     } else {
                   9944: 	if ($lastname=~/\S/) {
                   9945: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9946: 	    $name=~s/\s+,/,/;
                   9947: 	} else {
                   9948: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9949: 	}
                   9950:     }
                   9951:     $name=~s/^\s+//;
                   9952:     $name=~s/\s+$//;
                   9953:     $name=~s/\s+/ /g;
                   9954:     return $name;
                   9955: }
                   9956: 
1.84      www      9957: # ------------------------------------------------- Write to course preferences
                   9958: 
                   9959: sub writecoursepref {
                   9960:     my ($courseid,%prefs)=@_;
                   9961:     $courseid=~s/^\///;
                   9962:     $courseid=~s/\_/\//g;
                   9963:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9964:     my $chome=homeserver($cnum,$cdomain);
                   9965:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9966: 	return 'error: no such course';
                   9967:     }
                   9968:     my $cstring='';
1.800     albertel 9969:     foreach my $pref (keys(%prefs)) {
                   9970: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9971:     }
1.84      www      9972:     $cstring=~s/\&$//;
                   9973:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9974: }
                   9975: 
                   9976: # ---------------------------------------------------------- Make/modify course
                   9977: 
                   9978: sub createcourse {
1.741     raeburn  9979:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9980:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9981:     $url=&declutter($url);
                   9982:     my $cid='';
1.1028    raeburn  9983:     if ($context eq 'requestcourses') {
                   9984:         my $can_create = 0;
                   9985:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9986:         if ($udom eq $ownerdom) {
                   9987:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9988:                                   $context)) {
                   9989:                 $can_create = 1;
                   9990:             }
                   9991:         } else {
                   9992:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9993:                                            $category);
                   9994:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9995:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9996:                 if (@curr > 0) {
                   9997:                     my @options = qw(approval validate autolimit);
                   9998:                     my $optregex = join('|',@options);
                   9999:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10000:                         $can_create = 1;
                   10001:                     }
                   10002:                 }
                   10003:             }
                   10004:         }
                   10005:         if ($can_create) {
                   10006:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10007:                 unless (&allowed('ccc',$udom)) {
                   10008:                     return 'refused'; 
                   10009:                 }
1.1017    raeburn  10010:             }
                   10011:         } else {
                   10012:             return 'refused';
                   10013:         }
1.1028    raeburn  10014:     } elsif (!&allowed('ccc',$udom)) {
                   10015:         return 'refused';
1.84      www      10016:     }
1.1011    raeburn  10017: # --------------------------------------------------------------- Get Unique ID
                   10018:     my $uname;
                   10019:     if ($cnum =~ /^$match_courseid$/) {
                   10020:         my $chome=&homeserver($cnum,$udom,'true');
                   10021:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10022:             $uname = $cnum;
                   10023:         } else {
1.1038    raeburn  10024:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10025:         }
                   10026:     } else {
1.1038    raeburn  10027:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10028:     }
                   10029:     return $uname if ($uname =~ /^error/);
                   10030: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10031:     if (!defined($course_server)) {
                   10032:         if (defined(&domain($udom,'primary'))) {
                   10033:             $course_server = &domain($udom,'primary');
                   10034:         } else {
                   10035:             $course_server = $env{'user.home'}; 
                   10036:         }
                   10037:     }
                   10038:     my %host_servers =
                   10039:         &Apache::lonnet::get_servers($udom,'library');
                   10040:     unless ($host_servers{$course_server}) {
                   10041:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10042:     }
1.84      www      10043: # ------------------------------------------------------------- Make the course
                   10044:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10045:                       $course_server);
1.84      www      10046:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10047:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10048:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10049: 	return 'error: no such course';
                   10050:     }
1.271     www      10051: # ----------------------------------------------------------------- Course made
1.516     raeburn  10052: # log existence
1.1029    raeburn  10053:     my $now = time;
1.918     raeburn  10054:     my $newcourse = {
                   10055:                     $udom.'_'.$uname => {
1.921     raeburn  10056:                                      description => $description,
                   10057:                                      inst_code   => $inst_code,
                   10058:                                      owner       => $course_owner,
                   10059:                                      type        => $crstype,
1.1029    raeburn  10060:                                      creator     => $env{'user.name'}.':'.
                   10061:                                                     $env{'user.domain'},
                   10062:                                      created     => $now,
                   10063:                                      context     => $context,
1.918     raeburn  10064:                                                 },
                   10065:                     };
1.921     raeburn  10066:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10067: # set toplevel url
1.271     www      10068:     my $topurl=$url;
                   10069:     unless ($nonstandard) {
                   10070: # ------------------------------------------ For standard courses, make top url
                   10071:         my $mapurl=&clutter($url);
1.278     www      10072:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10073:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10074: <map>
                   10075: <resource id="1" type="start"></resource>
                   10076: <resource id="2" src="$mapurl"></resource>
                   10077: <resource id="3" type="finish"></resource>
                   10078: <link index="1" from="1" to="2"></link>
                   10079: <link index="2" from="2" to="3"></link>
                   10080: </map>
                   10081: ENDINITMAP
                   10082:         $topurl=&declutter(
1.638     albertel 10083:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10084:                           );
                   10085:     }
                   10086: # ----------------------------------------------------------- Write preferences
1.84      www      10087:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10088:                      ('description'              => $description,
                   10089:                       'url'                      => $topurl,
                   10090:                       'internal.creator'         => $env{'user.name'}.':'.
                   10091:                                                     $env{'user.domain'},
                   10092:                       'internal.created'         => $now,
                   10093:                       'internal.creationcontext' => $context)
                   10094:                     );
1.84      www      10095:     return '/'.$udom.'/'.$uname;
                   10096: }
                   10097: 
1.1011    raeburn  10098: # ------------------------------------------------------------------- Create ID
                   10099: sub generate_coursenum {
1.1038    raeburn  10100:     my ($udom,$crstype) = @_;
1.1011    raeburn  10101:     my $domdesc = &domain($udom);
                   10102:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10103:     my $first;
                   10104:     if ($crstype eq 'Community') {
                   10105:         $first = '0';
                   10106:     } else {
                   10107:         $first = int(1+rand(9)); 
                   10108:     } 
                   10109:     my $uname=$first.
1.1011    raeburn  10110:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10111:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10112:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10113: # ----------------------------------------------- Make sure that does not exist
                   10114:     my $uhome=&homeserver($uname,$udom,'true');
                   10115:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10116:         if ($crstype eq 'Community') {
                   10117:             $first = '0';
                   10118:         } else {
                   10119:             $first = int(1+rand(9));
                   10120:         }
                   10121:         $uname=$first.
1.1011    raeburn  10122:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10123:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10124:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10125:         $uhome=&homeserver($uname,$udom,'true');
                   10126:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10127:             return 'error: unable to generate unique course-ID';
                   10128:         }
                   10129:     }
                   10130:     return $uname;
                   10131: }
                   10132: 
1.813     albertel 10133: sub is_course {
1.1167    droeschl 10134:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10135:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10136: 
1.1381    raeburn  10137:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10138:     my $uhome=&homeserver($cnum,$cdom);
                   10139:     my $iscourse;
                   10140:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10141:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10142:     } else {
                   10143:         my $hashid = $cdom.':'.$cnum;
                   10144:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10145:         unless (defined($cached)) {
                   10146:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10147:                                         $cnum,undef,undef,'.');
                   10148:             $iscourse = 0;
                   10149:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10150:                 $iscourse = 1;
                   10151:             }
                   10152:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10153:         }
                   10154:     }
                   10155:     return unless ($iscourse);
1.1167    droeschl 10156:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10157: }
                   10158: 
1.1015    raeburn  10159: sub store_userdata {
                   10160:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10161:     my $result;
1.1016    raeburn  10162:     if ($datakey ne '') {
1.1013    raeburn  10163:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10164:             if ($udom eq '' || $uname eq '') {
                   10165:                 $udom = $env{'user.domain'};
                   10166:                 $uname = $env{'user.name'};
                   10167:             }
                   10168:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10169:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10170:                 $result = 'error: no_host';
                   10171:             } else {
                   10172:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10173:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10174: 
                   10175:                 my $namevalue='';
                   10176:                 foreach my $key (keys(%{$storehash})) {
                   10177:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10178:                 }
                   10179:                 $namevalue=~s/\&$//;
1.1224    raeburn  10180:                 unless ($namespace eq 'courserequests') {
                   10181:                     $datakey = &escape($datakey);
                   10182:                 }
1.1105    raeburn  10183:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10184:                                   $namevalue,$uhome);
1.1013    raeburn  10185:             }
                   10186:         } else {
                   10187:             $result = 'error: data to store was not a hash reference'; 
                   10188:         }
                   10189:     } else {
                   10190:         $result= 'error: invalid requestkey'; 
                   10191:     }
                   10192:     return $result;
                   10193: }
                   10194: 
1.21      www      10195: # ---------------------------------------------------------- Assign Custom Role
                   10196: 
                   10197: sub assigncustomrole {
1.957     raeburn  10198:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10199:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10200:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10201: }
                   10202: 
                   10203: # ----------------------------------------------------------------- Revoke Role
                   10204: 
                   10205: sub revokerole {
1.957     raeburn  10206:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10207:     my $now=time;
1.965     raeburn  10208:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10209: }
                   10210: 
                   10211: # ---------------------------------------------------------- Revoke Custom Role
                   10212: 
                   10213: sub revokecustomrole {
1.957     raeburn  10214:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10215:     my $now=time;
1.357     www      10216:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10217:            $deleteflag,$selfenroll,$context);
1.17      www      10218: }
                   10219: 
1.533     banghart 10220: # ------------------------------------------------------------ Disk usage
1.535     albertel 10221: sub diskusage {
1.955     raeburn  10222:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10223:     $directorypath =~ s/\/$//;
                   10224:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10225:                        .&escape($getpropath).':'.&escape($uname).':'
                   10226:                        .&escape($udom),homeserver($uname,$udom));
                   10227:     if ($listing eq 'unknown_cmd') {
                   10228:         if ($getpropath) {
                   10229:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10230:         }
                   10231:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10232:     }
1.514     albertel 10233:     return $listing;
1.512     banghart 10234: }
                   10235: 
1.566     banghart 10236: sub is_locked {
1.1096    raeburn  10237:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10238:     my @check;
                   10239:     my $is_locked;
1.1093    raeburn  10240:     push (@check,$file_name);
1.613     albertel 10241:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10242: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10243:     my ($tmp)=keys(%locked);
                   10244:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10245:     
1.566     banghart 10246:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10247:         $is_locked = 'false';
                   10248:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10249:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10250:                $is_locked = 'true';
1.1096    raeburn  10251:                if (ref($which) eq 'ARRAY') {
                   10252:                    push(@{$which},$entry);
                   10253:                } else {
                   10254:                    last;
                   10255:                }
1.745     raeburn  10256:            }
                   10257:        }
1.566     banghart 10258:     } else {
                   10259:         $is_locked = 'false';
                   10260:     }
1.1093    raeburn  10261:     return $is_locked;
1.566     banghart 10262: }
                   10263: 
1.759     albertel 10264: sub declutter_portfile {
                   10265:     my ($file) = @_;
1.833     albertel 10266:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10267:     return $file;
                   10268: }
                   10269: 
1.559     banghart 10270: # ------------------------------------------------------------- Mark as Read Only
                   10271: 
                   10272: sub mark_as_readonly {
                   10273:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10274:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10275:     my ($tmp)=keys(%current_permissions);
                   10276:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10277:     foreach my $file (@{$files}) {
1.759     albertel 10278: 	$file = &declutter_portfile($file);
1.561     banghart 10279:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10280:     }
1.613     albertel 10281:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10282:     return;
                   10283: }
                   10284: 
1.572     banghart 10285: # ------------------------------------------------------------Save Selected Files
                   10286: 
                   10287: sub save_selected_files {
                   10288:     my ($user, $path, @files) = @_;
                   10289:     my $filename = $user."savedfiles";
1.573     banghart 10290:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10291:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10292:     foreach my $file (@files) {
1.620     albertel 10293:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10294:     }
                   10295:     foreach my $file (@other_files) {
1.574     banghart 10296:         print (OUT $file."\n");
1.572     banghart 10297:     }
1.574     banghart 10298:     close (OUT);
1.572     banghart 10299:     return 'ok';
                   10300: }
                   10301: 
1.574     banghart 10302: sub clear_selected_files {
                   10303:     my ($user) = @_;
                   10304:     my $filename = $user."savedfiles";
1.1359    raeburn  10305:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10306:     print (OUT undef);
                   10307:     close (OUT);
                   10308:     return ("ok");    
                   10309: }
                   10310: 
1.572     banghart 10311: sub files_in_path {
                   10312:     my ($user, $path) = @_;
                   10313:     my $filename = $user."savedfiles";
                   10314:     my %return_files;
1.1359    raeburn  10315:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10316:     while (my $line_in = <IN>) {
1.574     banghart 10317:         chomp ($line_in);
                   10318:         my @paths_and_file = split (m!/!, $line_in);
                   10319:         my $file_part = pop (@paths_and_file);
                   10320:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10321:         $path_part.='/';
                   10322:         my $path_and_file = $path_part.$file_part;
                   10323:         if ($path_part eq $path) {
                   10324:             $return_files{$file_part}= 'selected';
                   10325:         }
                   10326:     }
1.574     banghart 10327:     close (IN);
                   10328:     return (\%return_files);
1.572     banghart 10329: }
                   10330: 
                   10331: # called in portfolio select mode, to show files selected NOT in current directory
                   10332: sub files_not_in_path {
                   10333:     my ($user, $path) = @_;
                   10334:     my $filename = $user."savedfiles";
                   10335:     my @return_files;
                   10336:     my $path_part;
1.1359    raeburn  10337:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10338:     while (my $line = <IN>) {
1.572     banghart 10339:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10340:         my @paths_and_file = split(m|/|, $line);
                   10341:         my $file_part = pop(@paths_and_file);
                   10342:         chomp($file_part);
                   10343:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10344:         $path_part .= '/';
                   10345:         my $path_and_file = $path_part.$file_part;
                   10346:         if ($path_part ne $path) {
1.800     albertel 10347:             push(@return_files, ($path_and_file));
1.572     banghart 10348:         }
                   10349:     }
1.800     albertel 10350:     close(OUT);
1.574     banghart 10351:     return (@return_files);
1.572     banghart 10352: }
                   10353: 
1.1273    raeburn  10354: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10355:  
                   10356: sub portfiles_versioning {
                   10357:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10358:     my $portfolio_root = '/userfiles/portfolio';
                   10359:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10360:     foreach my $file (@{$portfiles}) {
                   10361:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10362:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10363:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10364:         my $getpropath = 1;
                   10365:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10366:                                              $stu_name,$getpropath);
                   10367:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10368:         my $new_answer = 
                   10369:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10370:         if ($new_answer ne 'problem getting file') {
                   10371:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10372:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10373:                               [$symb,$env{'request.course.id'},'graded']);
                   10374:         }
                   10375:     }
                   10376: }
                   10377: 
                   10378: sub get_next_version {
                   10379:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10380:     my $version;
                   10381:     if (ref($dir_list) eq 'ARRAY') {
                   10382:         foreach my $row (@{$dir_list}) {
                   10383:             my ($file) = split(/\&/,$row,2);
                   10384:             my ($file_name,$file_version,$file_ext) =
                   10385:                 &file_name_version_ext($file);
                   10386:             if (($file_name eq $answer_name) &&
                   10387:                 ($file_ext eq $answer_ext)) {
                   10388:                      # gets here if filename and extension match,
                   10389:                      # regardless of version
                   10390:                 if ($file_version ne '') {
                   10391:                     # a versioned file is found  so save it for later
                   10392:                     if ($file_version > $version) {
                   10393:                         $version = $file_version;
                   10394:                     }
                   10395:                 }
                   10396:             }
                   10397:         }
                   10398:     }
                   10399:     $version ++;
                   10400:     return($version);
                   10401: }
                   10402: 
                   10403: sub version_selected_portfile {
                   10404:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10405:     my ($answer_name,$answer_ver,$answer_ext) =
                   10406:         &file_name_version_ext($file_name);
                   10407:     my $new_answer;
                   10408:     $env{'form.copy'} =
                   10409:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10410:     if($env{'form.copy'} eq '-1') {
                   10411:         $new_answer = 'problem getting file';
                   10412:     } else {
                   10413:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10414:         my $copy_result = 
                   10415:             &finishuserfileupload($stu_name,$domain,'copy',
                   10416:                                   '/portfolio'.$directory.$new_answer);
                   10417:     }
                   10418:     undef($env{'form.copy'});
                   10419:     return ($new_answer);
                   10420: }
                   10421: 
                   10422: sub file_name_version_ext {
                   10423:     my ($file)=@_;
                   10424:     my @file_parts = split(/\./, $file);
                   10425:     my ($name,$version,$ext);
                   10426:     if (@file_parts > 1) {
                   10427:         $ext=pop(@file_parts);
                   10428:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10429:             $version=pop(@file_parts);
                   10430:         }
                   10431:         $name=join('.',@file_parts);
                   10432:     } else {
                   10433:         $name=join('.',@file_parts);
                   10434:     }
                   10435:     return($name,$version,$ext);
                   10436: }
                   10437: 
1.745     raeburn  10438: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10439: 
1.745     raeburn  10440: sub get_portfile_permissions {
                   10441:     my ($domain,$user) = @_;
1.613     albertel 10442:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10443:     my ($tmp)=keys(%current_permissions);
                   10444:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10445:     return \%current_permissions;
                   10446: }
                   10447: 
                   10448: #---------------------------------------------Get portfolio file access controls
                   10449: 
1.749     raeburn  10450: sub get_access_controls {
1.745     raeburn  10451:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10452:     my %access;
                   10453:     my $real_file = $file;
                   10454:     $file =~ s/\.meta$//;
1.745     raeburn  10455:     if (defined($file)) {
1.749     raeburn  10456:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10457:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10458:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10459:             }
                   10460:         }
1.745     raeburn  10461:     } else {
1.749     raeburn  10462:         foreach my $key (keys(%{$current_permissions})) {
                   10463:             if ($key =~ /\0accesscontrol$/) {
                   10464:                 if (defined($group)) {
                   10465:                     if ($key !~ m-^\Q$group\E/-) {
                   10466:                         next;
                   10467:                     }
                   10468:                 }
                   10469:                 my ($fullpath) = split(/\0/,$key);
                   10470:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10471:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10472:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10473:                     }
                   10474:                 }
                   10475:             }
                   10476:         }
                   10477:     }
                   10478:     return %access;
                   10479: }
                   10480: 
                   10481: sub modify_access_controls {
                   10482:     my ($file_name,$changes,$domain,$user)=@_;
                   10483:     my ($outcome,$deloutcome);
                   10484:     my %store_permissions;
                   10485:     my %new_values;
                   10486:     my %new_control;
                   10487:     my %translation;
                   10488:     my @deletions = ();
                   10489:     my $now = time;
                   10490:     if (exists($$changes{'activate'})) {
                   10491:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10492:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10493:             my $numnew = scalar(@newitems);
                   10494:             for (my $i=0; $i<$numnew; $i++) {
                   10495:                 my $newkey = $newitems[$i];
                   10496:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10497:                 if ($newkey =~ /^\d+:/) { 
                   10498:                     $newkey =~ s/^(\d+)/$newid/;
                   10499:                     $translation{$1} = $newid;
                   10500:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10501:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10502:                     $translation{$1} = $newid;
                   10503:                 }
1.749     raeburn  10504:                 $new_values{$file_name."\0".$newkey} = 
                   10505:                                           $$changes{'activate'}{$newitems[$i]};
                   10506:                 $new_control{$newkey} = $now;
                   10507:             }
                   10508:         }
                   10509:     }
                   10510:     my %todelete;
                   10511:     my %changed_items;
                   10512:     foreach my $action ('delete','update') {
                   10513:         if (exists($$changes{$action})) {
                   10514:             if (ref($$changes{$action}) eq 'HASH') {
                   10515:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10516:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10517:                     if ($action eq 'delete') { 
                   10518:                         $todelete{$itemnum} = 1;
                   10519:                     } else {
                   10520:                         $changed_items{$itemnum} = $key;
                   10521:                     }
                   10522:                 }
1.745     raeburn  10523:             }
                   10524:         }
1.749     raeburn  10525:     }
                   10526:     # get lock on access controls for file.
                   10527:     my $lockhash = {
                   10528:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10529:                                                        ':'.$env{'user.domain'},
                   10530:                    }; 
                   10531:     my $tries = 0;
                   10532:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10533:    
1.1288    damieng  10534:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10535:         $tries ++;
1.1289    damieng  10536:         sleep(0.1);
1.749     raeburn  10537:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10538:     }
                   10539:     if ($gotlock eq 'ok') {
                   10540:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10541:         my ($tmp)=keys(%curr_permissions);
                   10542:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10543:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10544:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10545:             if (ref($curr_controls) eq 'HASH') {
                   10546:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10547:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10548:                     if (defined($todelete{$itemnum})) {
                   10549:                         push(@deletions,$file_name."\0".$control_item);
                   10550:                     } else {
                   10551:                         if (defined($changed_items{$itemnum})) {
                   10552:                             $new_control{$changed_items{$itemnum}} = $now;
                   10553:                             push(@deletions,$file_name."\0".$control_item);
                   10554:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10555:                         } else {
                   10556:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10557:                         }
                   10558:                     }
1.745     raeburn  10559:                 }
                   10560:             }
                   10561:         }
1.970     raeburn  10562:         my ($group);
                   10563:         if (&is_course($domain,$user)) {
                   10564:             ($group,my $file) = split(/\//,$file_name,2);
                   10565:         }
1.749     raeburn  10566:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10567:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10568:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10569:         #  remove lock
                   10570:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10571:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10572:         my $sqlresult =
1.970     raeburn  10573:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10574:                                     $group);
1.749     raeburn  10575:     } else {
                   10576:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10577:     }
1.749     raeburn  10578:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10579: }
                   10580: 
1.827     raeburn  10581: sub make_public_indefinitely {
1.1271    raeburn  10582:     my (@requrl) = @_;
                   10583:     return &automated_portfile_access('public',\@requrl);
                   10584: }
                   10585: 
                   10586: sub automated_portfile_access {
                   10587:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10588:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10589:         return 'invalid';
                   10590:     }
1.1271    raeburn  10591:     my %urls;
                   10592:     if (ref($addsref) eq 'ARRAY') {
                   10593:         foreach my $requrl (@{$addsref}) {
                   10594:             if (&is_portfolio_url($requrl)) {
                   10595:                 unless (exists($urls{$requrl})) {
                   10596:                     $urls{$requrl} = 'add';
                   10597:                 }
                   10598:             }
                   10599:         }
                   10600:     }
                   10601:     if (ref($delsref) eq 'ARRAY') {
                   10602:         foreach my $requrl (@{$delsref}) { 
                   10603:             if (&is_portfolio_url($requrl)) {
                   10604:                 unless (exists($urls{$requrl})) {
                   10605:                     $urls{$requrl} = 'delete'; 
                   10606:                 }
                   10607:             }
                   10608:         }
                   10609:     }
                   10610:     unless (keys(%urls)) {
                   10611:         return 'invalid';
                   10612:     }
                   10613:     my $ip;
                   10614:     if ($accesstype eq 'ip') {
                   10615:         if (ref($info) eq 'HASH') {
                   10616:             if ($info->{'ip'} ne '') {
                   10617:                 $ip = $info->{'ip'};
                   10618:             }
                   10619:         }
                   10620:         if ($ip eq '') {
                   10621:             return 'invalid';
                   10622:         }
                   10623:     }
                   10624:     my $errors;
1.827     raeburn  10625:     my $now = time;
1.1271    raeburn  10626:     my %current_perms;
                   10627:     foreach my $requrl (sort(keys(%urls))) {
                   10628:         my $action;
                   10629:         if ($urls{$requrl} eq 'add') {
                   10630:             $action = 'activate';
                   10631:         } else {
                   10632:             $action = 'none';
                   10633:         }
                   10634:         my $aclnum = 0;
1.827     raeburn  10635:         my (undef,$udom,$unum,$file_name,$group) =
                   10636:             &parse_portfolio_url($requrl);
1.1271    raeburn  10637:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10638:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10639:         }
                   10640:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10641:                                                    $group,$file_name);
                   10642:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10643:             my ($num,$scope,$end,$start) = 
                   10644:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10645:             if ($scope eq $accesstype) {
                   10646:                 if (($start <= $now) && ($end == 0)) {
                   10647:                     if ($accesstype eq 'ip') {
                   10648:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10649:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10650:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10651:                                     if ($urls{$requrl} eq 'add') {
                   10652:                                         $action = 'none';
                   10653:                                         last;
                   10654:                                     } else {
                   10655:                                         $action = 'delete';
                   10656:                                         $aclnum = $num;
                   10657:                                         last;
                   10658:                                     }
                   10659:                                 }
                   10660:                             }
                   10661:                         }
                   10662:                     } elsif ($accesstype eq 'public') {
                   10663:                         if ($urls{$requrl} eq 'add') {
                   10664:                             $action = 'none';
                   10665:                             last;
                   10666:                         } else {
                   10667:                             $action = 'delete';
                   10668:                             $aclnum = $num;
                   10669:                             last;
                   10670:                         }
                   10671:                     }
                   10672:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10673:                     $action = 'update';
                   10674:                     $aclnum = $num;
1.1271    raeburn  10675:                     last;
1.827     raeburn  10676:                 }
                   10677:             }
                   10678:         }
                   10679:         if ($action eq 'none') {
1.1271    raeburn  10680:             next;
1.827     raeburn  10681:         } else {
                   10682:             my %changes;
                   10683:             my $newend = 0;
                   10684:             my $newstart = $now;
1.1271    raeburn  10685:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10686:             $changes{$action}{$newkey} = {
1.1271    raeburn  10687:                 type => $accesstype,
1.827     raeburn  10688:                 time => {
                   10689:                     start => $newstart,
                   10690:                     end   => $newend,
                   10691:                 },
                   10692:             };
1.1271    raeburn  10693:             if ($accesstype eq 'ip') {
                   10694:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10695:             }
1.827     raeburn  10696:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10697:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10698:             unless ($outcome eq 'ok') {
                   10699:                 $errors .= $outcome.' ';
                   10700:             }
1.827     raeburn  10701:         }
1.1271    raeburn  10702:     }
                   10703:     if ($errors) {
                   10704:         $errors =~ s/\s$//;
                   10705:         return $errors;
1.827     raeburn  10706:     } else {
1.1271    raeburn  10707:         return 'ok';
1.827     raeburn  10708:     }
                   10709: }
                   10710: 
1.745     raeburn  10711: #------------------------------------------------------Get Marked as Read Only
                   10712: 
                   10713: sub get_marked_as_readonly {
                   10714:     my ($domain,$user,$what,$group) = @_;
                   10715:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10716:     my @readonly_files;
1.629     banghart 10717:     my $cmp1=$what;
                   10718:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10719:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10720:         if (defined($group)) {
                   10721:             if ($file_name !~ m-^\Q$group\E/-) {
                   10722:                 next;
                   10723:             }
                   10724:         }
1.561     banghart 10725:         if (ref($value) eq "ARRAY"){
                   10726:             foreach my $stored_what (@{$value}) {
1.629     banghart 10727:                 my $cmp2=$stored_what;
1.759     albertel 10728:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10729:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10730:                 }
1.629     banghart 10731:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10732:                     push(@readonly_files, $file_name);
1.745     raeburn  10733:                     last;
1.563     banghart 10734:                 } elsif (!defined($what)) {
                   10735:                     push(@readonly_files, $file_name);
1.745     raeburn  10736:                     last;
1.561     banghart 10737:                 }
                   10738:             }
1.745     raeburn  10739:         }
1.561     banghart 10740:     }
                   10741:     return @readonly_files;
                   10742: }
1.577     banghart 10743: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10744: 
1.577     banghart 10745: sub get_marked_as_readonly_hash {
1.745     raeburn  10746:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10747:     my %readonly_files;
1.745     raeburn  10748:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10749:         if (defined($group)) {
                   10750:             if ($file_name !~ m-^\Q$group\E/-) {
                   10751:                 next;
                   10752:             }
                   10753:         }
1.577     banghart 10754:         if (ref($value) eq "ARRAY"){
                   10755:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10756:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10757:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10758:                         if ($lock_descriptor eq 'graded') {
                   10759:                             $readonly_files{$file_name} = 'graded';
                   10760:                         } elsif ($lock_descriptor eq 'handback') {
                   10761:                             $readonly_files{$file_name} = 'handback';
                   10762:                         } else {
                   10763:                             if (!exists($readonly_files{$file_name})) {
                   10764:                                 $readonly_files{$file_name} = 'locked';
                   10765:                             }
                   10766:                         }
1.745     raeburn  10767:                     }
1.750     banghart 10768:                 } 
1.577     banghart 10769:             }
                   10770:         } 
                   10771:     }
                   10772:     return %readonly_files;
                   10773: }
1.559     banghart 10774: # ------------------------------------------------------------ Unmark as Read Only
                   10775: 
                   10776: sub unmark_as_readonly {
1.629     banghart 10777:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10778:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10779:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10780:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10781:     my $symb_crs = $what;
                   10782:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10783:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10784:     my ($tmp)=keys(%current_permissions);
                   10785:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10786:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10787:     foreach my $file (@readonly_files) {
1.759     albertel 10788: 	my $clean_file = &declutter_portfile($file);
                   10789: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10790: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10791:         my @new_locks;
                   10792:         my @del_keys;
                   10793:         if (ref($current_locks) eq "ARRAY"){
                   10794:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10795:                 my $compare=$locker;
1.749     raeburn  10796:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10797:                     $compare=join('',@{$locker});
1.746     raeburn  10798:                     if ($compare ne $symb_crs) {
                   10799:                         push(@new_locks, $locker);
                   10800:                     }
1.563     banghart 10801:                 }
                   10802:             }
1.650     albertel 10803:             if (scalar(@new_locks) > 0) {
1.563     banghart 10804:                 $current_permissions{$file} = \@new_locks;
                   10805:             } else {
                   10806:                 push(@del_keys, $file);
1.613     albertel 10807:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10808:                 delete($current_permissions{$file});
1.563     banghart 10809:             }
                   10810:         }
1.561     banghart 10811:     }
1.613     albertel 10812:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10813:     return;
                   10814: }
1.512     banghart 10815: 
1.17      www      10816: # ------------------------------------------------------------ Directory lister
                   10817: 
                   10818: sub dirlist {
1.955     raeburn  10819:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10820:     $uri=~s/^\///;
                   10821:     $uri=~s/\/$//;
1.253     stredwic 10822:     my ($udom, $uname);
1.955     raeburn  10823:     if ($getuserdir) {
1.253     stredwic 10824:         $udom = $userdomain;
                   10825:         $uname = $username;
1.955     raeburn  10826:     } else {
                   10827:         (undef,$udom,$uname)=split(/\//,$uri);
                   10828:         if(defined($userdomain)) {
                   10829:             $udom = $userdomain;
                   10830:         }
                   10831:         if(defined($username)) {
                   10832:             $uname = $username;
                   10833:         }
1.253     stredwic 10834:     }
1.955     raeburn  10835:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10836: 
1.955     raeburn  10837:     $dirRoot = $perlvar{'lonDocRoot'};
                   10838:     if (defined($getpropath)) {
                   10839:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10840:         $dirRoot =~ s/\/$//;
1.955     raeburn  10841:     } elsif (defined($getuserdir)) {
                   10842:         my $subdir=$uname.'__';
                   10843:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10844:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10845:                    ."/$udom/$subdir/$uname";
                   10846:     } elsif (defined($alternateRoot)) {
                   10847:         $dirRoot = $alternateRoot;
1.751     banghart 10848:     }
1.253     stredwic 10849: 
                   10850:     if($udom) {
                   10851:         if($uname) {
1.1135    raeburn  10852:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10853:             if ($uhome eq 'no_host') {
                   10854:                 return ([],'no_host');
                   10855:             }
1.955     raeburn  10856:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10857:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10858:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10859:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10860:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10861:             } else {
                   10862:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10863:             }
1.605     matthew  10864:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10865:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10866:                 @listing_results = split(/:/,$listing);
                   10867:             } else {
                   10868:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10869:             }
1.1135    raeburn  10870:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10871:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10872:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10873:                 return ([],$listing);
                   10874:             } else {
                   10875:                 return (\@listing_results);
1.1135    raeburn  10876:             }
1.955     raeburn  10877:         } elsif(!$alternateRoot) {
1.1136    raeburn  10878:             my (%allusers,%listerror);
1.841     albertel 10879: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10880:  	    foreach my $tryserver (keys(%servers)) {
                   10881:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10882:                                   &escape($udom),$tryserver);
                   10883:                 if ($listing eq 'unknown_cmd') {
                   10884: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10885: 				      $udom, $tryserver);
                   10886:                 } else {
                   10887:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10888:                 }
1.841     albertel 10889: 		if ($listing eq 'unknown_cmd') {
                   10890: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10891: 				      $udom, $tryserver);
                   10892: 		    @listing_results = split(/:/,$listing);
                   10893: 		} else {
                   10894: 		    @listing_results =
                   10895: 			map { &unescape($_); } split(/:/,$listing);
                   10896: 		}
1.1136    raeburn  10897:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10898:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10899:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10900:                     $listerror{$tryserver} = $listing;
                   10901:                 } else {
1.841     albertel 10902: 		    foreach my $line (@listing_results) {
                   10903: 			my ($entry) = split(/&/,$line,2);
                   10904: 			$allusers{$entry} = 1;
                   10905: 		    }
                   10906: 		}
1.253     stredwic 10907:             }
1.1136    raeburn  10908:             my @alluserslist=();
1.800     albertel 10909:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10910:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10911:             }
1.1318    droeschl 10912: 
                   10913:             if (!%listerror) {
                   10914:                 # no errors
                   10915:                 return (\@alluserslist);
                   10916:             } elsif (scalar(keys(%servers)) == 1) {
                   10917:                 # one library server, one error 
                   10918:                 my ($key) = keys(%listerror);
                   10919:                 return (\@alluserslist, $listerror{$key});
                   10920:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10921:                 # con_lost indicates that we might miss data from at least one
                   10922:                 # library server
                   10923:                 return (\@alluserslist, 'con_lost');
                   10924:             } else {
                   10925:                 # multiple library servers and no con_lost -> data should be
                   10926:                 # complete. 
                   10927:                 return (\@alluserslist);
                   10928:             }
                   10929: 
1.253     stredwic 10930:         } else {
1.1136    raeburn  10931:             return ([],'missing username');
1.253     stredwic 10932:         }
1.955     raeburn  10933:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10934:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10935:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10936:         return (\@all_domains);
1.955     raeburn  10937:     } else {
1.1136    raeburn  10938:         return ([],'missing domain');
1.275     stredwic 10939:     }
                   10940: }
                   10941: 
                   10942: # --------------------------------------------- GetFileTimestamp
                   10943: # This function utilizes dirlist and returns the date stamp for
                   10944: # when it was last modified.  It will also return an error of -1
                   10945: # if an error occurs
                   10946: 
                   10947: sub GetFileTimestamp {
1.955     raeburn  10948:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10949:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10950:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10951:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10952:                                     undef,$getuserdir);
                   10953:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10954:         return -1;
                   10955:     }
                   10956:     if (ref($fileref) eq 'ARRAY') {
                   10957:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10958:         # @stats contains first the filename, then the stat output
                   10959:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10960:     } else {
                   10961:         return -1;
1.253     stredwic 10962:     }
1.26      www      10963: }
                   10964: 
1.712     albertel 10965: sub stat_file {
                   10966:     my ($uri) = @_;
1.787     albertel 10967:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10968: 
1.955     raeburn  10969:     my ($udom,$uname,$file);
1.712     albertel 10970:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10971: 	($udom,$uname,$file) =
1.811     albertel 10972: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10973: 	$file = 'userfiles/'.$file;
                   10974:     }
                   10975:     if ($uri =~ m-^/res/-) {
                   10976: 	($udom,$uname) = 
1.807     albertel 10977: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10978: 	$file = $uri;
                   10979:     }
                   10980: 
                   10981:     if (!$udom || !$uname || !$file) {
                   10982: 	# unable to handle the uri
                   10983: 	return ();
                   10984:     }
1.956     raeburn  10985:     my $getpropath;
                   10986:     if ($file =~ /^userfiles\//) {
                   10987:         $getpropath = 1;
                   10988:     }
1.1136    raeburn  10989:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10990:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10991:         return ();
                   10992:     } else {
                   10993:         if (ref($listref) eq 'ARRAY') {
                   10994:             my @stats = split('&',$listref->[0]);
                   10995: 	    shift(@stats); #filename is first
                   10996: 	    return @stats;
                   10997:         }
1.712     albertel 10998:     }
                   10999:     return ();
                   11000: }
                   11001: 
1.1313    raeburn  11002: # --------------------------------------------------------- recursedirs
                   11003: # Recursive function to traverse either a specific user's Authoring Space
                   11004: # or corresponding Published Resource Space, and populate the hash ref:
                   11005: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11006: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11007: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11008: # files in Authoring Space.
                   11009: #
                   11010: # Inputs:
                   11011: #
                   11012: # $is_home - true if current server is home server for user's space
                   11013: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11014: # $docroot - Document root (i.e., /home/httpd/html
                   11015: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11016: # $relpath - Current path (relative to top level).
                   11017: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11018: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11019: #
                   11020: # Returns: nothing
                   11021: #
                   11022: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11023: #
                   11024: # Currently used by interface/londocs.pm to create linked select boxes for
                   11025: # directory and filename to import a Course "Author" resource into a course, and
                   11026: # also to create linked select boxes for Authoring Space and Directory to choose
                   11027: # save location for creation of a new "standard" problem from the Course Editor.
                   11028: #
                   11029: 
                   11030: sub recursedirs {
                   11031:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11032:     return unless (ref($dirhashref) eq 'HASH');
                   11033:     my $currpath = $docroot.$toppath;
                   11034:     if ($relpath) {
                   11035:         $currpath .= "/$relpath";
                   11036:     }
                   11037:     my $savefile;
                   11038:     if (ref($filehashref)) {
                   11039:         $savefile = 1;
                   11040:     }
                   11041:     if ($is_home) {
                   11042:         if (opendir(my $dirh,$currpath)) {
                   11043:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11044:                 next if ($item eq '');
                   11045:                 if (-d "$currpath/$item") {
                   11046:                     my $newpath;
                   11047:                     if ($relpath) {
                   11048:                         $newpath = "$relpath/$item";
                   11049:                     } else {
                   11050:                         $newpath = $item;
                   11051:                     }
                   11052:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11053:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11054:                 } elsif ($savefile) {
                   11055:                     if ($context eq 'priv') {
                   11056:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11057:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11058:                         }
                   11059:                     } else {
                   11060:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11061:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11062:                         }
                   11063:                     }
                   11064:                 }
                   11065:             }
                   11066:             closedir($dirh);
                   11067:         }
                   11068:     } else {
                   11069:         my ($dirlistref,$listerror) =
                   11070:             &dirlist($toppath.$relpath);
                   11071:         my @dir_lines;
                   11072:         my $dirptr=16384;
                   11073:         if (ref($dirlistref) eq 'ARRAY') {
                   11074:             foreach my $dir_line (sort
                   11075:                               {
                   11076:                                   my ($afile)=split('&',$a,2);
                   11077:                                   my ($bfile)=split('&',$b,2);
                   11078:                                   return (lc($afile) cmp lc($bfile));
                   11079:                               } (@{$dirlistref})) {
                   11080:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11081:                     split(/\&/,$dir_line,16);
                   11082:                 $item =~ s/\s+$//;
                   11083:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11084:                 if ($dirptr&$testdir) {
                   11085:                     my $newpath;
                   11086:                     if ($relpath) {
                   11087:                         $newpath = "$relpath/$item";
                   11088:                     } else {
                   11089:                         $relpath = '/';
                   11090:                         $newpath = $item;
                   11091:                     }
                   11092:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11093:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11094:                 } elsif ($savefile) {
                   11095:                     if ($context eq 'priv') {
                   11096:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11097:                             $filehashref->{$relpath}{$item} = 1;
                   11098:                         }
                   11099:                     } else {
                   11100:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11101:                             $filehashref->{$relpath}{$item} = 1;
                   11102:                         }
                   11103:                     }
                   11104:                 }
                   11105:             }
                   11106:         }
                   11107:     }
                   11108:     return;
                   11109: }
                   11110: 
1.26      www      11111: # -------------------------------------------------------- Value of a Condition
                   11112: 
1.713     albertel 11113: # gets the value of a specific preevaluated condition
                   11114: #    stored in the string  $env{user.state.<cid>}
                   11115: # or looks up a condition reference in the bighash and if if hasn't
                   11116: # already been evaluated recurses into docondval to get the value of
                   11117: # the condition, then memoizing it to 
                   11118: #   $env{user.state.<cid>.<condition>}
1.40      www      11119: sub directcondval {
                   11120:     my $number=shift;
1.620     albertel 11121:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11122: 	&Apache::lonuserstate::evalstate();
                   11123:     }
1.713     albertel 11124:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11125: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11126:     } elsif ($number =~ /^_/) {
                   11127: 	my $sub_condition;
                   11128: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11129: 		&GDBM_READER(),0640)) {
                   11130: 	    $sub_condition=$bighash{'conditions'.$number};
                   11131: 	    untie(%bighash);
                   11132: 	}
                   11133: 	my $value = &docondval($sub_condition);
1.949     raeburn  11134: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11135: 	return $value;
                   11136:     }
1.620     albertel 11137:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11138:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11139:     } else {
                   11140:        return 2;
                   11141:     }
                   11142: }
                   11143: 
1.713     albertel 11144: # get the collection of conditions for this resource
1.26      www      11145: sub condval {
                   11146:     my $condidx=shift;
1.54      www      11147:     my $allpathcond='';
1.713     albertel 11148:     foreach my $cond (split(/\|/,$condidx)) {
                   11149: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11150: 	    $allpathcond.=
                   11151: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11152: 	}
1.191     harris41 11153:     }
1.54      www      11154:     $allpathcond=~s/\|$//;
1.713     albertel 11155:     return &docondval($allpathcond);
                   11156: }
                   11157: 
                   11158: #evaluates an expression of conditions
                   11159: sub docondval {
                   11160:     my ($allpathcond) = @_;
                   11161:     my $result=0;
                   11162:     if ($env{'request.course.id'}
                   11163: 	&& defined($allpathcond)) {
                   11164: 	my $operand='|';
                   11165: 	my @stack;
                   11166: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11167: 	    if ($chunk eq '(') {
                   11168: 		push @stack,($operand,$result);
                   11169: 	    } elsif ($chunk eq ')') {
                   11170: 		my $before=pop @stack;
                   11171: 		if (pop @stack eq '&') {
                   11172: 		    $result=$result>$before?$before:$result;
                   11173: 		} else {
                   11174: 		    $result=$result>$before?$result:$before;
                   11175: 		}
                   11176: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11177: 		$operand=$chunk;
                   11178: 	    } else {
                   11179: 		my $new=directcondval($chunk);
                   11180: 		if ($operand eq '&') {
                   11181: 		    $result=$result>$new?$new:$result;
                   11182: 		} else {
                   11183: 		    $result=$result>$new?$result:$new;
                   11184: 		}
                   11185: 	    }
                   11186: 	}
1.26      www      11187:     }
                   11188:     return $result;
1.421     albertel 11189: }
                   11190: 
                   11191: # ---------------------------------------------------- Devalidate courseresdata
                   11192: 
                   11193: sub devalidatecourseresdata {
                   11194:     my ($coursenum,$coursedomain)=@_;
                   11195:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11196:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11197: }
                   11198: 
1.763     www      11199: 
1.200     www      11200: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11201: #
                   11202: #  Parameters:
                   11203: #      $coursenum    - Number of the course.
                   11204: #      $coursedomain - Domain at which the course was created.
                   11205: #  Returns:
                   11206: #     A hash of the course parameters along (I think) with timestamps
                   11207: #     and version info.
1.877     foxr     11208: 
1.624     albertel 11209: sub get_courseresdata {
                   11210:     my ($coursenum,$coursedomain)=@_;
1.200     www      11211:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11212:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11213:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11214:     my %dumpreply;
1.417     albertel 11215:     unless (defined($cached)) {
1.624     albertel 11216: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11217: 	$result=\%dumpreply;
1.251     albertel 11218: 	my ($tmp) = keys(%dumpreply);
                   11219: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11220: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11221: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11222: 	    return $tmp;
1.416     albertel 11223: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11224: 	    $result=undef;
1.599     albertel 11225: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11226: 	}
                   11227:     }
1.624     albertel 11228:     return $result;
                   11229: }
                   11230: 
1.633     albertel 11231: sub devalidateuserresdata {
                   11232:     my ($uname,$udom)=@_;
                   11233:     my $hashid="$udom:$uname";
                   11234:     &devalidate_cache_new('userres',$hashid);
                   11235: }
                   11236: 
1.624     albertel 11237: sub get_userresdata {
                   11238:     my ($uname,$udom)=@_;
                   11239:     #most student don\'t have any data set, check if there is some data
                   11240:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11241: 
                   11242:     my $hashid="$udom:$uname";
                   11243:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11244:     if (!defined($cached)) {
                   11245: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11246: 	$result=\%resourcedata;
                   11247: 	&do_cache_new('userres',$hashid,$result,600);
                   11248:     }
                   11249:     my ($tmp)=keys(%$result);
                   11250:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11251: 	return $result;
                   11252:     }
                   11253:     #error 2 occurs when the .db doesn't exist
                   11254:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11255:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11256: 	    &logthis("<font color=\"blue\">WARNING:".
                   11257: 		     " Trying to get resource data for ".
                   11258: 		     $uname." at ".$udom.": ".
                   11259: 		     $tmp."</font>");
                   11260:         }
1.624     albertel 11261:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11262: 	#&EXT_cache_set($udom,$uname);
                   11263: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11264: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11265:     }
                   11266:     return $tmp;
                   11267: }
1.879     foxr     11268: #----------------------------------------------- resdata - return resource data
                   11269: #  Purpose:
                   11270: #    Return resource data for either users or for a course.
                   11271: #  Parameters:
                   11272: #     $name      - Course/user name.
                   11273: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11274: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11275: #     $mapp      - decluttered URL of enclosing map  
                   11276: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11277: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11278: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11279: #     $courseid  - CourseID (first part of param identifier).
                   11280: #     $modifier  - Middle part of param identifier.
                   11281: #     $what      - Last part of param identifier.
1.879     foxr     11282: #     @which     - Array of names of resources desired.
                   11283: #  Returns:
                   11284: #     The value of the first reasource in @which that is found in the
                   11285: #     resource hash.
                   11286: #  Exceptional Conditions:
                   11287: #     If the $type passed in is not valid (not the string 'course' or 
                   11288: #     'user', an undefined  reference is returned.
                   11289: #     If none of the resources are found, an undef is returned
1.624     albertel 11290: sub resdata {
1.1301    raeburn  11291:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11292:         $modifier,$what,@which)=@_;
1.624     albertel 11293:     my $result;
                   11294:     if ($type eq 'course') {
                   11295: 	$result=&get_courseresdata($name,$domain);
                   11296:     } elsif ($type eq 'user') {
                   11297: 	$result=&get_userresdata($name,$domain);
                   11298:     }
                   11299:     if (!ref($result)) { return $result; }    
1.251     albertel 11300:     foreach my $item (@which) {
1.1301    raeburn  11301:         if ($item->[1] eq 'course') {
                   11302:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11303:                 unless ($$recursed) {
1.1302    raeburn  11304:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11305:                     $$recursed = 1;
                   11306:                 }
                   11307:                 foreach my $item (@${recurseup}) {
                   11308:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11309:                     last if (defined($result->{$norecursechk}));
                   11310:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11311:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11312:                 }
                   11313:             }
                   11314:         }
                   11315:         if (defined($result->{$item->[0]})) {
1.927     albertel 11316: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11317: 	}
1.250     albertel 11318:     }
1.291     albertel 11319:     return undef;
1.200     www      11320: }
                   11321: 
1.1360    raeburn  11322: sub get_domain_lti {
                   11323:     my ($cdom,$context) = @_;
                   11324:     my ($name,%lti);
                   11325:     if ($context eq 'consumer') {
                   11326:         $name = 'ltitools';
                   11327:     } elsif ($context eq 'provider') {
                   11328:         $name = 'lti';
                   11329:     } else {
                   11330:         return %lti;
                   11331:     }
                   11332:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11333:     if (defined($cached)) {
                   11334:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11335:             %lti = %{$result};
1.1298    raeburn  11336:         }
                   11337:     } else {
1.1360    raeburn  11338:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11339:         if (ref($domconfig{$name}) eq 'HASH') {
                   11340:             %lti = %{$domconfig{$name}};
                   11341:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11342:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11343:                 foreach my $id (keys(%lti)) {
                   11344:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11345:                         foreach my $item ('key','secret') {
1.1360    raeburn  11346:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11347:                         }
                   11348:                     }
                   11349:                 }
                   11350:             }
1.1298    raeburn  11351:         }
                   11352:         my $cachetime = 24*60*60;
1.1360    raeburn  11353:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11354:     }
1.1360    raeburn  11355:     return %lti;
1.1298    raeburn  11356: }
                   11357: 
1.1236    raeburn  11358: sub get_numsuppfiles {
                   11359:     my ($cnum,$cdom,$ignorecache)=@_;
                   11360:     my $hashid=$cnum.':'.$cdom;
                   11361:     my ($suppcount,$cached);
                   11362:     unless ($ignorecache) {
                   11363:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11364:     }
                   11365:     unless (defined($cached)) {
                   11366:         my $chome=&homeserver($cnum,$cdom);
                   11367:         unless ($chome eq 'no_host') {
1.1366    raeburn  11368:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11369:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11370:             ($suppcount,$supptools,$errors) =
                   11371:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11372:                                                          $supptools,$errors);
1.1236    raeburn  11373:         }
                   11374:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11375:     }
                   11376:     return $suppcount;
                   11377: }
                   11378: 
1.379     matthew  11379: #
                   11380: # EXT resource caching routines
                   11381: #
                   11382: 
1.1302    raeburn  11383: {
                   11384: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11385: #
                   11386: # The course for which we cache
                   11387: my $cachedmapkey='';
                   11388: # The cached recursive maps for this course
                   11389: my %cachedmaps=();
                   11390: # When this was last done
                   11391: my $cachedmaptime='';
                   11392: 
1.379     matthew  11393: sub clear_EXT_cache_status {
1.383     albertel 11394:     &delenv('cache.EXT.');
1.379     matthew  11395: }
                   11396: 
                   11397: sub EXT_cache_status {
                   11398:     my ($target_domain,$target_user) = @_;
1.383     albertel 11399:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11400:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11401:         # We know already the user has no data
                   11402:         return 1;
                   11403:     } else {
                   11404:         return 0;
                   11405:     }
                   11406: }
                   11407: 
                   11408: sub EXT_cache_set {
                   11409:     my ($target_domain,$target_user) = @_;
1.383     albertel 11410:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11411:     #&appenv({$cachename => time});
1.379     matthew  11412: }
                   11413: 
1.28      www      11414: # --------------------------------------------------------- Value of a Variable
1.58      www      11415: sub EXT {
1.715     albertel 11416: 
1.1228    raeburn  11417:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11418:     unless ($varname) { return ''; }
1.218     albertel 11419:     #get real user name/domain, courseid and symb
                   11420:     my $courseid;
1.359     albertel 11421:     my $publicuser;
1.427     www      11422:     if ($symbparm) {
                   11423: 	$symbparm=&get_symb_from_alias($symbparm);
                   11424:     }
1.218     albertel 11425:     if (!($uname && $udom)) {
1.790     albertel 11426:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11427:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11428:     } else {
1.620     albertel 11429: 	$courseid=$env{'request.course.id'};
1.218     albertel 11430:     }
1.48      www      11431:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11432:     my $rest;
1.320     albertel 11433:     if (defined($therest[0])) {
1.48      www      11434:        $rest=join('.',@therest);
                   11435:     } else {
                   11436:        $rest='';
                   11437:     }
1.320     albertel 11438: 
1.57      www      11439:     my $qualifierrest=$qualifier;
                   11440:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11441:     my $spacequalifierrest=$space;
                   11442:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11443:     if ($realm eq 'user') {
1.48      www      11444: # --------------------------------------------------------------- user.resource
                   11445: 	if ($space eq 'resource') {
1.651     albertel 11446: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11447: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11448: 		 &&
1.744     albertel 11449: 		 ($symbparm eq &symbread()) ) {	
                   11450: 		# if we are in the middle of processing the resource the
                   11451: 		# get the value we are planning on committing
                   11452:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11453:                     return $Apache::lonhomework::results{$qualifierrest};
                   11454:                 } else {
                   11455:                     return $Apache::lonhomework::history{$qualifierrest};
                   11456:                 }
1.335     albertel 11457: 	    } else {
1.359     albertel 11458: 		my %restored;
1.620     albertel 11459: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11460: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11461: 		} else {
                   11462: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11463: 		}
1.335     albertel 11464: 		return $restored{$qualifierrest};
                   11465: 	    }
1.48      www      11466: # ----------------------------------------------------------------- user.access
                   11467:         } elsif ($space eq 'access') {
1.218     albertel 11468: 	    # FIXME - not supporting calls for a specific user
1.48      www      11469:             return &allowed($qualifier,$rest);
                   11470: # ------------------------------------------ user.preferences, user.environment
                   11471:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11472: 	    if (($uname eq $env{'user.name'}) &&
                   11473: 		($udom eq $env{'user.domain'})) {
                   11474: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11475: 	    } else {
1.359     albertel 11476: 		my %returnhash;
                   11477: 		if (!$publicuser) {
                   11478: 		    %returnhash=&userenvironment($udom,$uname,
                   11479: 						 $qualifierrest);
                   11480: 		}
1.218     albertel 11481: 		return $returnhash{$qualifierrest};
                   11482: 	    }
1.48      www      11483: # ----------------------------------------------------------------- user.course
                   11484:         } elsif ($space eq 'course') {
1.218     albertel 11485: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11486:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11487: # ------------------------------------------------------------------- user.role
                   11488:         } elsif ($space eq 'role') {
1.218     albertel 11489: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11490:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11491:             if ($qualifier eq 'value') {
                   11492: 		return $role;
                   11493:             } elsif ($qualifier eq 'extent') {
                   11494:                 return $where;
                   11495:             }
                   11496: # ----------------------------------------------------------------- user.domain
                   11497:         } elsif ($space eq 'domain') {
1.218     albertel 11498:             return $udom;
1.48      www      11499: # ------------------------------------------------------------------- user.name
                   11500:         } elsif ($space eq 'name') {
1.218     albertel 11501:             return $uname;
1.48      www      11502: # ---------------------------------------------------- Any other user namespace
1.29      www      11503:         } else {
1.359     albertel 11504: 	    my %reply;
                   11505: 	    if (!$publicuser) {
                   11506: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11507: 	    }
                   11508: 	    return $reply{$qualifierrest};
1.48      www      11509:         }
1.236     www      11510:     } elsif ($realm eq 'query') {
                   11511: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11512:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11513: 						[$spacequalifierrest]);
1.620     albertel 11514: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11515:    } elsif ($realm eq 'request') {
1.48      www      11516: # ------------------------------------------------------------- request.browser
                   11517:         if ($space eq 'browser') {
1.1145    bisitz   11518:             return $env{'browser.'.$qualifier};
1.57      www      11519: # ------------------------------------------------------------ request.filename
                   11520:         } else {
1.620     albertel 11521:             return $env{'request.'.$spacequalifierrest};
1.29      www      11522:         }
1.28      www      11523:     } elsif ($realm eq 'course') {
1.48      www      11524: # ---------------------------------------------------------- course.description
1.620     albertel 11525:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11526:     } elsif ($realm eq 'resource') {
1.165     www      11527: 
1.620     albertel 11528: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11529: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11530: 	}
1.693     albertel 11531: 
1.1232    raeburn  11532:         if ($qualifier eq '') {
                   11533: 	    if ($space eq 'title') {
                   11534: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11535: 	        return &gettitle($symbparm);
                   11536: 	    }
1.693     albertel 11537: 	
1.1232    raeburn  11538: 	    if ($space eq 'map') {
                   11539: 	        my ($map) = &decode_symb($symbparm);
                   11540: 	        return &symbread($map);
                   11541: 	    }
                   11542:             if ($space eq 'maptitle') {
                   11543:                 my ($map) = &decode_symb($symbparm);
                   11544:                 return &gettitle($map);
                   11545:             }
                   11546: 	    if ($space eq 'filename') {
                   11547: 	        if ($symbparm) {
                   11548: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11549: 	        }
                   11550: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11551: 	    }
1.1232    raeburn  11552: 
1.1233    raeburn  11553:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11554:                 if ($space eq 'visibleparts') {
                   11555:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11556:                     my $item;
                   11557:                     if (ref($navmap)) {
                   11558:                         my $res = $navmap->getBySymb($symbparm);
                   11559:                         my $parts = $res->parts();
                   11560:                         if (ref($parts) eq 'ARRAY') {
                   11561:                             $item = join(',',@{$parts});
                   11562:                         }
                   11563:                         undef($navmap);
1.1232    raeburn  11564:                     }
1.1233    raeburn  11565:                     return $item;
1.1232    raeburn  11566:                 }
                   11567:             }
                   11568:         }
1.693     albertel 11569: 
1.1301    raeburn  11570: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11571: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11572:         if (($courseid eq '') && ($cid)) {
                   11573:             $courseid = $cid;
                   11574:         }
                   11575: 	if (($symbparm && $courseid) && 
                   11576: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11577: 
1.218     albertel 11578: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11579: 
1.60      www      11580: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11581: 	    my $symbp=$symbparm;
1.1301    raeburn  11582: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11583: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11584:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11585: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11586: 	    if (($env{'user.name'} eq $uname) &&
                   11587: 		($env{'user.domain'} eq $udom)) {
                   11588: 		$section=$env{'request.course.sec'};
1.733     raeburn  11589:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11590:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11591: 	    } else {
1.539     albertel 11592: 		if (! defined($usection)) {
1.551     albertel 11593: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11594: 		} else {
                   11595: 		    $section = $usection;
                   11596: 		}
1.733     raeburn  11597:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11598: 	    }
                   11599: 
                   11600: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11601: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11602:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11603: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11604: 
1.593     albertel 11605: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11606: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11607:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11608: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11609: 
1.60      www      11610: # ----------------------------------------------------------- first, check user
1.624     albertel 11611: 
1.1301    raeburn  11612: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11613:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11614: 				       ([$courselevelr,'resource'],
                   11615: 					[$courselevelm,'map'     ],
1.1301    raeburn  11616:                                         [$courseleveli,'map'     ],
1.927     albertel 11617: 					[$courselevel, 'course'  ]));
1.931     albertel 11618: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11619: 
1.594     albertel 11620: # ------------------------------------------------ second, check some of course
1.684     raeburn  11621:             my $coursereply;
1.691     raeburn  11622:             if (@groups > 0) {
                   11623:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11624:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11625:                                        $mapp,\$recursed,\@recurseup);
                   11626:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11627:             }
1.96      www      11628: 
1.684     raeburn  11629: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11630: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11631: 				  'course',$mapp,\$recursed,\@recurseup,
                   11632:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11633: 				  ([$seclevelr,   'resource'],
                   11634: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11635:                                    [$secleveli,   'map'     ],
1.927     albertel 11636: 				   [$seclevel,    'course'  ],
                   11637: 				   [$courselevelr,'resource']));
                   11638: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11639: 
1.60      www      11640: # ------------------------------------------------------ third, check map parms
1.218     albertel 11641: 	    my %parmhash=();
                   11642: 	    my $thisparm='';
                   11643: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11644: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11645: 		    &GDBM_READER(),0640)) {
1.218     albertel 11646: 		$thisparm=$parmhash{$symbparm};
                   11647: 		untie(%parmhash);
                   11648: 	    }
1.927     albertel 11649: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11650: 	}
1.594     albertel 11651: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11652:  
                   11653:         my $what = $spacequalifierrest;
                   11654: 	$what=~s/\./\_/;
1.282     albertel 11655: 	my $filename;
                   11656: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11657: 	if ($symbparm) {
1.409     www      11658: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11659: 	} else {
1.620     albertel 11660: 	    $filename=$env{'request.filename'};
1.282     albertel 11661: 	}
1.1362    raeburn  11662:         my $toolsymb;
                   11663:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11664:             $toolsymb = $symbparm;
                   11665:         }
                   11666: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11667: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11668: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11669: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11670: 
1.1301    raeburn  11671: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11672: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11673: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11674: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11675: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11676: 				     'course',$mapp,\$recursed,\@recurseup,
                   11677:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11678: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11679:                                       [$courseleveli,'map'   ],
1.927     albertel 11680: 				      [$courselevel, 'course']));
                   11681: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11682: 	}
1.145     www      11683: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11684: 	unless ($space eq '0') {
1.336     albertel 11685: 	    my @parts=split(/_/,$space);
                   11686: 	    my $id=pop(@parts);
                   11687: 	    my $part=join('_',@parts);
                   11688: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11689: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11690: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11691: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11692: 	}
1.395     albertel 11693: 	if ($recurse) { return undef; }
1.1362    raeburn  11694: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11695: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11696: # ---------------------------------------------------- Any other user namespace
                   11697:     } elsif ($realm eq 'environment') {
                   11698: # ----------------------------------------------------------------- environment
1.620     albertel 11699: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11700: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11701: 	} else {
1.770     albertel 11702: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11703: 		return '';
                   11704: 	    }
1.219     albertel 11705: 	    my %returnhash=&userenvironment($udom,$uname,
                   11706: 					    $spacequalifierrest);
                   11707: 	    return $returnhash{$spacequalifierrest};
                   11708: 	}
1.28      www      11709:     } elsif ($realm eq 'system') {
1.48      www      11710: # ----------------------------------------------------------------- system.time
                   11711: 	if ($space eq 'time') {
                   11712: 	    return time;
                   11713:         }
1.696     albertel 11714:     } elsif ($realm eq 'server') {
                   11715: # ----------------------------------------------------------------- system.time
                   11716: 	if ($space eq 'name') {
                   11717: 	    return $ENV{'SERVER_NAME'};
                   11718:         }
1.28      www      11719:     }
1.48      www      11720:     return '';
1.61      www      11721: }
                   11722: 
1.927     albertel 11723: sub get_reply {
                   11724:     my ($reply_value) = @_;
1.940     raeburn  11725:     if (ref($reply_value) eq 'ARRAY') {
                   11726:         if (wantarray) {
                   11727: 	    return @$reply_value;
                   11728:         }
                   11729:         return $reply_value->[0];
                   11730:     } else {
                   11731:         return $reply_value;
1.927     albertel 11732:     }
                   11733: }
                   11734: 
1.691     raeburn  11735: sub check_group_parms {
1.1301    raeburn  11736:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11737:         $recursed,$recurseupref) = @_;
                   11738:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11739:                   [$what,'course']);
                   11740:     my $coursereply;
1.691     raeburn  11741:     foreach my $group (@{$groups}) {
1.1301    raeburn  11742:         my @groupitems = ();
1.691     raeburn  11743:         foreach my $level (@levels) {
1.927     albertel 11744:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11745:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11746:         }
1.1301    raeburn  11747:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11748:                                    $env{'course.'.$courseid.'.domain'},
                   11749:                                    'course',$mapp,$recursed,$recurseupref,
                   11750:                                    $courseid,'.['.$group.'].',$what,
                   11751:                                    @groupitems);
                   11752:         last if (defined($coursereply));
1.691     raeburn  11753:     }
                   11754:     return $coursereply;
                   11755: }
                   11756: 
1.1301    raeburn  11757: sub get_map_hierarchy {
1.1302    raeburn  11758:     my ($mapname,$courseid) = @_;
                   11759:     my @recurseup = ();
1.1301    raeburn  11760:     if ($mapname) {
1.1302    raeburn  11761:         if (($cachedmapkey eq $courseid) &&
                   11762:             (abs($cachedmaptime-time)<5)) {
                   11763:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11764:                 return @{$cachedmaps{$mapname}};
                   11765:             }
                   11766:         }
1.1301    raeburn  11767:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11768:         if (ref($navmap)) {
                   11769:             @recurseup = $navmap->recurseup_maps($mapname);
                   11770:             undef($navmap);
1.1302    raeburn  11771:             $cachedmaps{$mapname} = \@recurseup;
                   11772:             $cachedmaptime=time;
                   11773:             $cachedmapkey=$courseid;
1.1301    raeburn  11774:         }
                   11775:     }
                   11776:     return @recurseup;
                   11777: }
                   11778: 
1.1302    raeburn  11779: }
                   11780: 
1.691     raeburn  11781: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11782:     my ($courseid,@groups) = @_;
                   11783:     @groups = sort(@groups);
1.691     raeburn  11784:     return @groups;
                   11785: }
                   11786: 
1.395     albertel 11787: sub packages_tab_default {
1.1362    raeburn  11788:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11789:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11790: 
                   11791:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11792:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11793: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11794: 	if ($pack_type eq 'default') {
                   11795: 	    $do_default=1;
                   11796: 	} elsif ($pack_type eq 'extension') {
                   11797: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11798: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11799: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11800: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11801: 	}
                   11802:     }
                   11803:     # first look for a package that matches the requested part id
                   11804:     foreach my $package (@specifics) {
                   11805: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11806: 	next if ($pack_part ne $part);
                   11807: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11808: 	    return $packagetab{"$pack_type&$name&default"};
                   11809: 	}
                   11810:     }
                   11811:     # look for any possible matching non extension_ package
                   11812:     foreach my $package (@specifics) {
                   11813: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11814: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11815: 	    return $packagetab{"$pack_type&$name&default"};
                   11816: 	}
1.585     albertel 11817: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11818: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11819: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11820: 	}
                   11821:     }
1.738     albertel 11822:     # look for any posible extension_ match
                   11823:     foreach my $package (@extension) {
                   11824: 	my ($package,$pack_type)=@{$package};
                   11825: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11826: 	    return $packagetab{"$pack_type&$name&default"};
                   11827: 	}
                   11828: 	if (defined($packagetab{$package."&$name&default"})) {
                   11829: 	    return $packagetab{$package."&$name&default"};
                   11830: 	}
                   11831:     }
                   11832:     # look for a global default setting
                   11833:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11834: 	return $packagetab{"default&$name&default"};
                   11835:     }
1.395     albertel 11836:     return undef;
                   11837: }
                   11838: 
1.334     albertel 11839: sub add_prefix_and_part {
                   11840:     my ($prefix,$part)=@_;
                   11841:     my $keyroot;
                   11842:     if (defined($prefix) && $prefix !~ /^__/) {
                   11843: 	# prefix that has a part already
                   11844: 	$keyroot=$prefix;
                   11845:     } elsif (defined($prefix)) {
                   11846: 	# prefix that is missing a part
                   11847: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11848:     } else {
                   11849: 	# no prefix at all
                   11850: 	if (defined($part)) { $keyroot='_'.$part; }
                   11851:     }
                   11852:     return $keyroot;
                   11853: }
                   11854: 
1.71      www      11855: # ---------------------------------------------------------------- Get metadata
                   11856: 
1.599     albertel 11857: my %metaentry;
1.1070    www      11858: my %importedpartids;
1.1369    raeburn  11859: my %importedrespids;
1.71      www      11860: sub metadata {
1.1362    raeburn  11861:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11862:     $uri=&declutter($uri);
1.288     albertel 11863:     # if it is a non metadata possible uri return quickly
1.529     albertel 11864:     if (($uri eq '') || 
                   11865: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11866: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11867:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11868: 	return undef;
                   11869:     }
1.1261    raeburn  11870:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11871: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11872: 	return undef;
1.288     albertel 11873:     }
1.73      www      11874:     my $filename=$uri;
                   11875:     $uri=~s/\.meta$//;
1.172     www      11876: #
                   11877: # Is the metadata already cached?
1.177     www      11878: # Look at timestamp of caching
1.172     www      11879: # Everything is cached by the main uri, libraries are never directly cached
                   11880: #
1.428     albertel 11881:     if (!defined($liburi)) {
1.599     albertel 11882: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11883: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11884:     }
1.1362    raeburn  11885: 
                   11886: #
                   11887: # If the uri is for an external tool the file from
                   11888: # which metadata should be retrieved depends on whether
                   11889: # the tool had been configured to be gradable (set in the Course
                   11890: # Editor or Resource Editor).
                   11891: #
                   11892: # If a valid symb has been included as the third arg in the call
                   11893: # to &metadata() that can be used to retrieve the value of
                   11894: # parameter_0_gradable set for the resource, and included in the
                   11895: # uploaded map containing the tool. The value is retrieved via
                   11896: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11897: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11898: # is retrieved via &get().
                   11899: #
                   11900: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11901: # hiddenresource and encrypturl (during course initialization)
                   11902: # the map-level parameter for resource.0.gradable included in the 
                   11903: # uploaded map containing the tool will not yet have been stored
                   11904: # in the user_course_parms.db file for the user's session, so in 
                   11905: # this case fall back to retrieving gradable status from the
                   11906: # exttool_$marker.db file.
1.1362    raeburn  11907: #
                   11908: # In order to avoid an infinite loop, &metadata() will return
                   11909: # before a call to &EXT(), if the uri is for an external tool
                   11910: # and the $what for which metadata is being requested is
                   11911: # parameter_0_gradable or 0_gradable.
                   11912: #
                   11913: 
                   11914:     if ($uri =~ /ext\.tool$/) {
                   11915:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11916:             return;
                   11917:         } else {
                   11918:             my ($checked,$use_passback);
                   11919:             if ($toolsymb ne '') {
                   11920:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11921:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11922:                     $checked = 1;
                   11923:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11924:                         $use_passback = 1;
                   11925:                     }
                   11926:                 }
                   11927:             }
                   11928:             unless ($checked) {
                   11929:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11930:                 $marker=~s/\D//g;
1.1363    raeburn  11931:                 if ($marker) {
1.1362    raeburn  11932:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11933:                     $use_passback = $toolsettings{'gradable'};
                   11934:                 }
                   11935:             }
                   11936:             if ($use_passback) {
                   11937:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11938:             } else {
                   11939:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11940:             }
                   11941:         }
                   11942:     }
                   11943: 
1.428     albertel 11944:     {
1.1069    www      11945: # Imported parts would go here
1.1369    raeburn  11946:         my @origfiletagids=();
1.1069    www      11947:         my $importedparts=0;
1.1369    raeburn  11948: 
                   11949: # Imported responseids would go here
                   11950:         my $importedresponses=0;
1.172     www      11951: #
                   11952: # Is this a recursive call for a library?
                   11953: #
1.599     albertel 11954: #	if (! exists($metacache{$uri})) {
                   11955: #	    $metacache{$uri}={};
                   11956: #	}
1.924     albertel 11957: 	my $cachetime = 60*60;
1.171     www      11958:         if ($liburi) {
                   11959: 	    $liburi=&declutter($liburi);
                   11960:             $filename=$liburi;
1.401     bowersj2 11961:         } else {
1.599     albertel 11962: 	    &devalidate_cache_new('meta',$uri);
                   11963: 	    undef(%metaentry);
1.401     bowersj2 11964: 	}
1.140     www      11965:         my %metathesekeys=();
1.73      www      11966:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11967: 	my $metastring;
1.1140    www      11968: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11969: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11970: 	    $metastring = 
1.929     albertel 11971: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11972: 					  ('grade_target' => 'meta'));
                   11973: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11974: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11975:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11976: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11977: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11978: 	    $metastring=&getfile($file);
1.489     albertel 11979: 	}
1.208     albertel 11980:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11981:         my $token;
1.140     www      11982:         undef %metathesekeys;
1.71      www      11983:         while ($token=$parser->get_token) {
1.339     albertel 11984: 	    if ($token->[0] eq 'S') {
                   11985: 		if (defined($token->[2]->{'package'})) {
1.172     www      11986: #
                   11987: # This is a package - get package info
                   11988: #
1.339     albertel 11989: 		    my $package=$token->[2]->{'package'};
                   11990: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11991: 		    if (defined($token->[2]->{'id'})) { 
                   11992: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11993: 		    }
1.599     albertel 11994: 		    if ($metaentry{':packages'}) {
                   11995: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11996: 		    } else {
1.599     albertel 11997: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11998: 		    }
1.736     albertel 11999: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12000: 			my $part=$keyroot;
                   12001: 			$part=~s/^\_//;
1.736     albertel 12002: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12003: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12004: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12005: 			    # ignore package.tab specified default values
                   12006:                             # here &package_tab_default() will fetch those
                   12007: 			    if ($subp eq 'default') { next; }
1.736     albertel 12008: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12009: 			    my $unikey;
                   12010: 			    if ($pack =~ /_0$/) {
                   12011: 				$unikey='parameter_0_'.$name;
                   12012: 				$part=0;
                   12013: 			    } else {
                   12014: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12015: 			    }
1.339     albertel 12016: 			    if ($subp eq 'display') {
                   12017: 				$value.=' [Part: '.$part.']';
                   12018: 			    }
1.599     albertel 12019: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12020: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12021: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12022: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12023: 			    }
1.599     albertel 12024: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12025: 				$metaentry{':'.$unikey}=
                   12026: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12027: 			    }
1.339     albertel 12028: 			}
                   12029: 		    }
                   12030: 		} else {
1.172     www      12031: #
                   12032: # This is not a package - some other kind of start tag
1.339     albertel 12033: #
                   12034: 		    my $entry=$token->[1];
1.1068    www      12035: 		    my $unikey='';
1.175     www      12036: 
1.339     albertel 12037: 		    if ($entry eq 'import') {
1.175     www      12038: #
                   12039: # Importing a library here
1.339     albertel 12040: #
1.1067    www      12041:                         my $location=$parser->get_text('/import');
                   12042:                         my $dir=$filename;
                   12043:                         $dir=~s|[^/]*$||;
                   12044:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12045: 
                   12046:                         my $importid=$token->[2]->{'id'};
1.1068    www      12047:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12048: #
                   12049: # Check metadata for imported file to
                   12050: # see if it contained response items
                   12051: #
1.1372    raeburn  12052:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12053:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12054:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12055:                                                            $depthcount+1));
                   12056:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12057:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12058:                                                              undef,$depthcount+1);
                   12059:                             if ($libresponseorder ne '') {
                   12060:                                 if ($#origfiletagids<0) {
                   12061:                                     undef(%importedrespids);
                   12062:                                     undef(%importedpartids);
                   12063:                                 }
1.1373    raeburn  12064:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12065:                                 if (@respids) {
                   12066:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12067:                                 }
                   12068:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12069:                                     $importedresponses = 1;
1.1369    raeburn  12070: # We need to get the original file and the imported file to get the response order correct
                   12071: # Load and inspect original file
1.1372    raeburn  12072:                                     if ($#origfiletagids<0) {
                   12073:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12074:                                         $origfile=&getfile($origfilelocation);
                   12075:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12076:                                     }
1.1369    raeburn  12077:                                 }
                   12078:                             }
                   12079:                         }
1.1370    raeburn  12080: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12081: # hash populated for imported library file
                   12082:                         %metaentry = %currmetaentry;
                   12083:                         undef(%currmetaentry);
1.1374    raeburn  12084:                         if ($importmode eq 'part') {
1.1068    www      12085: # Import as part(s)
1.1069    www      12086:                            $importedparts=1;
                   12087: # We need to get the original file and the imported file to get the part order correct
                   12088: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12089: # Load and inspect original file if we didn't do that already
                   12090:                            if ($#origfiletagids<0) {
                   12091:                                undef(%importedrespids);
                   12092:                                undef(%importedpartids);
                   12093:                                if ($origfile eq '') {
                   12094:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12095:                                    $origfile=&getfile($origfilelocation);
                   12096:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12097:                                }
1.1070    www      12098:                            }
1.1372    raeburn  12099:                            my @impfilepartids;
                   12100: # If <partorder> tag is included in metadata for the imported file
                   12101: # get the parts in the imported file from that.
                   12102:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12103:                                %currmetaentry = %metaentry;
                   12104:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12105:                                                             $depthcount+1);
                   12106:                                %metaentry = %currmetaentry;
                   12107:                                undef(%currmetaentry);
                   12108:                                if ($libpartorder ne '') {
                   12109:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12110:                                }
                   12111:                            } else {
                   12112: # If no <partorder> tag available, load and inspect imported file
                   12113:                                my $impfile=&getfile($location);
                   12114:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12115:                            }
1.1069    www      12116:                            if ($#impfilepartids>=0) {
                   12117: # This problem had parts
1.1070    www      12118:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12119:                            } else {
                   12120: # Importing by turning a single problem into a problem part
                   12121: # It gets the import-tags ID as part-ID
                   12122:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12123:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12124:                            }
1.1068    www      12125:                         } else {
1.1374    raeburn  12126: # Import as problem or as normal import
                   12127:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12128:                             unless ($importmode eq 'problem') {
1.1068    www      12129: # Normal import
1.1374    raeburn  12130:                                 if (defined($token->[2]->{'id'})) {
                   12131:                                     $unikey.='_'.$token->[2]->{'id'};
                   12132:                                 }
                   12133:                             }
                   12134: # Check metadata for imported file to
                   12135: # see if it contained parts
                   12136:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12137:                                 %currmetaentry = %metaentry;
                   12138:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12139:                                                              $depthcount+1);
                   12140:                                 %metaentry = %currmetaentry;
                   12141:                                 undef(%currmetaentry);
                   12142:                                 if ($libpartorder ne '') {
                   12143:                                     $importedparts = 1;
                   12144:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12145:                                 }
                   12146:                             }
1.1067    www      12147:                         }
1.339     albertel 12148: 			if ($depthcount<20) {
1.736     albertel 12149: 			    my $metadata = 
1.1362    raeburn  12150: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12151: 					  $depthcount+1);
                   12152: 			    foreach my $meta (split(',',$metadata)) {
                   12153: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12154: 				$metathesekeys{$meta}=1;
1.339     albertel 12155: 			    }
1.1068    www      12156:                         }
1.1067    www      12157: 		    } else {
                   12158: #
                   12159: # Not importing, some other kind of non-package, non-library start tag
                   12160: # 
                   12161:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12162:                         if (defined($token->[2]->{'id'})) {
                   12163:                             $unikey.='_'.$token->[2]->{'id'};
                   12164:                         }
1.339     albertel 12165: 			if (defined($token->[2]->{'name'})) { 
                   12166: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12167: 			}
                   12168: 			$metathesekeys{$unikey}=1;
1.736     albertel 12169: 			foreach my $param (@{$token->[3]}) {
                   12170: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12171: 				$token->[2]->{$param};
1.339     albertel 12172: 			}
                   12173: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12174: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12175: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12176: 		 # only ws inside the tag, and not in default, so use default
                   12177: 		 # as value
1.599     albertel 12178: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12179: 			} elsif ( $internaltext =~ /\S/ ) {
                   12180: 		  # something interesting inside the tag
                   12181: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12182: 			} else {
1.908     albertel 12183: 		  # no interesting values, don't set a default
1.339     albertel 12184: 			}
1.172     www      12185: # end of not-a-package not-a-library import
1.339     albertel 12186: 		    }
1.172     www      12187: # end of not-a-package start tag
1.339     albertel 12188: 		}
1.172     www      12189: # the next is the end of "start tag"
1.339     albertel 12190: 	    }
                   12191: 	}
1.483     albertel 12192: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12193: 	$extension = lc($extension);
                   12194: 	if ($extension eq 'htm') { $extension='html'; }
                   12195: 
1.737     albertel 12196: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12197: 	    #no specific packages #how's our extension
                   12198: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12199: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12200: 					 \%metathesekeys);
                   12201: 	}
1.883     albertel 12202: 
                   12203: 	if (!exists($metaentry{':packages'})
                   12204: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12205: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12206: 		#no specific packages well let's get default then
                   12207: 		if ($key!~/^default&/) { next; }
1.488     albertel 12208: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12209: 					     \%metathesekeys);
                   12210: 	    }
                   12211: 	}
1.338     www      12212: # are there custom rights to evaluate
1.599     albertel 12213: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12214: 
1.338     www      12215:     #
                   12216:     # Importing a rights file here
1.339     albertel 12217:     #
                   12218: 	    unless ($depthcount) {
1.599     albertel 12219: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12220: 		my $dir=$filename;
                   12221: 		$dir=~s|[^/]*$||;
                   12222: 		$location=&filelocation($dir,$location);
1.736     albertel 12223: 		my $rights_metadata =
1.1362    raeburn  12224: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12225: 			      $depthcount+1);
                   12226: 		foreach my $rights (split(',',$rights_metadata)) {
                   12227: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12228: 		    $metathesekeys{$rights}=1;
1.339     albertel 12229: 		}
                   12230: 	    }
                   12231: 	}
1.737     albertel 12232: 	# uniqifiy package listing
                   12233: 	my %seen;
                   12234: 	my @uniq_packages =
                   12235: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12236: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12237: 
1.1369    raeburn  12238:         if (($importedresponses) || ($importedparts)) {
                   12239:             if ($importedparts) {
1.1070    www      12240: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12241:                 $metaentry{':partorder'}='';
                   12242:                 $metathesekeys{'partorder'}=1;
                   12243:             }
                   12244:             if ($importedresponses) {
                   12245: # We had imported responses and need to rebuil responseorder
                   12246:                 $metaentry{':responseorder'}='';
                   12247:                 $metathesekeys{'responseorder'}=1;
                   12248:             }
                   12249:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12250:                 my $origid = $origfiletagids[$index+1];
                   12251:                 if ($origfiletagids[$index] eq 'part') {
                   12252: # Original part, part of the problem
                   12253:                     if ($importedparts) {
                   12254:                         $metaentry{':partorder'}.=','.$origid;
                   12255:                     }
                   12256:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12257:                     if ($importedparts) {
                   12258: # We have imported parts at this position
1.1373    raeburn  12259:                         if ($importedpartids{$origid} ne '') {
                   12260:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12261:                         }
1.1369    raeburn  12262:                     }
                   12263:                     if ($importedresponses) {
                   12264: # We have imported responses at this position
1.1373    raeburn  12265:                         if ($importedrespids{$origid} ne '') {
                   12266:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12267:                         }
                   12268:                     }
                   12269:                 } else {
                   12270: # Original response item, part of the problem
                   12271:                     if ($importedresponses) {
                   12272:                         $metaentry{':responseorder'}.=','.$origid;
                   12273:                     }
                   12274:                 }
                   12275:             }
                   12276:             if ($importedparts) {
                   12277:                 $metaentry{':partorder'}=~s/^\,//;
                   12278:             }
                   12279:             if ($importedresponses) {
                   12280:                 $metaentry{':responseorder'}=~s/^\,//;
                   12281:             }
1.1070    www      12282:         }
1.737     albertel 12283: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12284: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12285: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12286:         unless ($liburi) {
                   12287: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12288:         }
1.177     www      12289: # this is the end of "was not already recently cached
1.71      www      12290:     }
1.599     albertel 12291:     return $metaentry{':'.$what};
1.261     albertel 12292: }
                   12293: 
1.488     albertel 12294: sub metadata_create_package_def {
1.483     albertel 12295:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12296:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12297:     if ($subp eq 'default') { next; }
                   12298:     
1.599     albertel 12299:     if (defined($metaentry{':packages'})) {
                   12300: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12301:     } else {
1.599     albertel 12302: 	$metaentry{':packages'}=$package;
1.483     albertel 12303:     }
                   12304:     my $value=$packagetab{$key};
                   12305:     my $unikey;
                   12306:     $unikey='parameter_0_'.$name;
1.599     albertel 12307:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12308:     $$metathesekeys{$unikey}=1;
1.599     albertel 12309:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12310: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12311:     }
1.599     albertel 12312:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12313: 	$metaentry{':'.$unikey}=
                   12314: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12315:     }
                   12316: }
                   12317: 
1.261     albertel 12318: sub metadata_generate_part0 {
                   12319:     my ($metadata,$metacache,$uri) = @_;
                   12320:     my %allnames;
1.737     albertel 12321:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12322: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12323: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12324: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12325: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12326: 	    $allnames{$name}=$part;
                   12327: 	  }
                   12328: 	}
                   12329:     }
                   12330:     foreach my $name (keys(%allnames)) {
                   12331:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12332:       my $key=":parameter_0_$name";
1.261     albertel 12333:       $$metacache{"$key.part"}='0';
                   12334:       $$metacache{"$key.name"}=$name;
1.428     albertel 12335:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12336: 					   $allnames{$name}.'_'.$name.
                   12337: 					   '.type'};
1.428     albertel 12338:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12339: 			     '.display'};
1.644     www      12340:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12341:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12342:       $$metacache{"$key.display"}=$olddis;
                   12343:     }
1.71      www      12344: }
                   12345: 
1.764     albertel 12346: # ------------------------------------------------------ Devalidate title cache
                   12347: 
                   12348: sub devalidate_title_cache {
                   12349:     my ($url)=@_;
                   12350:     if (!$env{'request.course.id'}) { return; }
                   12351:     my $symb=&symbread($url);
                   12352:     if (!$symb) { return; }
                   12353:     my $key=$env{'request.course.id'}."\0".$symb;
                   12354:     &devalidate_cache_new('title',$key);
                   12355: }
                   12356: 
1.1014    droeschl 12357: # ------------------------------------------------- Get the title of a course
                   12358: 
                   12359: sub current_course_title {
                   12360:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12361: }
1.301     www      12362: # ------------------------------------------------- Get the title of a resource
                   12363: 
                   12364: sub gettitle {
                   12365:     my $urlsymb=shift;
                   12366:     my $symb=&symbread($urlsymb);
1.534     albertel 12367:     if ($symb) {
1.620     albertel 12368: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12369: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12370: 	if (defined($cached)) { 
                   12371: 	    return $result;
                   12372: 	}
1.534     albertel 12373: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12374: 	my $title='';
1.907     albertel 12375: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12376: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12377: 	} else {
                   12378: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12379: 		    &GDBM_READER(),0640)) {
                   12380: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12381: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12382: 		untie(%bighash);
                   12383: 	    }
1.534     albertel 12384: 	}
                   12385: 	$title=~s/\&colon\;/\:/gs;
                   12386: 	if ($title) {
1.1159    www      12387: # Remember both $symb and $title for dynamic metadata
                   12388:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12389:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12390: # Cache this title and then return it
1.599     albertel 12391: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12392: 	}
                   12393: 	$urlsymb=$url;
                   12394:     }
                   12395:     my $title=&metadata($urlsymb,'title');
                   12396:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12397:     return $title;
1.301     www      12398: }
1.613     albertel 12399: 
1.614     albertel 12400: sub get_slot {
                   12401:     my ($which,$cnum,$cdom)=@_;
                   12402:     if (!$cnum || !$cdom) {
1.790     albertel 12403: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12404: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12405: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12406:     }
1.703     albertel 12407:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12408:     my %slotinfo;
                   12409:     if (exists($remembered{$key})) {
                   12410: 	$slotinfo{$which} = $remembered{$key};
                   12411:     } else {
                   12412: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12413: 	&Apache::lonhomework::showhash(%slotinfo);
                   12414: 	my ($tmp)=keys(%slotinfo);
                   12415: 	if ($tmp=~/^error:/) { return (); }
                   12416: 	$remembered{$key} = $slotinfo{$which};
                   12417:     }
1.616     albertel 12418:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12419: 	return %{$slotinfo{$which}};
                   12420:     }
                   12421:     return $slotinfo{$which};
1.614     albertel 12422: }
1.1150    raeburn  12423: 
                   12424: sub get_reservable_slots {
                   12425:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12426:     my $now = time;
                   12427:     my $reservable_info;
                   12428:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12429:     if (exists($remembered{$key})) {
                   12430:         $reservable_info = $remembered{$key};
                   12431:     } else {
                   12432:         my %resv;
                   12433:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12434:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12435:         $reservable_info = \%resv;
                   12436:         $remembered{$key} = $reservable_info;
                   12437:     }
                   12438:     return $reservable_info;
                   12439: }
                   12440: 
                   12441: sub get_course_slots {
                   12442:     my ($cnum,$cdom) = @_;
                   12443:     my $hashid=$cnum.':'.$cdom;
                   12444:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12445:     if (defined($cached)) {
                   12446:         if (ref($result) eq 'HASH') {
                   12447:             return %{$result};
                   12448:         }
                   12449:     } else {
                   12450:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12451:         my ($tmp) = keys(%slots);
                   12452:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12453:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12454:             return %slots;
                   12455:         }
                   12456:     }
                   12457:     return;
                   12458: }
                   12459: 
                   12460: sub devalidate_slots_cache {
                   12461:     my ($cnum,$cdom)=@_;
                   12462:     my $hashid=$cnum.':'.$cdom;
                   12463:     &devalidate_cache_new('allslots',$hashid);
                   12464: }
                   12465: 
1.1181    raeburn  12466: sub get_coursechange {
                   12467:     my ($cdom,$cnum) = @_;
                   12468:     if ($cdom eq '' || $cnum eq '') {
                   12469:         return unless ($env{'request.course.id'});
                   12470:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12471:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12472:     }
                   12473:     my $hashid=$cdom.'_'.$cnum;
                   12474:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12475:     if ((defined($cached)) && ($change ne '')) {
                   12476:         return $change;
                   12477:     } else {
                   12478:         my %crshash;
                   12479:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12480:         if ($crshash{'internal.contentchange'} eq '') {
                   12481:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12482:             if ($change eq '') {
                   12483:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12484:                 $change = $crshash{'internal.created'};
                   12485:             }
                   12486:         } else {
                   12487:             $change = $crshash{'internal.contentchange'};
                   12488:         }
                   12489:         my $cachetime = 600;
                   12490:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12491:     }
                   12492:     return $change;
                   12493: }
                   12494: 
                   12495: sub devalidate_coursechange_cache {
                   12496:     my ($cnum,$cdom)=@_;
                   12497:     my $hashid=$cnum.':'.$cdom;
                   12498:     &devalidate_cache_new('crschange',$hashid);
                   12499: }
                   12500: 
1.31      www      12501: # ------------------------------------------------- Update symbolic store links
                   12502: 
                   12503: sub symblist {
                   12504:     my ($mapname,%newhash)=@_;
1.438     www      12505:     $mapname=&deversion(&declutter($mapname));
1.31      www      12506:     my %hash;
1.620     albertel 12507:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12508:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12509:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12510: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12511: 		next if ($url eq 'last_known'
                   12512: 			 && $env{'form.no_update_last_known'});
                   12513: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12514: 						    $newhash{$url}->[1],
                   12515: 						    $newhash{$url}->[0]);
1.191     harris41 12516:             }
1.31      www      12517:             if (untie(%hash)) {
                   12518: 		return 'ok';
                   12519:             }
                   12520:         }
                   12521:     }
                   12522:     return 'error';
1.212     www      12523: }
                   12524: 
                   12525: # --------------------------------------------------------------- Verify a symb
                   12526: 
                   12527: sub symbverify {
1.1190    raeburn  12528:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12529:     my $thisfn=$thisurl;
1.439     www      12530:     $thisfn=&declutter($thisfn);
1.215     www      12531: # direct jump to resource in page or to a sequence - will construct own symbs
                   12532:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12533: # check URL part
1.409     www      12534:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12535: 
1.431     www      12536:     unless ($url eq $thisfn) { return 0; }
1.213     www      12537: 
1.216     www      12538:     $symb=&symbclean($symb);
1.510     www      12539:     $thisurl=&deversion($thisurl);
1.439     www      12540:     $thisfn=&deversion($thisfn);
1.213     www      12541: 
                   12542:     my %bighash;
                   12543:     my $okay=0;
1.431     www      12544: 
1.620     albertel 12545:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12546:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12547:         my $noclutter;
1.1032    raeburn  12548:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12549:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12550:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12551:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12552:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12553:                 $noclutter = 1;
                   12554:             }
                   12555:         }
                   12556:         my $ids;
                   12557:         if ($noclutter) {
                   12558:             $ids=$bighash{'ids_'.$thisurl};
                   12559:         } else {
                   12560:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12561:         }
1.1102    raeburn  12562:         unless ($ids) {
                   12563:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12564:             $ids=$bighash{$idkey};
1.216     www      12565:         }
                   12566:         if ($ids) {
                   12567: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12568:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12569:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12570:             }
1.800     albertel 12571: 	    foreach my $id (split(/\,/,$ids)) {
                   12572: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12573:                if (
                   12574:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12575:    eq $symb) {
                   12576:                    if (ref($encstate)) {
                   12577:                        $$encstate = $bighash{'encrypted_'.$id};
                   12578:                    }
1.620     albertel 12579: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12580: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12581:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12582: 		       $okay=1;
1.1202    raeburn  12583:                        last;
1.582     albertel 12584: 		   }
                   12585: 	       }
1.216     www      12586: 	   }
                   12587:         }
1.213     www      12588: 	untie(%bighash);
                   12589:     }
                   12590:     return $okay;
1.31      www      12591: }
                   12592: 
1.210     www      12593: # --------------------------------------------------------------- Clean-up symb
                   12594: 
                   12595: sub symbclean {
                   12596:     my $symb=shift;
1.568     albertel 12597:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12598: # remove version from map
                   12599:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12600: 
1.210     www      12601: # remove version from URL
                   12602:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12603: 
1.507     www      12604: # remove wrapper
                   12605: 
1.510     www      12606:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12607:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12608:     return $symb;
1.409     www      12609: }
                   12610: 
                   12611: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12612: 
                   12613: sub encode_symb {
                   12614:     my ($map,$resid,$url)=@_;
                   12615:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12616: }
1.409     www      12617: 
                   12618: sub decode_symb {
1.568     albertel 12619:     my $symb=shift;
                   12620:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12621:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12622:     return (&fixversion($map),$resid,&fixversion($url));
                   12623: }
                   12624: 
                   12625: sub fixversion {
                   12626:     my $fn=shift;
1.609     banghart 12627:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12628:     my %bighash;
                   12629:     my $uri=&clutter($fn);
1.620     albertel 12630:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12631: # is this cached?
1.599     albertel 12632:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12633:     if (defined($cached)) { return $result; }
                   12634: # unfortunately not cached, or expired
1.620     albertel 12635:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12636: 	    &GDBM_READER(),0640)) {
                   12637:  	if ($bighash{'version_'.$uri}) {
                   12638:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12639:  	    unless (($version eq 'mostrecent') || 
                   12640: 		    ($version==&getversion($uri))) {
1.440     www      12641:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12642:  	    }
                   12643:  	}
                   12644:  	untie %bighash;
1.413     www      12645:     }
1.599     albertel 12646:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12647: }
                   12648: 
                   12649: sub deversion {
                   12650:     my $url=shift;
                   12651:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12652:     return $url;
1.210     www      12653: }
                   12654: 
1.31      www      12655: # ------------------------------------------------------ Return symb list entry
                   12656: 
                   12657: sub symbread {
1.1282    raeburn  12658:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12659:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12660:     if (defined($env{$cache_str})) {
                   12661:         if ($ignorecachednull) {
                   12662:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12663:         } else {
                   12664:             return $env{$cache_str};
                   12665:         }
                   12666:     }
1.242     www      12667: # no filename provided? try from environment
1.1265    raeburn  12668:     unless ($thisfn) {
1.620     albertel 12669:         if ($env{'request.symb'}) {
                   12670: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12671: 	}
1.620     albertel 12672: 	$thisfn=$env{'request.filename'};
1.44      www      12673:     }
1.569     albertel 12674:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12675: # is that filename actually a symb? Verify, clean, and return
                   12676:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12677: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12678: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12679: 	}
1.242     www      12680:     }
1.44      www      12681:     $thisfn=declutter($thisfn);
1.31      www      12682:     my %hash;
1.37      www      12683:     my %bighash;
                   12684:     my $syval='';
1.620     albertel 12685:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12686:         my $targetfn = $thisfn;
1.609     banghart 12687:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12688:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12689:         }
1.687     albertel 12690: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12691: 	    $targetfn=$1;
                   12692: 	}
1.620     albertel 12693:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12694:                       &GDBM_READER(),0640)) {
1.481     raeburn  12695: 	    $syval=$hash{$targetfn};
1.37      www      12696:             untie(%hash);
                   12697:         }
                   12698: # ---------------------------------------------------------- There was an entry
                   12699:         if ($syval) {
1.601     albertel 12700: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12701: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12702: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12703: 		    #return $env{$cache_str}='';
1.601     albertel 12704: 		#}    
                   12705: 		#$syval.=$1;
                   12706: 	    #}
1.37      www      12707:         } else {
                   12708: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12709:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12710:                             &GDBM_READER(),0640)) {
1.37      www      12711: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12712:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12713:               unless ($ids) { 
                   12714:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12715:               }
                   12716:               unless ($ids) {
                   12717: # alias?
                   12718: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12719:               }
1.37      www      12720:               if ($ids) {
                   12721: # ------------------------------------------------------------------- Has ID(s)
                   12722:                  my @possibilities=split(/\,/,$ids);
1.39      www      12723:                  if ($#possibilities==0) {
                   12724: # ----------------------------------------------- There is only one possibility
1.37      www      12725: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12726: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12727: 						    $resid,$thisfn);
1.1282    raeburn  12728:                      if (ref($possibles) eq 'HASH') {
                   12729:                          $possibles->{$syval} = 1;    
                   12730:                      }
                   12731:                      if ($checkforblock) {
                   12732:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12733:                          if (@blockers) {
                   12734:                              $syval = '';
                   12735:                              return;
                   12736:                          }
                   12737:                      }
                   12738:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12739: # ------------------------------------------ There is more than one possibility
                   12740:                      my $realpossible=0;
1.800     albertel 12741:                      foreach my $id (@possibilities) {
                   12742: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12743:                          my $canaccess;
                   12744:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12745:                              $canaccess = 1;
                   12746:                          } else { 
                   12747:                              $canaccess = &allowed('bre',$file);
                   12748:                          }
                   12749:                          if ($canaccess) {
                   12750:          		     my ($mapid,$resid)=split(/\./,$id);
                   12751:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12752:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12753: 						             $resid,$thisfn);
                   12754:                                  if (ref($possibles) eq 'HASH') {
                   12755:                                      $possibles->{$syval} = 1;
                   12756:                                  }
                   12757:                                  if ($checkforblock) {
                   12758:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12759:                                      unless (@blockers > 0) {
                   12760:                                          $syval = $poss_syval;
                   12761:                                          $realpossible++;
                   12762:                                      }
                   12763:                                  } else {
                   12764:                                      $syval = $poss_syval;
                   12765:                                      $realpossible++;
                   12766:                                  }
                   12767:                              }
1.39      www      12768: 			 }
1.191     harris41 12769:                      }
1.39      www      12770: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12771:                  } else {
                   12772:                      $syval='';
1.37      www      12773:                  }
                   12774: 	      }
1.1282    raeburn  12775:               untie(%bighash);
1.481     raeburn  12776:            }
1.31      www      12777:         }
1.62      www      12778:         if ($syval) {
1.620     albertel 12779: 	    return $env{$cache_str}=$syval;
1.62      www      12780:         }
1.31      www      12781:     }
1.949     raeburn  12782:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12783:     return $env{$cache_str}='';
1.31      www      12784: }
                   12785: 
                   12786: # ---------------------------------------------------------- Return random seed
                   12787: 
1.32      www      12788: sub numval {
                   12789:     my $txt=shift;
                   12790:     $txt=~tr/A-J/0-9/;
                   12791:     $txt=~tr/a-j/0-9/;
                   12792:     $txt=~tr/K-T/0-9/;
                   12793:     $txt=~tr/k-t/0-9/;
                   12794:     $txt=~tr/U-Z/0-5/;
                   12795:     $txt=~tr/u-z/0-5/;
                   12796:     $txt=~s/\D//g;
1.564     albertel 12797:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12798:     return int($txt);
1.368     albertel 12799: }
                   12800: 
1.484     albertel 12801: sub numval2 {
                   12802:     my $txt=shift;
                   12803:     $txt=~tr/A-J/0-9/;
                   12804:     $txt=~tr/a-j/0-9/;
                   12805:     $txt=~tr/K-T/0-9/;
                   12806:     $txt=~tr/k-t/0-9/;
                   12807:     $txt=~tr/U-Z/0-5/;
                   12808:     $txt=~tr/u-z/0-5/;
                   12809:     $txt=~s/\D//g;
                   12810:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12811:     my $total;
                   12812:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12813:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12814:     return int($total);
                   12815: }
                   12816: 
1.575     albertel 12817: sub numval3 {
                   12818:     use integer;
                   12819:     my $txt=shift;
                   12820:     $txt=~tr/A-J/0-9/;
                   12821:     $txt=~tr/a-j/0-9/;
                   12822:     $txt=~tr/K-T/0-9/;
                   12823:     $txt=~tr/k-t/0-9/;
                   12824:     $txt=~tr/U-Z/0-5/;
                   12825:     $txt=~tr/u-z/0-5/;
                   12826:     $txt=~s/\D//g;
                   12827:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12828:     my $total;
                   12829:     foreach my $val (@txts) { $total+=$val; }
                   12830:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12831:     return $total;
                   12832: }
                   12833: 
1.675     albertel 12834: sub digest {
                   12835:     my ($data)=@_;
                   12836:     my $digest=&Digest::MD5::md5($data);
                   12837:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12838:     my ($e,$f);
                   12839:     {
                   12840:         use integer;
                   12841:         $e=($a+$b);
                   12842:         $f=($c+$d);
                   12843:         if ($_64bit) {
                   12844:             $e=(($e<<32)>>32);
                   12845:             $f=(($f<<32)>>32);
                   12846:         }
                   12847:     }
                   12848:     if (wantarray) {
                   12849: 	return ($e,$f);
                   12850:     } else {
                   12851: 	my $g;
                   12852: 	{
                   12853: 	    use integer;
                   12854: 	    $g=($e+$f);
                   12855: 	    if ($_64bit) {
                   12856: 		$g=(($g<<32)>>32);
                   12857: 	    }
                   12858: 	}
                   12859: 	return $g;
                   12860:     }
                   12861: }
                   12862: 
1.368     albertel 12863: sub latest_rnd_algorithm_id {
1.675     albertel 12864:     return '64bit5';
1.366     albertel 12865: }
1.32      www      12866: 
1.503     albertel 12867: sub get_rand_alg {
                   12868:     my ($courseid)=@_;
1.790     albertel 12869:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12870:     if ($courseid) {
1.620     albertel 12871: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12872:     }
                   12873:     return &latest_rnd_algorithm_id();
                   12874: }
                   12875: 
1.562     albertel 12876: sub validCODE {
                   12877:     my ($CODE)=@_;
                   12878:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12879:     return 0;
                   12880: }
                   12881: 
1.491     albertel 12882: sub getCODE {
1.620     albertel 12883:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12884:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12885: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12886: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12887: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12888:     }
                   12889:     return undef;
                   12890: }
1.1133    foxr     12891: #
                   12892: #  Determines the random seed for a specific context:
                   12893: #
                   12894: # parameters:
                   12895: #   symb      - in course context the symb for the seed.
                   12896: #   course_id - The course id of the form domain_coursenum.
                   12897: #   domain    - Domain for the user.
                   12898: #   course    - Course for the user.
                   12899: #   cenv      - environment of the course.
                   12900: #
                   12901: # NOTE:
                   12902: #   All parameters are picked out of the environment if missing
                   12903: #   or not defined.
                   12904: #   If a symb cannot be determined the current time is used instead.
                   12905: #
                   12906: #  For a given well defined symb, courside, domain, username,
                   12907: #  and course environment, the seed is reproducible.
                   12908: #
1.31      www      12909: sub rndseed {
1.1133    foxr     12910:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12911:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12912:     if (!defined($symb)) {
1.366     albertel 12913: 	unless ($symb=$wsymb) { return time; }
                   12914:     }
1.1146    foxr     12915:     if (!defined $courseid) { 
                   12916: 	$courseid=$wcourseid; 
                   12917:     }
                   12918:     if (!defined $domain) { $domain=$wdomain; }
                   12919:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12920: 
                   12921:     my $which;
                   12922:     if (defined($cenv->{'rndseed'})) {
                   12923: 	$which = $cenv->{'rndseed'};
                   12924:     } else {
                   12925: 	$which =&get_rand_alg($courseid);
                   12926:     }
1.491     albertel 12927:     if (defined(&getCODE())) {
1.1133    foxr     12928: 
1.675     albertel 12929: 	if ($which eq '64bit5') {
                   12930: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12931: 	} elsif ($which eq '64bit4') {
1.575     albertel 12932: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12933: 	} else {
                   12934: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12935: 	}
1.675     albertel 12936:     } elsif ($which eq '64bit5') {
                   12937: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12938:     } elsif ($which eq '64bit4') {
                   12939: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12940:     } elsif ($which eq '64bit3') {
                   12941: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12942:     } elsif ($which eq '64bit2') {
                   12943: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12944:     } elsif ($which eq '64bit') {
                   12945: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12946:     }
                   12947:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12948: }
                   12949: 
                   12950: sub rndseed_32bit {
                   12951:     my ($symb,$courseid,$domain,$username)=@_;
                   12952:     {
                   12953: 	use integer;
                   12954: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12955: 	my $symbseed=numval($symb) << 22;
                   12956: 	my $namechck=unpack("%32C*",$username) << 17;
                   12957: 	my $nameseed=numval($username) << 12;
                   12958: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12959: 	my $courseseed=unpack("%32C*",$courseid);
                   12960: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12961: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12962: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12963: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12964: 	return $num;
                   12965:     }
                   12966: }
                   12967: 
                   12968: sub rndseed_64bit {
                   12969:     my ($symb,$courseid,$domain,$username)=@_;
                   12970:     {
                   12971: 	use integer;
                   12972: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12973: 	my $symbseed=numval($symb) << 10;
                   12974: 	my $namechck=unpack("%32S*",$username);
                   12975: 	
                   12976: 	my $nameseed=numval($username) << 21;
                   12977: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12978: 	my $courseseed=unpack("%32S*",$courseid);
                   12979: 	
                   12980: 	my $num1=$symbchck+$symbseed+$namechck;
                   12981: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12982: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12983: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12984: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12985: 	return "$num1,$num2";
1.155     albertel 12986:     }
1.366     albertel 12987: }
                   12988: 
1.443     albertel 12989: sub rndseed_64bit2 {
                   12990:     my ($symb,$courseid,$domain,$username)=@_;
                   12991:     {
                   12992: 	use integer;
                   12993: 	# strings need to be an even # of cahracters long, it it is odd the
                   12994:         # last characters gets thrown away
                   12995: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12996: 	my $symbseed=numval($symb) << 10;
                   12997: 	my $namechck=unpack("%32S*",$username.' ');
                   12998: 	
                   12999: 	my $nameseed=numval($username) << 21;
1.501     albertel 13000: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13001: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13002: 	
                   13003: 	my $num1=$symbchck+$symbseed+$namechck;
                   13004: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13005: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13006: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13007: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13008: 	return "$num1,$num2";
                   13009:     }
                   13010: }
                   13011: 
                   13012: sub rndseed_64bit3 {
                   13013:     my ($symb,$courseid,$domain,$username)=@_;
                   13014:     {
                   13015: 	use integer;
                   13016: 	# strings need to be an even # of cahracters long, it it is odd the
                   13017:         # last characters gets thrown away
                   13018: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13019: 	my $symbseed=numval2($symb) << 10;
                   13020: 	my $namechck=unpack("%32S*",$username.' ');
                   13021: 	
                   13022: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13023: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13024: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13025: 	
                   13026: 	my $num1=$symbchck+$symbseed+$namechck;
                   13027: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13028: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13029: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13030: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13031: 	
1.503     albertel 13032: 	return "$num1:$num2";
1.443     albertel 13033:     }
                   13034: }
                   13035: 
1.575     albertel 13036: sub rndseed_64bit4 {
                   13037:     my ($symb,$courseid,$domain,$username)=@_;
                   13038:     {
                   13039: 	use integer;
                   13040: 	# strings need to be an even # of cahracters long, it it is odd the
                   13041:         # last characters gets thrown away
                   13042: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13043: 	my $symbseed=numval3($symb) << 10;
                   13044: 	my $namechck=unpack("%32S*",$username.' ');
                   13045: 	
                   13046: 	my $nameseed=numval3($username) << 21;
                   13047: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13048: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13049: 	
                   13050: 	my $num1=$symbchck+$symbseed+$namechck;
                   13051: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13052: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13053: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13054: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13055: 	
1.575     albertel 13056: 	return "$num1:$num2";
                   13057:     }
                   13058: }
                   13059: 
1.675     albertel 13060: sub rndseed_64bit5 {
                   13061:     my ($symb,$courseid,$domain,$username)=@_;
                   13062:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13063:     return "$num1:$num2";
                   13064: }
                   13065: 
1.366     albertel 13066: sub rndseed_CODE_64bit {
                   13067:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13068:     {
1.366     albertel 13069: 	use integer;
1.443     albertel 13070: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13071: 	my $symbseed=numval2($symb);
1.491     albertel 13072: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13073: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13074: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13075: 	my $num1=$symbseed+$CODEchck;
                   13076: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13077: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13078: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13079: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13080: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13081: 	return "$num1:$num2";
1.366     albertel 13082:     }
                   13083: }
                   13084: 
1.575     albertel 13085: sub rndseed_CODE_64bit4 {
                   13086:     my ($symb,$courseid,$domain,$username)=@_;
                   13087:     {
                   13088: 	use integer;
                   13089: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13090: 	my $symbseed=numval3($symb);
                   13091: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13092: 	my $CODEseed=numval3(&getCODE());
                   13093: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13094: 	my $num1=$symbseed+$CODEchck;
                   13095: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13096: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13097: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13098: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13099: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13100: 	return "$num1:$num2";
                   13101:     }
                   13102: }
                   13103: 
1.675     albertel 13104: sub rndseed_CODE_64bit5 {
                   13105:     my ($symb,$courseid,$domain,$username)=@_;
                   13106:     my $code = &getCODE();
                   13107:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13108:     return "$num1:$num2";
                   13109: }
                   13110: 
1.366     albertel 13111: sub setup_random_from_rndseed {
                   13112:     my ($rndseed)=@_;
1.503     albertel 13113:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13114:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13115:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13116:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13117:         } else {
                   13118:             &Math::Random::random_set_seed($num1,$num2);
                   13119:         }
1.366     albertel 13120:     } else {
                   13121: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13122:     }
1.36      albertel 13123: }
                   13124: 
1.474     albertel 13125: sub latest_receipt_algorithm_id {
1.835     albertel 13126:     return 'receipt3';
1.474     albertel 13127: }
                   13128: 
1.480     www      13129: sub recunique {
                   13130:     my $fucourseid=shift;
                   13131:     my $unique;
1.835     albertel 13132:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13133: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13134: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13135:     } else {
                   13136: 	$unique=$perlvar{'lonReceipt'};
                   13137:     }
                   13138:     return unpack("%32C*",$unique);
                   13139: }
                   13140: 
                   13141: sub recprefix {
                   13142:     my $fucourseid=shift;
                   13143:     my $prefix;
1.835     albertel 13144:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13145: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13146: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13147:     } else {
                   13148: 	$prefix=$perlvar{'lonHostID'};
                   13149:     }
                   13150:     return unpack("%32C*",$prefix);
                   13151: }
                   13152: 
1.76      www      13153: sub ireceipt {
1.474     albertel 13154:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13155: 
                   13156:     my $return =&recprefix($fucourseid).'-';
                   13157: 
                   13158:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13159: 	$env{'request.state'} eq 'construct') {
                   13160: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13161: 	return $return;
                   13162:     }
                   13163: 
1.76      www      13164:     my $cuname=unpack("%32C*",$funame);
                   13165:     my $cudom=unpack("%32C*",$fudom);
                   13166:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13167:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13168:     my $cunique=&recunique($fucourseid);
1.474     albertel 13169:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13170:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13171: 
1.790     albertel 13172: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13173: 			       
                   13174: 	$return.= ($cunique%$cuname+
                   13175: 		   $cunique%$cudom+
                   13176: 		   $cusymb%$cuname+
                   13177: 		   $cusymb%$cudom+
                   13178: 		   $cucourseid%$cuname+
                   13179: 		   $cucourseid%$cudom+
                   13180: 		   $cpart%$cuname+
                   13181: 		   $cpart%$cudom);
                   13182:     } else {
                   13183: 	$return.= ($cunique%$cuname+
                   13184: 		   $cunique%$cudom+
                   13185: 		   $cusymb%$cuname+
                   13186: 		   $cusymb%$cudom+
                   13187: 		   $cucourseid%$cuname+
                   13188: 		   $cucourseid%$cudom);
                   13189:     }
                   13190:     return $return;
1.76      www      13191: }
                   13192: 
                   13193: sub receipt {
1.474     albertel 13194:     my ($part)=@_;
1.790     albertel 13195:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13196:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13197: }
1.260     ng       13198: 
1.790     albertel 13199: sub whichuser {
                   13200:     my ($passedsymb)=@_;
                   13201:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13202:     if (defined($env{'form.grade_symb'})) {
                   13203: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13204: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13205: 	if (!$allowed &&
                   13206: 	    exists($env{'request.course.sec'}) &&
                   13207: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13208: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13209: 			      '/'.$env{'request.course.sec'});
                   13210: 	}
                   13211: 	if ($allowed) {
                   13212: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13213: 	    $courseid=$tmp_courseid;
                   13214: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13215: 	    ($name)=&get_env_multiple('form.grade_username');
                   13216: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13217: 	}
                   13218:     }
                   13219:     if (!$passedsymb) {
                   13220: 	$symb=&symbread();
                   13221:     } else {
                   13222: 	$symb=$passedsymb;
                   13223:     }
                   13224:     $courseid=$env{'request.course.id'};
                   13225:     $domain=$env{'user.domain'};
                   13226:     $name=$env{'user.name'};
                   13227:     if ($name eq 'public' && $domain eq 'public') {
                   13228: 	if (!defined($env{'form.username'})) {
                   13229: 	    $env{'form.username'}.=time.rand(10000000);
                   13230: 	}
                   13231: 	$name.=$env{'form.username'};
                   13232:     }
                   13233:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13234: 
                   13235: }
                   13236: 
1.36      albertel 13237: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13238: # returns either the contents of the file or 
                   13239: # -1 if the file doesn't exist
1.481     raeburn  13240: #
                   13241: # if the target is a file that was uploaded via DOCS, 
                   13242: # a check will be made to see if a current copy exists on the local server,
                   13243: # if it does this will be served, otherwise a copy will be retrieved from
                   13244: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13245: # the local server.   
1.472     albertel 13246: 
1.36      albertel 13247: sub getfile {
1.538     albertel 13248:     my ($file) = @_;
1.609     banghart 13249:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13250:     &repcopy($file);
                   13251:     return &readfile($file);
                   13252: }
                   13253: 
                   13254: sub repcopy_userfile {
                   13255:     my ($file)=@_;
1.1142    raeburn  13256:     my $londocroot = $perlvar{'lonDocRoot'};
                   13257:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13258:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13259:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13260: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13261:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13262:     if (-e "$file") {
1.828     www      13263: # we already have a local copy, check it out
1.538     albertel 13264: 	my @fileinfo = stat($file);
1.828     www      13265: 	my $rtncode;
                   13266: 	my $info;
1.538     albertel 13267: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13268: 	if ($lwpresp ne 'ok') {
1.828     www      13269: # there is no such file anymore, even though we had a local copy
1.482     albertel 13270: 	    if ($rtncode eq '404') {
1.538     albertel 13271: 		unlink($file);
1.482     albertel 13272: 	    }
                   13273: 	    return -1;
                   13274: 	}
                   13275: 	if ($info < $fileinfo[9]) {
1.828     www      13276: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13277: 	    return 'ok';
1.828     www      13278: 	} else {
                   13279: # the file is outdated, get rid of it
                   13280: 	    unlink($file);
1.482     albertel 13281: 	}
1.828     www      13282:     }
                   13283: # one way or the other, at this point, we don't have the file
                   13284: # construct the correct path for the file
                   13285:     my @parts = ($cdom,$cnum); 
                   13286:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13287: 	push @parts, split(/\//,$1);
                   13288:     }
                   13289:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13290:     foreach my $part (@parts) {
                   13291: 	$path .= '/'.$part;
                   13292: 	if (!-e $path) {
                   13293: 	    mkdir($path,0770);
1.482     albertel 13294: 	}
                   13295:     }
1.828     www      13296: # now the path exists for sure
                   13297: # get a user agent
                   13298:     my $transferfile=$file.'.in.transfer';
                   13299: # FIXME: this should flock
                   13300:     if (-e $transferfile) { return 'ok'; }
                   13301:     my $request;
                   13302:     $uri=~s/^\///;
1.980     raeburn  13303:     my $homeserver = &homeserver($cnum,$cdom);
                   13304:     my $protocol = $protocol{$homeserver};
                   13305:     $protocol = 'http' if ($protocol ne 'https');
                   13306:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13307:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13308: # did it work?
                   13309:     if ($response->is_error()) {
                   13310: 	unlink($transferfile);
                   13311: 	&logthis("Userfile repcopy failed for $uri");
                   13312: 	return -1;
                   13313:     }
                   13314: # worked, rename the transfer file
                   13315:     rename($transferfile,$file);
1.607     raeburn  13316:     return 'ok';
1.481     raeburn  13317: }
                   13318: 
1.517     albertel 13319: sub tokenwrapper {
                   13320:     my $uri=shift;
1.980     raeburn  13321:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13322:     $uri=~s|^/||;
1.620     albertel 13323:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13324:     my $token=$1;
1.552     albertel 13325:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13326:     if ($udom && $uname && $file) {
                   13327: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13328:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13329:         my $homeserver = &homeserver($uname,$udom);
                   13330:         my $protocol = $protocol{$homeserver};
                   13331:         $protocol = 'http' if ($protocol ne 'https');
                   13332:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13333:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13334:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13335:     } else {
                   13336:         return '/adm/notfound.html';
                   13337:     }
                   13338: }
                   13339: 
1.828     www      13340: # call with reqtype HEAD: get last modification time
                   13341: # call with reqtype GET: get the file contents
                   13342: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13343: #
1.481     raeburn  13344: sub getuploaded {
                   13345:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13346:     $uri=~s/^\///;
1.980     raeburn  13347:     my $homeserver = &homeserver($cnum,$cdom);
                   13348:     my $protocol = $protocol{$homeserver};
                   13349:     $protocol = 'http' if ($protocol ne 'https');
                   13350:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13351:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13352:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13353:     $$rtncode = $response->code;
1.482     albertel 13354:     if (! $response->is_success()) {
                   13355: 	return 'failed';
                   13356:     }      
                   13357:     if ($reqtype eq 'HEAD') {
1.486     www      13358: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13359:     } elsif ($reqtype eq 'GET') {
                   13360: 	$$info = $response->content;
1.472     albertel 13361:     }
1.482     albertel 13362:     return 'ok';
1.36      albertel 13363: }
                   13364: 
1.481     raeburn  13365: sub readfile {
                   13366:     my $file = shift;
                   13367:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13368:     my $fh;
1.1359    raeburn  13369:     open($fh,"<",$file);
1.481     raeburn  13370:     my $a='';
1.800     albertel 13371:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13372:     return $a;
                   13373: }
                   13374: 
1.36      albertel 13375: sub filelocation {
1.590     banghart 13376:     my ($dir,$file) = @_;
                   13377:     my $location;
                   13378:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13379: 
                   13380:     if ($file =~ m-^/adm/-) {
                   13381: 	$file=~s-^/adm/wrapper/-/-;
                   13382: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13383:     }
1.882     albertel 13384: 
1.1139    www      13385:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13386:         $location = $file;
1.609     banghart 13387:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13388:         my ($udom,$uname,$filename)=
1.811     albertel 13389:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13390:         my $home=&homeserver($uname,$udom);
                   13391:         my $is_me=0;
                   13392:         my @ids=&current_machine_ids();
                   13393:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13394:         if ($is_me) {
1.1117    foxr     13395:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13396:         } else {
                   13397:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13398:   	      $udom.'/'.$uname.'/'.$filename;
                   13399:         }
1.882     albertel 13400:     } elsif ($file =~ m-^/adm/-) {
                   13401: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13402:     } else {
                   13403:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13404:         $file=~s:^/(res|priv)/:/:;
                   13405:         my $space=$1;
1.590     banghart 13406:         if ( !( $file =~ m:^/:) ) {
                   13407:             $location = $dir. '/'.$file;
                   13408:         } else {
1.1142    raeburn  13409:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13410:         }
1.59      albertel 13411:     }
1.590     banghart 13412:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13413:     while ($location=~m{/\.\./}) {
                   13414: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13415: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13416: 	} else {
                   13417: 	    $location=~ s{/\.\./}{/}g;
                   13418: 	}
                   13419:     } #remove dir/..
1.590     banghart 13420:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13421:     return $location;
1.46      www      13422: }
1.36      albertel 13423: 
1.46      www      13424: sub hreflocation {
                   13425:     my ($dir,$file)=@_;
1.980     raeburn  13426:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13427: 	$file=filelocation($dir,$file);
1.700     albertel 13428:     } elsif ($file=~m-^/adm/-) {
                   13429: 	$file=~s-^/adm/wrapper/-/-;
                   13430: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13431:     }
                   13432:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13433: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13434:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13435: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13436: 	        {/uploaded/$1/$2/}x;
1.46      www      13437:     }
1.913     albertel 13438:     if ($file=~ m{^/userfiles/}) {
                   13439: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13440:     }
1.462     albertel 13441:     return $file;
1.465     albertel 13442: }
                   13443: 
1.1139    www      13444: 
                   13445: 
                   13446: 
                   13447: 
1.465     albertel 13448: sub current_machine_domains {
1.853     albertel 13449:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13450: }
                   13451: 
                   13452: sub machine_domains {
                   13453:     my ($hostname) = @_;
1.465     albertel 13454:     my @domains;
1.838     albertel 13455:     my %hostname = &all_hostnames();
1.465     albertel 13456:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13457: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13458: 	if ($hostname eq $name) {
1.844     albertel 13459: 	    push(@domains,&host_domain($id));
1.465     albertel 13460: 	}
                   13461:     }
                   13462:     return @domains;
                   13463: }
                   13464: 
                   13465: sub current_machine_ids {
1.853     albertel 13466:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13467: }
                   13468: 
                   13469: sub machine_ids {
                   13470:     my ($hostname) = @_;
                   13471:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13472:     my @ids;
1.888     albertel 13473:     my %name_to_host = &all_names();
1.889     albertel 13474:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13475: 	return @{ $name_to_host{$hostname} };
                   13476:     }
                   13477:     return;
1.31      www      13478: }
                   13479: 
1.824     raeburn  13480: sub additional_machine_domains {
                   13481:     my @domains;
1.1359    raeburn  13482:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13483:     while( my $line = <$fh>) {
                   13484:         $line =~ s/\s//g;
                   13485:         push(@domains,$line);
                   13486:     }
                   13487:     return @domains;
                   13488: }
                   13489: 
                   13490: sub default_login_domain {
                   13491:     my $domain = $perlvar{'lonDefDomain'};
                   13492:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13493:     foreach my $posdom (&current_machine_domains(),
                   13494:                         &additional_machine_domains()) {
                   13495:         if (lc($posdom) eq lc($testdomain)) {
                   13496:             $domain=$posdom;
                   13497:             last;
                   13498:         }
                   13499:     }
                   13500:     return $domain;
                   13501: }
                   13502: 
1.31      www      13503: # ------------------------------------------------------------- Declutters URLs
                   13504: 
                   13505: sub declutter {
                   13506:     my $thisfn=shift;
1.569     albertel 13507:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13508:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13509:         $thisfn=~s{^/home/httpd/html}{};
                   13510:     }
1.31      www      13511:     $thisfn=~s/^\///;
1.697     albertel 13512:     $thisfn=~s|^adm/wrapper/||;
                   13513:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13514:     $thisfn=~s/^res\///;
1.1172    bisitz   13515:     $thisfn=~s/^priv\///;
1.1032    raeburn  13516:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13517:         $thisfn=~s/\?.+$//;
                   13518:     }
1.268     www      13519:     return $thisfn;
                   13520: }
                   13521: 
                   13522: # ------------------------------------------------------------- Clutter up URLs
                   13523: 
                   13524: sub clutter {
                   13525:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13526:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13527: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13528:        $thisfn='/res'.$thisfn; 
                   13529:     }
1.1031    raeburn  13530:     if ($thisfn !~m|^/adm|) {
                   13531: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13532: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13533: 	} else {
                   13534: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13535: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13536: 	    if ($embstyle eq 'ssi'
                   13537: 		|| ($embstyle eq 'hdn')
                   13538: 		|| ($embstyle eq 'rat')
                   13539: 		|| ($embstyle eq 'prv')
                   13540: 		|| ($embstyle eq 'ign')) {
                   13541: 		#do nothing with these
                   13542: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13543: 		|| ($embstyle eq 'emb')
                   13544: 		|| ($embstyle eq 'wrp')) {
                   13545: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13546: 	    } elsif ($embstyle eq 'unk'
                   13547: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13548: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13549: 	    } else {
1.718     www      13550: #		&logthis("Got a blank emb style");
1.695     albertel 13551: 	    }
1.694     albertel 13552: 	}
1.1343    raeburn  13553:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13554:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13555:     }
1.31      www      13556:     return $thisfn;
1.12      www      13557: }
                   13558: 
1.787     albertel 13559: sub clutter_with_no_wrapper {
                   13560:     my $uri = &clutter(shift);
                   13561:     if ($uri =~ m-^/adm/-) {
                   13562: 	$uri =~ s-^/adm/wrapper/-/-;
                   13563: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13564:     }
                   13565:     return $uri;
                   13566: }
                   13567: 
1.557     albertel 13568: sub freeze_escape {
                   13569:     my ($value)=@_;
                   13570:     if (ref($value)) {
                   13571: 	$value=&nfreeze($value);
                   13572: 	return '__FROZEN__'.&escape($value);
                   13573:     }
                   13574:     return &escape($value);
                   13575: }
                   13576: 
1.11      www      13577: 
1.557     albertel 13578: sub thaw_unescape {
                   13579:     my ($value)=@_;
                   13580:     if ($value =~ /^__FROZEN__/) {
                   13581: 	substr($value,0,10,undef);
                   13582: 	$value=&unescape($value);
                   13583: 	return &thaw($value);
                   13584:     }
                   13585:     return &unescape($value);
                   13586: }
                   13587: 
1.436     albertel 13588: sub correct_line_ends {
                   13589:     my ($result)=@_;
                   13590:     $$result =~s/\r\n/\n/mg;
                   13591:     $$result =~s/\r/\n/mg;
1.415     albertel 13592: }
1.1       albertel 13593: # ================================================================ Main Program
                   13594: 
1.184     www      13595: sub goodbye {
1.204     albertel 13596:    &logthis("Starting Shut down");
1.443     albertel 13597: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13598:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13599: #converted
1.599     albertel 13600: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13601:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13602: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13603: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13604: #1.1 only
1.870     albertel 13605: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13606: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13607: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13608: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13609:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13610:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13611:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13612:    &flushcourselogs();
                   13613:    &logthis("Shutting down");
                   13614: }
                   13615: 
1.852     albertel 13616: sub get_dns {
1.1210    raeburn  13617:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13618:     if (!$ignore_cache) {
                   13619: 	my ($content,$cached)=
                   13620: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13621: 	if ($cached) {
1.1210    raeburn  13622: 	    &$func($content,$hashref);
1.869     albertel 13623: 	    return;
                   13624: 	}
                   13625:     }
                   13626: 
                   13627:     my %alldns;
1.1379    raeburn  13628:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13629:         foreach my $dns (<$config>) {
                   13630: 	    next if ($dns !~ /^\^(\S*)/x);
                   13631:             my $line = $1;
                   13632:             my ($host,$protocol) = split(/:/,$line);
                   13633:             if ($protocol ne 'https') {
                   13634:                 $protocol = 'http';
                   13635:             }
                   13636: 	    $alldns{$host} = $protocol;
1.979     raeburn  13637:         }
1.1379    raeburn  13638:         close($config);
1.869     albertel 13639:     }
                   13640:     while (%alldns) {
1.1263    raeburn  13641: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13642: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13643:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13644:         delete($alldns{$dns});
1.852     albertel 13645: 	next if ($response->is_error());
1.1379    raeburn  13646:         if ($url eq '/adm/dns/loncapaCRL') {
                   13647:             return &$func($response);
                   13648:         } else {
                   13649: 	    my @content = split("\n",$response->content);
                   13650: 	    unless ($nocache) {
                   13651: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   13652: 	    }
                   13653: 	    &$func(\@content,$hashref);
                   13654:             return;
                   13655:         }
                   13656:     }
                   13657:     my $which = (split('/',$url,4))[3];
                   13658:     if ($which eq 'loncapaCRL') {
                   13659:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   13660:         if (-e $diskfile) {
                   13661:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   13662:         } else {
                   13663:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   13664:         }
                   13665:     } else {
                   13666:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13667:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13668:             my @content = <$config>;
                   13669:             close($config);
                   13670:             &$func(\@content,$hashref);
                   13671:         }
1.852     albertel 13672:     }
1.1210    raeburn  13673:     return;
                   13674: }
                   13675: 
                   13676: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13677: sub parse_dns_checksums_tab {
1.1210    raeburn  13678:     my ($lines,$hashref) = @_;
1.1264    raeburn  13679:     my $lonhost = $perlvar{'lonHostID'};
                   13680:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13681:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13682:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13683:     my $webconfdir = '/etc/httpd/conf';
                   13684:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13685:         $webconfdir = '/etc/apache2';
                   13686:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13687:         if ($1 >= 10) {
                   13688:             $webconfdir = '/etc/apache2';
                   13689:         }
                   13690:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13691:         if ($1 >= 10.0) {
                   13692:             $webconfdir = '/etc/apache2';
                   13693:         }
                   13694:     }
1.1210    raeburn  13695:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13696:     my (%chksum,%revnum);
                   13697:     if (ref($lines) eq 'ARRAY') {
                   13698:         chomp(@{$lines});
1.1238    raeburn  13699:         my $version = shift(@{$lines});
                   13700:         if ($version eq $release) {  
1.1210    raeburn  13701:             foreach my $line (@{$lines}) {
1.1238    raeburn  13702:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13703:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13704:                     if ($webconfdir eq '/etc/apache2') {
                   13705:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13706:                     }
                   13707:                 }
1.1238    raeburn  13708:                 $chksum{$file} = $shasum;
                   13709:                 $revnum{$file} = $version;
1.1210    raeburn  13710:             }
                   13711:             if (ref($hashref) eq 'HASH') {
                   13712:                 %{$hashref} = (
                   13713:                                 sums     => \%chksum,
                   13714:                                 versions => \%revnum,
                   13715:                               );
                   13716:             }
                   13717:         }
                   13718:     }
1.869     albertel 13719:     return;
1.852     albertel 13720: }
1.1210    raeburn  13721: 
                   13722: sub fetch_dns_checksums {
1.1238    raeburn  13723:     my %checksums;
                   13724:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13725:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13726:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13727:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13728:              \%checksums);
1.1210    raeburn  13729:     return \%checksums;
                   13730: }
                   13731: 
1.1379    raeburn  13732: sub fetch_crl_pemfile {
                   13733:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   13734: }
                   13735: 
                   13736: sub save_crl_pem {
                   13737:     my ($response) = @_;
1.1380    raeburn  13738:     my ($msg,$hadchanges);
1.1379    raeburn  13739:     if (ref($response)) {
                   13740:         my $now = time;
                   13741:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   13742:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   13743:         if (open(my $fh,'>',"$tmpcrl")) {
                   13744:             print $fh $response->content;
                   13745:             close($fh);
                   13746:             if (-e $lonca) {
                   13747:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   13748:                     my $check = <PIPE>;
                   13749:                     close(PIPE);
                   13750:                     chomp($check);
                   13751:                     if ($check eq 'verify OK') {
                   13752:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  13753:                         my $backup;
1.1379    raeburn  13754:                         if (-e $dest) {
1.1380    raeburn  13755:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   13756:                                 $backup = 'ok';
                   13757:                             }
1.1379    raeburn  13758:                         }
                   13759:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   13760:                             $msg = 'ok';
1.1380    raeburn  13761:                             if ($backup) {
                   13762:                                 my (%oldnums,%newnums);
                   13763:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   13764:                                     while (<PIPE>) {
                   13765:                                         $oldnums{(split(/:/))[1]} = 1;
                   13766:                                     }
                   13767:                                     close(PIPE);
                   13768:                                 }
                   13769:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   13770:                                     while(<PIPE>) {
                   13771:                                         $newnums{(split(/:/))[1]} = 1;
                   13772:                                     }
                   13773:                                     close(PIPE);
                   13774:                                 }
                   13775:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   13776:                                     unless (exists($oldnums{$key})) {
                   13777:                                         $hadchanges = 1;
                   13778:                                         last;
                   13779:                                     }
                   13780:                                 }
                   13781:                                 unless ($hadchanges) {
                   13782:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   13783:                                         unless (exists($newnums{$key})) {
                   13784:                                             $hadchanges = 1;
                   13785:                                             last;
                   13786:                                         }
                   13787:                                     }
                   13788:                                 }
                   13789:                             }
1.1379    raeburn  13790:                         }
                   13791:                     } else {
                   13792:                         unlink($tmpcrl);
                   13793:                     }
                   13794:                 } else {
                   13795:                     unlink($tmpcrl);
                   13796:                 }
                   13797:             } else {
                   13798:                 unlink($tmpcrl);
                   13799:             }
                   13800:         }
                   13801:     }
1.1380    raeburn  13802:     return ($msg,$hadchanges);
1.1379    raeburn  13803: }
                   13804: 
1.327     albertel 13805: # ------------------------------------------------------------ Read domain file
                   13806: {
1.852     albertel 13807:     my $loaded;
1.846     albertel 13808:     my %domain;
                   13809: 
1.852     albertel 13810:     sub parse_domain_tab {
                   13811: 	my ($lines) = @_;
                   13812: 	foreach my $line (@$lines) {
                   13813: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13814: 
1.846     albertel 13815: 	    chomp($line);
1.852     albertel 13816: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13817: 	    my %this_domain;
                   13818: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13819: 			       'lang_def', 'city', 'longi', 'lati',
                   13820: 			       'primary') {
                   13821: 		$this_domain{$field} = shift(@elements);
                   13822: 	    }
                   13823: 	    $domain{$name} = \%this_domain;
1.852     albertel 13824: 	}
                   13825:     }
1.864     albertel 13826: 
                   13827:     sub reset_domain_info {
                   13828: 	undef($loaded);
                   13829: 	undef(%domain);
                   13830:     }
                   13831: 
1.852     albertel 13832:     sub load_domain_tab {
1.1293    raeburn  13833: 	my ($ignore_cache,$nocache) = @_;
                   13834: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13835: 	my $fh;
1.1359    raeburn  13836: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13837: 	    my @lines = <$fh>;
                   13838: 	    &parse_domain_tab(\@lines);
1.448     albertel 13839: 	}
1.852     albertel 13840: 	close($fh);
                   13841: 	$loaded = 1;
1.327     albertel 13842:     }
1.846     albertel 13843: 
                   13844:     sub domain {
1.852     albertel 13845: 	&load_domain_tab() if (!$loaded);
                   13846: 
1.846     albertel 13847: 	my ($name,$what) = @_;
                   13848: 	return if ( !exists($domain{$name}) );
                   13849: 
                   13850: 	if (!$what) {
                   13851: 	    return $domain{$name}{'description'};
                   13852: 	}
                   13853: 	return $domain{$name}{$what};
                   13854:     }
1.974     raeburn  13855: 
                   13856:     sub domain_info {
                   13857:         &load_domain_tab() if (!$loaded);
                   13858:         return %domain;
                   13859:     }
                   13860: 
1.327     albertel 13861: }
                   13862: 
                   13863: 
1.1       albertel 13864: # ------------------------------------------------------------- Read hosts file
                   13865: {
1.838     albertel 13866:     my %hostname;
1.844     albertel 13867:     my %hostdom;
1.845     albertel 13868:     my %libserv;
1.852     albertel 13869:     my $loaded;
1.888     albertel 13870:     my %name_to_host;
1.1074    raeburn  13871:     my %internetdom;
1.1107    raeburn  13872:     my %LC_dns_serv;
1.852     albertel 13873: 
                   13874:     sub parse_hosts_tab {
                   13875: 	my ($file) = @_;
                   13876: 	foreach my $configline (@$file) {
                   13877: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13878:             chomp($configline);
                   13879: 	    if ($configline =~ /^\^/) {
                   13880:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13881:                     $LC_dns_serv{$1} = 1;
                   13882:                 }
                   13883:                 next;
                   13884:             }
1.1074    raeburn  13885: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13886: 	    $name=~s/\s//g;
                   13887: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13888:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13889:                     my $curr = $hostname{$id};
                   13890:                     my $skip;
                   13891:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13892:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13893:                             $skip = 1;
                   13894:                         } else {
                   13895:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13896:                         }
                   13897:                     }
                   13898:                     unless ($skip) {
                   13899:                         push(@{$name_to_host{$name}},$id);
                   13900:                     }
                   13901:                 } else {
                   13902:                     push(@{$name_to_host{$name}},$id);
                   13903:                 }
1.852     albertel 13904: 		$hostname{$id}=$name;
                   13905: 		$hostdom{$id}=$domain;
                   13906: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13907:                 if (defined($protocol)) {
                   13908:                     if ($protocol eq 'https') {
                   13909:                         $protocol{$id} = $protocol;
                   13910:                     } else {
                   13911:                         $protocol{$id} = 'http'; 
                   13912:                     }
1.968     raeburn  13913:                 } else {
1.969     raeburn  13914:                     $protocol{$id} = 'http';
1.968     raeburn  13915:                 }
1.1074    raeburn  13916:                 if (defined($intdom)) {
                   13917:                     $internetdom{$id} = $intdom;
                   13918:                 }
1.852     albertel 13919: 	    }
                   13920: 	}
                   13921:     }
1.864     albertel 13922:     
                   13923:     sub reset_hosts_info {
1.897     albertel 13924: 	&purge_remembered();
1.864     albertel 13925: 	&reset_domain_info();
                   13926: 	&reset_hosts_ip_info();
1.1339    raeburn  13927:         undef(%internetdom);
1.892     albertel 13928: 	undef(%name_to_host);
1.864     albertel 13929: 	undef(%hostname);
                   13930: 	undef(%hostdom);
                   13931: 	undef(%libserv);
                   13932: 	undef($loaded);
                   13933:     }
1.1       albertel 13934: 
1.852     albertel 13935:     sub load_hosts_tab {
1.1293    raeburn  13936: 	my ($ignore_cache,$nocache) = @_;
                   13937: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13938: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13939: 	my @config = <$config>;
                   13940: 	&parse_hosts_tab(\@config);
                   13941: 	close($config);
                   13942: 	$loaded=1;
1.1       albertel 13943:     }
1.852     albertel 13944: 
1.838     albertel 13945:     sub hostname {
1.852     albertel 13946: 	&load_hosts_tab() if (!$loaded);
                   13947: 
1.838     albertel 13948: 	my ($lonid) = @_;
                   13949: 	return $hostname{$lonid};
                   13950:     }
1.845     albertel 13951: 
1.838     albertel 13952:     sub all_hostnames {
1.852     albertel 13953: 	&load_hosts_tab() if (!$loaded);
                   13954: 
1.838     albertel 13955: 	return %hostname;
                   13956:     }
1.845     albertel 13957: 
1.888     albertel 13958:     sub all_names {
1.1293    raeburn  13959:         my ($ignore_cache,$nocache) = @_;
                   13960: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13961: 
                   13962: 	return %name_to_host;
                   13963:     }
                   13964: 
1.974     raeburn  13965:     sub all_host_domain {
                   13966:         &load_hosts_tab() if (!$loaded);
                   13967:         return %hostdom;
                   13968:     }
                   13969: 
1.1339    raeburn  13970:     sub all_host_intdom {
                   13971:         &load_hosts_tab() if (!$loaded);
                   13972:         return %internetdom;
                   13973:     }
                   13974: 
1.845     albertel 13975:     sub is_library {
1.852     albertel 13976: 	&load_hosts_tab() if (!$loaded);
                   13977: 
1.845     albertel 13978: 	return exists($libserv{$_[0]});
                   13979:     }
                   13980: 
                   13981:     sub all_library {
1.852     albertel 13982: 	&load_hosts_tab() if (!$loaded);
                   13983: 
1.845     albertel 13984: 	return %libserv;
                   13985:     }
                   13986: 
1.1062    droeschl 13987:     sub unique_library {
                   13988: 	#2x reverse removes all hostnames that appear more than once
                   13989:         my %unique = reverse &all_library();
                   13990:         return reverse %unique;
                   13991:     }
                   13992: 
1.841     albertel 13993:     sub get_servers {
1.852     albertel 13994: 	&load_hosts_tab() if (!$loaded);
                   13995: 
1.841     albertel 13996: 	my ($domain,$type) = @_;
                   13997: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13998: 	                                          : %hostname;
                   13999: 	my %result;
1.842     albertel 14000: 	if (ref($domain) eq 'ARRAY') {
                   14001: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14002: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14003: 		    $result{$host} = $hostname;
                   14004: 		}
                   14005: 	    }
                   14006: 	} else {
                   14007: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14008: 		if ($hostdom{$host} eq $domain) {
                   14009: 		    $result{$host} = $hostname;
                   14010: 		}
1.841     albertel 14011: 	    }
                   14012: 	}
                   14013: 	return %result;
                   14014:     }
1.845     albertel 14015: 
1.1062    droeschl 14016:     sub get_unique_servers {
                   14017:         my %unique = reverse &get_servers(@_);
                   14018: 	return reverse %unique;
                   14019:     }
                   14020: 
1.844     albertel 14021:     sub host_domain {
1.852     albertel 14022: 	&load_hosts_tab() if (!$loaded);
                   14023: 
1.844     albertel 14024: 	my ($lonid) = @_;
                   14025: 	return $hostdom{$lonid};
                   14026:     }
                   14027: 
1.841     albertel 14028:     sub all_domains {
1.852     albertel 14029: 	&load_hosts_tab() if (!$loaded);
                   14030: 
1.841     albertel 14031: 	my %seen;
                   14032: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14033: 	return @uniq;
                   14034:     }
1.1074    raeburn  14035: 
                   14036:     sub internet_dom {
                   14037:         &load_hosts_tab() if (!$loaded);
                   14038: 
                   14039:         my ($lonid) = @_;
                   14040:         return $internetdom{$lonid};
                   14041:     }
1.1107    raeburn  14042: 
                   14043:     sub is_LC_dns {
                   14044:         &load_hosts_tab() if (!$loaded);
                   14045: 
                   14046:         my ($hostname) = @_;
                   14047:         return exists($LC_dns_serv{$hostname});
                   14048:     }
                   14049: 
1.1       albertel 14050: }
                   14051: 
1.847     albertel 14052: { 
                   14053:     my %iphost;
1.856     albertel 14054:     my %name_to_ip;
                   14055:     my %lonid_to_ip;
1.869     albertel 14056: 
1.847     albertel 14057:     sub get_hosts_from_ip {
                   14058: 	my ($ip) = @_;
                   14059: 	my %iphosts = &get_iphost();
                   14060: 	if (ref($iphosts{$ip})) {
                   14061: 	    return @{$iphosts{$ip}};
                   14062: 	}
                   14063: 	return;
1.839     albertel 14064:     }
1.864     albertel 14065:     
                   14066:     sub reset_hosts_ip_info {
                   14067: 	undef(%iphost);
                   14068: 	undef(%name_to_ip);
                   14069: 	undef(%lonid_to_ip);
                   14070:     }
1.856     albertel 14071: 
                   14072:     sub get_host_ip {
                   14073: 	my ($lonid) = @_;
                   14074: 	if (exists($lonid_to_ip{$lonid})) {
                   14075: 	    return $lonid_to_ip{$lonid};
                   14076: 	}
                   14077: 	my $name=&hostname($lonid);
                   14078:    	my $ip = gethostbyname($name);
                   14079: 	return if (!$ip || length($ip) ne 4);
                   14080: 	$ip=inet_ntoa($ip);
                   14081: 	$name_to_ip{$name}   = $ip;
                   14082: 	$lonid_to_ip{$lonid} = $ip;
                   14083: 	return $ip;
                   14084:     }
1.847     albertel 14085:     
                   14086:     sub get_iphost {
1.1293    raeburn  14087: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14088: 
1.869     albertel 14089: 	if (!$ignore_cache) {
                   14090: 	    if (%iphost) {
                   14091: 		return %iphost;
                   14092: 	    }
                   14093: 	    my ($ip_info,$cached)=
                   14094: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14095: 	    if ($cached) {
                   14096: 		%iphost      = %{$ip_info->[0]};
                   14097: 		%name_to_ip  = %{$ip_info->[1]};
                   14098: 		%lonid_to_ip = %{$ip_info->[2]};
                   14099: 		return %iphost;
                   14100: 	    }
                   14101: 	}
1.894     albertel 14102: 
                   14103: 	# get yesterday's info for fallback
                   14104: 	my %old_name_to_ip;
                   14105: 	my ($ip_info,$cached)=
                   14106: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14107: 	if ($cached) {
                   14108: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14109: 	}
                   14110: 
1.1293    raeburn  14111: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14112: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14113: 	    my $ip;
                   14114: 	    if (!exists($name_to_ip{$name})) {
                   14115: 		$ip = gethostbyname($name);
                   14116: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14117: 		    if (defined($old_name_to_ip{$name})) {
                   14118: 			$ip = $old_name_to_ip{$name};
                   14119: 			&logthis("Can't find $name defaulting to old $ip");
                   14120: 		    } else {
                   14121: 			&logthis("Name $name no IP found");
                   14122: 			next;
                   14123: 		    }
                   14124: 		} else {
                   14125: 		    $ip=inet_ntoa($ip);
1.847     albertel 14126: 		}
                   14127: 		$name_to_ip{$name} = $ip;
                   14128: 	    } else {
                   14129: 		$ip = $name_to_ip{$name};
1.653     albertel 14130: 	    }
1.888     albertel 14131: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14132: 		$lonid_to_ip{$id} = $ip;
                   14133: 	    }
                   14134: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14135: 	}
1.1293    raeburn  14136:         unless ($nocache) {
                   14137: 	    &do_cache_new('iphost','iphost',
                   14138: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14139: 		          48*60*60);
                   14140:         }
1.869     albertel 14141: 
1.847     albertel 14142: 	return %iphost;
1.598     albertel 14143:     }
                   14144: 
1.992     raeburn  14145:     #
                   14146:     #  Given a DNS returns the loncapa host name for that DNS 
                   14147:     # 
                   14148:     sub host_from_dns {
                   14149:         my ($dns) = @_;
                   14150:         my @hosts;
                   14151:         my $ip;
                   14152: 
1.993     raeburn  14153:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14154:             $ip = $name_to_ip{$dns};
                   14155:         }
                   14156:         if (!$ip) {
                   14157:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14158:             if (length($ip) == 4) { 
                   14159: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14160:             }
                   14161:         }
                   14162:         if ($ip) {
                   14163: 	    @hosts = get_hosts_from_ip($ip);
                   14164: 	    return $hosts[0];
                   14165:         }
                   14166:         return undef;
1.986     foxr     14167:     }
1.992     raeburn  14168: 
1.1074    raeburn  14169:     sub get_internet_names {
                   14170:         my ($lonid) = @_;
                   14171:         return if ($lonid eq '');
                   14172:         my ($idnref,$cached)=
                   14173:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14174:         if ($cached) {
                   14175:             return $idnref;
                   14176:         }
                   14177:         my $ip = &get_host_ip($lonid);
                   14178:         my @hosts = &get_hosts_from_ip($ip);
                   14179:         my %iphost = &get_iphost();
                   14180:         my (@idns,%seen);
                   14181:         foreach my $id (@hosts) {
                   14182:             my $dom = &host_domain($id);
                   14183:             my $prim_id = &domain($dom,'primary');
                   14184:             my $prim_ip = &get_host_ip($prim_id);
                   14185:             next if ($seen{$prim_ip});
                   14186:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14187:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14188:                     my $intdom = &internet_dom($id);
                   14189:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14190:                         push(@idns,$intdom);
                   14191:                     }
                   14192:                 }
                   14193:             }
                   14194:             $seen{$prim_ip} = 1;
                   14195:         }
1.1219    raeburn  14196:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14197:     }
                   14198: 
1.986     foxr     14199: }
                   14200: 
1.1079    raeburn  14201: sub all_loncaparevs {
1.1249    raeburn  14202:     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  14203: }
                   14204: 
1.1227    raeburn  14205: # ---------------------------------------------------------- Read loncaparev table
                   14206: {
                   14207:     sub load_loncaparevs { 
                   14208:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14209:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14210:                 while (my $configline=<$config>) {
                   14211:                     chomp($configline);
                   14212:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14213:                     $loncaparevs{$hostid}=$loncaparev;
                   14214:                 }
                   14215:                 close($config);
                   14216:             }
                   14217:         }
                   14218:     }
                   14219: }
                   14220: 
                   14221: # ---------------------------------------------------------- Read serverhostID table
                   14222: {
                   14223:     sub load_serverhomeIDs {
                   14224:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14225:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14226:                 while (my $configline=<$config>) {
                   14227:                     chomp($configline);
                   14228:                     my ($name,$id)=split(/:/,$configline);
                   14229:                     $serverhomeIDs{$name}=$id;
                   14230:                 }
                   14231:                 close($config);
                   14232:             }
                   14233:         }
                   14234:     }
                   14235: }
                   14236: 
                   14237: 
1.862     albertel 14238: BEGIN {
                   14239: 
                   14240: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14241:     unless ($readit) {
                   14242: {
                   14243:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14244:     %perlvar = (%perlvar,%{$configvars});
                   14245: }
                   14246: 
                   14247: 
1.1       albertel 14248: # ------------------------------------------------------ Read spare server file
                   14249: {
1.1359    raeburn  14250:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14251: 
                   14252:     while (my $configline=<$config>) {
                   14253:        chomp($configline);
1.284     matthew  14254:        if ($configline) {
1.784     albertel 14255: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14256: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14257: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14258:        }
                   14259:     }
1.448     albertel 14260:     close($config);
1.1       albertel 14261: }
1.11      www      14262: # ------------------------------------------------------------ Read permissions
                   14263: {
1.1359    raeburn  14264:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14265: 
                   14266:     while (my $configline=<$config>) {
1.448     albertel 14267: 	chomp($configline);
                   14268: 	if ($configline) {
                   14269: 	    my ($role,$perm)=split(/ /,$configline);
                   14270: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14271: 	}
1.11      www      14272:     }
1.448     albertel 14273:     close($config);
1.11      www      14274: }
                   14275: 
                   14276: # -------------------------------------------- Read plain texts for permissions
                   14277: {
1.1359    raeburn  14278:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14279: 
                   14280:     while (my $configline=<$config>) {
1.448     albertel 14281: 	chomp($configline);
                   14282: 	if ($configline) {
1.742     raeburn  14283: 	    my ($short,@plain)=split(/:/,$configline);
                   14284:             %{$prp{$short}} = ();
                   14285: 	    if (@plain > 0) {
                   14286:                 $prp{$short}{'std'} = $plain[0];
                   14287:                 for (my $i=1; $i<@plain; $i++) {
                   14288:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14289:                 }
                   14290:             }
1.448     albertel 14291: 	}
1.135     www      14292:     }
1.448     albertel 14293:     close($config);
1.135     www      14294: }
                   14295: 
                   14296: # ---------------------------------------------------------- Read package table
                   14297: {
1.1359    raeburn  14298:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14299: 
                   14300:     while (my $configline=<$config>) {
1.483     albertel 14301: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14302: 	chomp($configline);
                   14303: 	my ($short,$plain)=split(/:/,$configline);
                   14304: 	my ($pack,$name)=split(/\&/,$short);
                   14305: 	if ($plain ne '') {
                   14306: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14307: 	    $packagetab{$short}=$plain; 
                   14308: 	}
1.11      www      14309:     }
1.448     albertel 14310:     close($config);
1.329     matthew  14311: }
                   14312: 
1.1073    raeburn  14313: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14314: 
                   14315: &load_loncaparevs();
1.1073    raeburn  14316: 
1.1074    raeburn  14317: # ---------------------------------------------------------- Read serverhostID table
                   14318: 
1.1227    raeburn  14319: &load_serverhomeIDs();
                   14320: 
                   14321: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14322: {
                   14323:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14324:     if (-e $file) {
                   14325:         my $parser = HTML::LCParser->new($file);
                   14326:         while (my $token = $parser->get_token()) {
                   14327:             if ($token->[0] eq 'S') {
                   14328:                 my $item = $token->[1];
                   14329:                 my $name = $token->[2]{'name'};
                   14330:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14331:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14332:                 my $namematch = $token->[2]{'namematch'};
                   14333:                 if ($item eq 'parameter') {
                   14334:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14335:                         my $release = $parser->get_text();
                   14336:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14337:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14338:                     }
                   14339:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14340:                     my $release = $parser->get_text();
                   14341:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14342:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14343:                 }
                   14344:             }
                   14345:         }
                   14346:     }
1.1073    raeburn  14347: }
                   14348: 
1.1138    raeburn  14349: # ---------------------------------------------------------- Read managers table
                   14350: {
                   14351:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14352:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14353:             while (my $configline=<$config>) {
                   14354:                 chomp($configline);
                   14355:                 next if ($configline =~ /^\#/);
                   14356:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14357:                     $managerstab{$configline} = 1;
                   14358:                 }
                   14359:             }
                   14360:             close($config);
                   14361:         }
                   14362:     }
                   14363: }
                   14364: 
1.329     matthew  14365: # ------------- set up temporary directory
                   14366: {
1.1117    foxr     14367:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14368: 
1.11      www      14369: }
                   14370: 
1.794     albertel 14371: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14372: 				'compress_threshold'=> 20_000,
                   14373:  			        });
1.185     www      14374: 
1.281     www      14375: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14376: $dumpcount=0;
1.958     www      14377: $locknum=0;
1.22      www      14378: 
1.163     harris41 14379: &logtouch();
1.672     albertel 14380: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14381: $readit=1;
1.564     albertel 14382:     {
                   14383: 	use integer;
                   14384: 	my $test=(2**32)+1;
1.568     albertel 14385: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14386: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14387:     }
1.195     www      14388: }
1.1       albertel 14389: }
1.179     www      14390: 
1.1       albertel 14391: 1;
1.191     harris41 14392: __END__
                   14393: 
1.243     albertel 14394: =pod
                   14395: 
1.191     harris41 14396: =head1 NAME
                   14397: 
1.243     albertel 14398: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14399: 
                   14400: =head1 SYNOPSIS
                   14401: 
1.243     albertel 14402: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14403: 
                   14404:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14405: 
1.243     albertel 14406: Common parameters:
                   14407: 
                   14408: =over 4
                   14409: 
                   14410: =item *
                   14411: 
                   14412: $uname : an internal username (if $cname expecting a course Id specifically)
                   14413: 
                   14414: =item *
                   14415: 
                   14416: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14417: 
                   14418: =item *
                   14419: 
                   14420: $symb : a resource instance identifier
                   14421: 
                   14422: =item *
                   14423: 
                   14424: $namespace : the name of a .db file that contains the data needed or
                   14425: being set.
                   14426: 
                   14427: =back
                   14428: 
1.394     bowersj2 14429: =head1 OVERVIEW
1.191     harris41 14430: 
1.394     bowersj2 14431: lonnet provides subroutines which interact with the
                   14432: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14433: about classes, users, and resources.
1.243     albertel 14434: 
                   14435: For many of these objects you can also use this to store data about
                   14436: them or modify them in various ways.
1.191     harris41 14437: 
1.394     bowersj2 14438: =head2 Symbs
1.191     harris41 14439: 
1.394     bowersj2 14440: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14441: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14442: map, the resource number of the resource in the map, and the URL of
                   14443: the resource itself. The latter is somewhat redundant, but might help
                   14444: if maps change.
                   14445: 
                   14446: An example is
                   14447: 
                   14448:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14449: 
                   14450: The respective map entry is
                   14451: 
                   14452:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14453:   title="Problem 2">
                   14454:  </resource>
                   14455: 
                   14456: Symbs are used by the random number generator, as well as to store and
                   14457: restore data specific to a certain instance of for example a problem.
                   14458: 
                   14459: =head2 Storing And Retrieving Data
                   14460: 
                   14461: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14462: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14463: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14464: is is the non-critical message twin of cstore. These functions are for
                   14465: handlers to store a perl hash to a user's permanent data space in an
                   14466: easy manner, and to retrieve it again on another call. It is expected
                   14467: that a handler would use this once at the beginning to retrieve data,
                   14468: and then again once at the end to send only the new data back.
                   14469: 
                   14470: The data is stored in the user's data directory on the user's
                   14471: homeserver under the ID of the course.
                   14472: 
                   14473: The hash that is returned by restore will have all of the previous
                   14474: value for all of the elements of the hash.
                   14475: 
                   14476: Example:
                   14477: 
                   14478:  #creating a hash
                   14479:  my %hash;
                   14480:  $hash{'foo'}='bar';
                   14481: 
                   14482:  #storing it
                   14483:  &Apache::lonnet::cstore(\%hash);
                   14484: 
                   14485:  #changing a value
                   14486:  $hash{'foo'}='notbar';
                   14487: 
                   14488:  #adding a new value
                   14489:  $hash{'bar'}='foo';
                   14490:  &Apache::lonnet::cstore(\%hash);
                   14491: 
                   14492:  #retrieving the hash
                   14493:  my %history=&Apache::lonnet::restore();
                   14494: 
                   14495:  #print the hash
                   14496:  foreach my $key (sort(keys(%history))) {
                   14497:    print("\%history{$key} = $history{$key}");
                   14498:  }
                   14499: 
                   14500: Will print out:
1.191     harris41 14501: 
1.394     bowersj2 14502:  %history{1:foo} = bar
                   14503:  %history{1:keys} = foo:timestamp
                   14504:  %history{1:timestamp} = 990455579
                   14505:  %history{2:bar} = foo
                   14506:  %history{2:foo} = notbar
                   14507:  %history{2:keys} = foo:bar:timestamp
                   14508:  %history{2:timestamp} = 990455580
                   14509:  %history{bar} = foo
                   14510:  %history{foo} = notbar
                   14511:  %history{timestamp} = 990455580
                   14512:  %history{version} = 2
                   14513: 
                   14514: Note that the special hash entries C<keys>, C<version> and
                   14515: C<timestamp> were added to the hash. C<version> will be equal to the
                   14516: total number of versions of the data that have been stored. The
                   14517: C<timestamp> attribute will be the UNIX time the hash was
                   14518: stored. C<keys> is available in every historical section to list which
                   14519: keys were added or changed at a specific historical revision of a
                   14520: hash.
                   14521: 
                   14522: B<Warning>: do not store the hash that restore returns directly. This
                   14523: will cause a mess since it will restore the historical keys as if the
                   14524: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14525: 
1.394     bowersj2 14526: Calling convention:
1.191     harris41 14527: 
1.1225    raeburn  14528:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14529:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14530: 
1.394     bowersj2 14531: For more detailed information, see lonnet specific documentation.
1.191     harris41 14532: 
1.394     bowersj2 14533: =head1 RETURN MESSAGES
1.191     harris41 14534: 
1.394     bowersj2 14535: =over 4
1.191     harris41 14536: 
1.394     bowersj2 14537: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14538: 
1.394     bowersj2 14539: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14540: when the connection is brought back up
1.191     harris41 14541: 
1.394     bowersj2 14542: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14543: for later delivery
1.191     harris41 14544: 
1.967     bisitz   14545: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14546: 
1.394     bowersj2 14547: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14548: that was requested
1.191     harris41 14549: 
1.243     albertel 14550: =back
1.191     harris41 14551: 
1.243     albertel 14552: =head1 PUBLIC SUBROUTINES
1.191     harris41 14553: 
1.243     albertel 14554: =head2 Session Environment Functions
1.191     harris41 14555: 
1.243     albertel 14556: =over 4
1.191     harris41 14557: 
1.394     bowersj2 14558: =item * 
                   14559: X<appenv()>
1.949     raeburn  14560: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14561: the user envirnoment file, and will be restored for each access this
1.620     albertel 14562: user makes during this session, also modifies the %env for the current
1.949     raeburn  14563: process. Optional rolesarrayref - if defined contains a reference to an array
                   14564: of roles which are exempt from the restriction on modifying user.role entries 
                   14565: in the user's environment.db and in %env.    
1.191     harris41 14566: 
                   14567: =item *
1.394     bowersj2 14568: X<delenv()>
1.987     raeburn  14569: B<delenv($delthis,$regexp)>: removes all items from the session
                   14570: environment file that begin with $delthis. If the 
                   14571: optional second arg - $regexp - is true, $delthis is treated as a 
                   14572: regular expression, otherwise \Q$delthis\E is used. 
                   14573: The values are also deleted from the current processes %env.
1.191     harris41 14574: 
1.795     albertel 14575: =item * get_env_multiple($name) 
                   14576: 
                   14577: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14578: values may be defined and end up as an array ref.
                   14579: 
                   14580: returns an array of values
                   14581: 
1.243     albertel 14582: =back
                   14583: 
                   14584: =head2 User Information
1.191     harris41 14585: 
1.243     albertel 14586: =over 4
1.191     harris41 14587: 
                   14588: =item *
1.394     bowersj2 14589: X<queryauthenticate()>
                   14590: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14591: authentication scheme
                   14592: 
                   14593: =item *
1.394     bowersj2 14594: X<authenticate()>
1.1073    raeburn  14595: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14596: authenticate user from domain's lib servers (first use the current
                   14597: one). C<$upass> should be the users password.
1.1073    raeburn  14598: $checkdefauth is optional (value is 1 if a check should be made to
                   14599:    authenticate user using default authentication method, and allow
                   14600:    account creation if username does not have account in the domain).
                   14601: $clientcancheckhost is optional (value is 1 if checking whether the
                   14602:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14603: 
                   14604: =item *
1.394     bowersj2 14605: X<homeserver()>
                   14606: B<homeserver($uname,$udom)>: find the server which has
                   14607: the user's directory and files (there must be only one), this caches
                   14608: the answer, and also caches if there is a borken connection.
1.191     harris41 14609: 
                   14610: =item *
1.394     bowersj2 14611: X<idget()>
1.1300    raeburn  14612: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14613: a list of student/employee IDs or clicker IDs
                   14614: (student/employee IDs are a unique resource in a domain, there must be 
                   14615: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14616: clickerIDs are not necessarily unique, as students might share clickers.
                   14617: (returns hash: id=>name,id=>name)
1.191     harris41 14618: 
                   14619: =item *
1.394     bowersj2 14620: X<idrget()>
                   14621: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14622: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14623: 
                   14624: =item *
1.394     bowersj2 14625: X<idput()>
1.1300    raeburn  14626: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14627: names and associated student/employee IDs or clicker IDs.
                   14628: 
                   14629: =item *
                   14630: X<iddel()>
                   14631: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14632: student/employee ID or clicker ID username look-ups from domain.
                   14633: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14634: If no $uhome is provided, it will be determined usig &homeserver()
                   14635: for each user.  If no $namespace is provided, the default is ids.
                   14636: 
                   14637: =item *
                   14638: X<updateclickers()>
                   14639: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14640: clicker ID-to-username look-ups in clickers.db on library server.
                   14641: Permitted actions are add or del (i.e., add or delete). The 
                   14642: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14643: value is an escaped comma-separated list of usernames (for whom the
                   14644: library server is the homeserver), who registered that particular ID.
                   14645: If $critical is true, the update will be sent via &critical, otherwise
                   14646: &reply() will be used.
1.191     harris41 14647: 
                   14648: =item *
1.394     bowersj2 14649: X<rolesinit()>
1.1169    droeschl 14650: B<rolesinit($udom,$username)>: get user privileges.
                   14651: returns user role, first access and timer interval hashes
1.243     albertel 14652: 
                   14653: =item *
1.1171    droeschl 14654: X<privileged()>
                   14655: B<privileged($username,$domain)>: returns a true if user has a
                   14656: privileged and active role (i.e. su or dc), false otherwise.
                   14657: 
                   14658: =item *
1.551     albertel 14659: X<getsection()>
                   14660: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14661: course $cname, return section name/number or '' for "not in course"
                   14662: and '-1' for "no section"
                   14663: 
                   14664: =item *
1.394     bowersj2 14665: X<userenvironment()>
                   14666: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14667: passed in @what from the requested user's environment, returns a hash
                   14668: 
1.858     raeburn  14669: =item * 
                   14670: X<userlog_query()>
1.859     albertel 14671: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14672: activity.log file. %filters defines filters applied when parsing the
                   14673: log file. These can be start or end timestamps, or the type of action
                   14674: - log to look for Login or Logout events, check for Checkin or
                   14675: Checkout, role for role selection. The response is in the form
                   14676: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14677: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14678: 
1.243     albertel 14679: =back
                   14680: 
                   14681: =head2 User Roles
                   14682: 
                   14683: =over 4
                   14684: 
                   14685: =item *
                   14686: 
1.1284    raeburn  14687: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14688: returns codes for allowed actions.
                   14689: 
                   14690: The first argument is required, all others are optional.
                   14691: 
                   14692: $priv is the privilege being checked.
                   14693: $uri contains additional information about what is being checked for access (e.g.,
                   14694: URL, course ID etc.). 
                   14695: $symb is the unique resource instance identifier in a course; if needed,
                   14696: but not provided, it will be retrieved via a call to &symbread(). 
                   14697: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14698: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14699: files).
                   14700: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14701: prevents recursive calls to &allowed.
                   14702: 
1.243     albertel 14703:  F: full access
                   14704:  U,I,K: authentication modes (cxx only)
                   14705:  '': forbidden
                   14706:  1: user needs to choose course
                   14707:  2: browse allowed
1.766     albertel 14708:  A: passphrase authentication needed
1.1284    raeburn  14709:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14710: 
                   14711: =item *
                   14712: 
1.1192    raeburn  14713: constructaccess($url,$setpriv) : check for access to construction space URL
                   14714: 
                   14715: See if the owner domain and name in the URL match those in the
                   14716: expected environment.  If so, return three element list
                   14717: ($ownername,$ownerdomain,$ownerhome).
                   14718: 
                   14719: Otherwise return the null string.
                   14720: 
                   14721: If second argument 'setpriv' is true, it assigns the privileges,
                   14722: and returns the same three element list, unless the owner has
                   14723: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14724: in which case the null string is returned.
                   14725: 
                   14726: =item *
                   14727: 
1.1326    raeburn  14728: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14729: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14730: for system, domain, and course level. $uname and $udom are optional (current
                   14731: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14732: 
                   14733: =item *
                   14734: 
1.988     raeburn  14735: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14736: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14737: $type is Course (default) or Community.
1.988     raeburn  14738: If $forcedefault evaluates to true, text returned will be default 
                   14739: text for $type. Otherwise, if this is a course, the text returned 
                   14740: will be a custom name for the role (if defined in the course's 
                   14741: environment).  If no custom name is defined the default is returned.
                   14742:    
1.832     raeburn  14743: =item *
                   14744: 
1.1219    raeburn  14745: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14746: All arguments are optional. Returns a hash of a roles, either for
                   14747: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14748: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14749: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14750: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14751: For each key, value is set to colon-separated start and end times for
                   14752: the role.  If no username and domain are specified, will default to
1.934     raeburn  14753: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14754: of role statuses (active, future or previous), roles 
                   14755: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14756: to restrict the list of roles reported. If no array ref is 
                   14757: provided for types, will default to return only active roles.
1.834     albertel 14758: 
1.1195    raeburn  14759: =item *
                   14760: 
                   14761: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14762: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14763: 
                   14764: Additional optional arguments are: $type (if role checking is to be restricted 
                   14765: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14766: available roles) or future (roles available in the future), and
                   14767: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14768: have active Domain Coordinator role in course's domain or in additional
                   14769: domains (specified in 'Domains to check for privileged users' in course
                   14770: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14771: 
                   14772: =item *
                   14773: 
                   14774: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14775: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14776: $possdomains and $possroles are optional array refs -- to domains to check and
                   14777: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14778: users' roles.db to check for a dc or su role in any domain. This can be
                   14779: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14780: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14781: this then allows &privileged_by_domain() to be used, which caches the identity
                   14782: of privileged users, eliminating the need for repeated calls to &dump().
                   14783: 
                   14784: =item *
                   14785: 
                   14786: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14787: where the outer hash keys are domains specified in the $possdomains array ref,
                   14788: next inner hash keys are privileged roles specified in the $roles array ref,
                   14789: and the innermost hash contains key = value pairs for username:domain = end:start
                   14790: for active or future "privileged" users with that role in that domain. To avoid
                   14791: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14792: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14793: 
1.243     albertel 14794: =back
                   14795: 
                   14796: =head2 User Modification
                   14797: 
                   14798: =over 4
                   14799: 
                   14800: =item *
                   14801: 
1.957     raeburn  14802: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14803: user for the level given by URL.  Optional start and end dates (leave empty
                   14804: string or zero for "no date")
1.191     harris41 14805: 
                   14806: =item *
                   14807: 
1.243     albertel 14808: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14809: change a users, password, possible return values are: ok,
                   14810: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14811: refused
1.191     harris41 14812: 
                   14813: =item *
                   14814: 
1.243     albertel 14815: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14816: 
                   14817: =item *
                   14818: 
1.1058    raeburn  14819: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14820:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14821: 
                   14822: will update user information (firstname,middlename,lastname,generation,
                   14823: permanentemail), and if forceid is true, student/employee ID also.
                   14824: A user's institutional affiliation(s) can also be updated.
                   14825: User information fields will not be overwritten with empty entries 
                   14826: unless the field is included in the $candelete array reference.
                   14827: This array is included when a single user is modified via "Manage Users",
                   14828: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14829: 
                   14830: =item *
                   14831: 
1.286     matthew  14832: modifystudent
                   14833: 
1.957     raeburn  14834: modify a student's enrollment and identification information.
1.1235    raeburn  14835: The course id is resolved based on the current user's environment.  
                   14836: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14837: associated with a course.
                   14838: 
1.297     matthew  14839: This call is essentially a wrapper for lonnet::modifyuser and
                   14840: lonnet::modify_student_enrollment
1.286     matthew  14841: 
                   14842: Inputs: 
                   14843: 
                   14844: =over 4
                   14845: 
1.957     raeburn  14846: =item B<$udom> Student's loncapa domain
1.286     matthew  14847: 
1.957     raeburn  14848: =item B<$uname> Student's loncapa login name
1.286     matthew  14849: 
1.964     bisitz   14850: =item B<$uid> Student/Employee ID
1.286     matthew  14851: 
1.957     raeburn  14852: =item B<$umode> Student's authentication mode
1.286     matthew  14853: 
1.957     raeburn  14854: =item B<$upass> Student's password
1.286     matthew  14855: 
1.957     raeburn  14856: =item B<$first> Student's first name
1.286     matthew  14857: 
1.957     raeburn  14858: =item B<$middle> Student's middle name
1.286     matthew  14859: 
1.957     raeburn  14860: =item B<$last> Student's last name
1.286     matthew  14861: 
1.957     raeburn  14862: =item B<$gene> Student's generation
1.286     matthew  14863: 
1.957     raeburn  14864: =item B<$usec> Student's section in course
1.286     matthew  14865: 
                   14866: =item B<$end> Unix time of the roles expiration
                   14867: 
                   14868: =item B<$start> Unix time of the roles start date
                   14869: 
                   14870: =item B<$forceid> If defined, allow $uid to be changed
                   14871: 
                   14872: =item B<$desiredhome> server to use as home server for student
                   14873: 
1.957     raeburn  14874: =item B<$email> Student's permanent e-mail address
                   14875: 
                   14876: =item B<$type> Type of enrollment (auto or manual)
                   14877: 
1.963     raeburn  14878: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14879: 
                   14880: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14881: 
1.963     raeburn  14882: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14883: 
1.963     raeburn  14884: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14885: 
1.1216    raeburn  14886: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14887: 
                   14888: =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  14889: 
1.286     matthew  14890: =back
1.297     matthew  14891: 
                   14892: =item *
                   14893: 
                   14894: modify_student_enrollment
                   14895: 
1.1235    raeburn  14896: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14897: 'role.request.course' must be defined for this function to proceed.
                   14898: 
                   14899: Inputs:
                   14900: 
                   14901: =over 4
                   14902: 
1.1235    raeburn  14903: =item $udom, student's domain
1.297     matthew  14904: 
1.1235    raeburn  14905: =item $uname, student's name
1.297     matthew  14906: 
1.1235    raeburn  14907: =item $uid, student's user id
1.297     matthew  14908: 
1.1235    raeburn  14909: =item $first, student's first name
1.297     matthew  14910: 
                   14911: =item $middle
                   14912: 
                   14913: =item $last
                   14914: 
                   14915: =item $gene
                   14916: 
                   14917: =item $usec
                   14918: 
                   14919: =item $end
                   14920: 
                   14921: =item $start
                   14922: 
1.957     raeburn  14923: =item $type
                   14924: 
                   14925: =item $locktype
                   14926: 
                   14927: =item $cid
                   14928: 
                   14929: =item $selfenroll
                   14930: 
                   14931: =item $context
                   14932: 
1.1216    raeburn  14933: =item $credits, number of credits student will earn from this class
                   14934: 
1.1314    raeburn  14935: =item $instsec, institutional course section code for student
                   14936: 
1.297     matthew  14937: =back
                   14938: 
1.191     harris41 14939: 
                   14940: =item *
                   14941: 
1.243     albertel 14942: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14943: custom role; give a custom role to a user for the level given by URL.  Specify
                   14944: name and domain of role author, and role name
1.191     harris41 14945: 
                   14946: =item *
                   14947: 
1.243     albertel 14948: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14949: 
                   14950: =item *
                   14951: 
1.243     albertel 14952: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14953: 
                   14954: =back
                   14955: 
                   14956: =head2 Course Infomation
                   14957: 
                   14958: =over 4
1.191     harris41 14959: 
                   14960: =item *
                   14961: 
1.1118    foxr     14962: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14963: specified course id, including all environment settings for the
                   14964: course, the description of the course will be in the hash under the
                   14965: key 'description'
1.191     harris41 14966: 
1.1118    foxr     14967: $options is an optional parameter that if supplied is a hash reference that controls
                   14968: what how this function works.  It has the following key/values:
                   14969: 
                   14970: =over 4
                   14971: 
                   14972: =item freshen_cache
                   14973: 
                   14974: If defined, and the environment cache for the course is valid, it is 
                   14975: returned in the returned hash.
                   14976: 
                   14977: =item one_time
                   14978: 
                   14979: If defined, the last cache time is set to _now_
                   14980: 
                   14981: =item user
                   14982: 
                   14983: If defined, the supplied username is used instead of the current user.
                   14984: 
                   14985: 
                   14986: =back
                   14987: 
1.191     harris41 14988: =item *
                   14989: 
1.624     albertel 14990: resdata($name,$domain,$type,@which) : request for current parameter
                   14991: setting for a specific $type, where $type is either 'course' or 'user',
                   14992: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14993: answers for 10 minutes.
1.243     albertel 14994: 
1.877     foxr     14995: =item *
                   14996: 
                   14997: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14998: data base, returning a hash that is keyed by the resource name and has
                   14999: values that are the resource value.  I believe that the timestamps and
                   15000: versions are also returned.
                   15001: 
1.1236    raeburn  15002: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15003: supplemental content area. This routine caches the number of files for 
                   15004: 10 minutes.
                   15005: 
1.243     albertel 15006: =back
                   15007: 
                   15008: =head2 Course Modification
                   15009: 
                   15010: =over 4
1.191     harris41 15011: 
                   15012: =item *
                   15013: 
1.243     albertel 15014: writecoursepref($courseid,%prefs) : write preferences (environment
                   15015: database) for a course
1.191     harris41 15016: 
                   15017: =item *
                   15018: 
1.1011    raeburn  15019: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15020: 
                   15021: =item *
                   15022: 
1.1038    raeburn  15023: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15024: 
1.1167    droeschl 15025: =item *
                   15026: 
                   15027: is_course($courseid), is_course($cdom, $cnum)
                   15028: 
                   15029: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15030: two component version $cdom, $cnum. It checks if the specified course exists.
                   15031: 
                   15032: Returns:
                   15033:     undef if the course doesn't exist, otherwise
                   15034:     in scalar context the combined courseid.
                   15035:     in list context the two components of the course identifier, domain and 
                   15036:     courseid.    
                   15037: 
1.243     albertel 15038: =back
                   15039: 
                   15040: =head2 Resource Subroutines
                   15041: 
                   15042: =over 4
1.191     harris41 15043: 
                   15044: =item *
                   15045: 
1.243     albertel 15046: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15047: 
                   15048: =item *
                   15049: 
1.243     albertel 15050: repcopy($filename) : subscribes to the requested file, and attempts to
                   15051: replicate from the owning library server, Might return
1.607     raeburn  15052: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15053: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15054: resource. Expects the local filesystem pathname
                   15055: (/home/httpd/html/res/....)
                   15056: 
                   15057: =back
                   15058: 
                   15059: =head2 Resource Information
                   15060: 
                   15061: =over 4
1.191     harris41 15062: 
                   15063: =item *
                   15064: 
1.1228    raeburn  15065: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15066: and returns the value of a variety of different possible values,
                   15067: $varname should be a request string, and the other parameters can be
                   15068: used to specify who and what one is asking about. Ordinarily, $cid 
                   15069: does not need to be specified, as it is retrived from 
                   15070: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15071: within lonuserstate::loadmap() when initializing a course, before
                   15072: $env{'request.course.id'} has been set, so it needs to be provided
                   15073: in that one case.
1.243     albertel 15074: 
                   15075: Possible values for $varname are environment.lastname (or other item
                   15076: from the envirnment hash), user.name (or someother aspect about the
                   15077: user), resource.0.maxtries (or some other part and parameter of a
                   15078: resource)
1.204     albertel 15079: 
                   15080: =item *
                   15081: 
1.243     albertel 15082: directcondval($number) : get current value of a condition; reads from a state
                   15083: string
1.204     albertel 15084: 
                   15085: =item *
                   15086: 
1.243     albertel 15087: condval($condidx) : value of condition index based on state
1.204     albertel 15088: 
                   15089: =item *
                   15090: 
1.1362    raeburn  15091: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15092: resource's metadata, $what should be either a specific key, or either
                   15093: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15094: packages that this resource currently uses, the last 3 arguments are 
                   15095: only used internally for recursive metadata.
                   15096: 
                   15097: the toolsymb is only used where the uri is for an external tool (for which
                   15098: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15099: 
1.1371    raeburn  15100: this function automatically caches all requests except any made recursively
                   15101: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15102: defined).
1.191     harris41 15103: 
                   15104: =item *
                   15105: 
1.243     albertel 15106: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15107: network of library servers; returns file handle of where SQL and regex results
                   15108: will be stored for query
1.191     harris41 15109: 
                   15110: =item *
                   15111: 
1.1282    raeburn  15112: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15113: return symbolic list entry (all arguments optional). 
                   15114: 
                   15115: Args: filename is the filename (including path) for the file for which a symb 
                   15116: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15117: to check access status if more than one resource was found in the bighash 
                   15118: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15119: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15120: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15121: cause possible symbs to be checked to determine if they are subject to content
                   15122: blocking, if so they will not be included as possible symbs; possibles is a
                   15123: ref to a hash, which, as a side effect, will be populated with all possible 
                   15124: symbs (content blocking not tested).
                   15125:  
1.243     albertel 15126: returns the data handle
1.191     harris41 15127: 
                   15128: =item *
                   15129: 
1.1190    raeburn  15130: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15131: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15132: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15133: on failure, user must be in a course, as it assumes the existence of
                   15134: the course initial hash, and uses $env('request.course.id'}.  The third
                   15135: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15136: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15137: encrypted; otherwise it will be null.  
1.191     harris41 15138: 
                   15139: =item *
                   15140: 
1.243     albertel 15141: symbclean($symb) : removes versions numbers from a symb, returns the
                   15142: cleaned symb
1.191     harris41 15143: 
                   15144: =item *
                   15145: 
1.243     albertel 15146: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15147: course map, user must be in a course for it to work.
1.191     harris41 15148: 
                   15149: =item *
                   15150: 
1.243     albertel 15151: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15152: 
                   15153: =item *
                   15154: 
1.243     albertel 15155: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15156: a random seed, all arguments are optional, if they aren't sent it uses the
                   15157: environment to derive them. Note: if symb isn't sent and it can't get one
                   15158: from &symbread it will use the current time as its return value
1.191     harris41 15159: 
                   15160: =item *
                   15161: 
1.243     albertel 15162: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15163: unfakeable, receipt
1.191     harris41 15164: 
                   15165: =item *
                   15166: 
1.620     albertel 15167: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15168: 
                   15169: =item *
                   15170: 
1.243     albertel 15171: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15172: 
                   15173: =item *
                   15174: 
1.243     albertel 15175: 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 15176: 
                   15177: =item *
                   15178: 
1.243     albertel 15179: 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 15180: 
                   15181: =item *
                   15182: 
1.243     albertel 15183: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15184: 
                   15185: =item *
                   15186: 
1.243     albertel 15187: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15188: forcing spreadsheet to reevaluate the resource scores next time.
                   15189: 
1.1195    raeburn  15190: =item * 
                   15191: 
1.1196    raeburn  15192: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15193: when viewing in course context.
1.1195    raeburn  15194: 
1.1196    raeburn  15195:  input: six args -- filename (decluttered), course number, course domain,
                   15196:                     url, symb (if registered) and group (if this is a 
                   15197:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15198: 
1.1196    raeburn  15199:  output: array of five scalars --
1.1195    raeburn  15200:          $cfile -- url for file editing if editable on current server
                   15201:          $home -- homeserver of resource (i.e., for author if published,
                   15202:                                           or course if uploaded.).
                   15203:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15204:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15205:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15206: 
                   15207: =item *
                   15208: 
                   15209: is_course_upload($file,$cnum,$cdom)
                   15210: 
                   15211: Used in course context to determine if current file was uploaded to 
                   15212: the course (i.e., would be found in /userfiles/docs on the course's 
                   15213: homeserver.
                   15214: 
                   15215:   input: 3 args -- filename (decluttered), course number and course domain.
                   15216:   output: boolean -- 1 if file was uploaded.
                   15217: 
1.243     albertel 15218: =back
                   15219: 
                   15220: =head2 Storing/Retreiving Data
                   15221: 
                   15222: =over 4
1.191     harris41 15223: 
                   15224: =item *
                   15225: 
1.1269    raeburn  15226: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15227: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15228: the remaining args aren't required and if they aren't passed or are '' they will
                   15229: be derived from the env (with the exception of $laststore, which is an 
                   15230: optional arg used when a user's submission is stored in grading).
                   15231: $laststore is $version=$timestamp, where $version is the most recent version
                   15232: number retrieved for the corresponding $symb in the $namespace db file, and
                   15233: $timestamp is the timestamp for that transaction (UNIX time).
                   15234: $laststore is currently only passed when cstore() is called by 
                   15235: structuretags::finalize_storage().
1.191     harris41 15236: 
                   15237: =item *
                   15238: 
1.1269    raeburn  15239: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15240: but uses critical subroutine
1.191     harris41 15241: 
                   15242: =item *
                   15243: 
1.243     albertel 15244: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15245: all args are optional
1.191     harris41 15246: 
                   15247: =item *
                   15248: 
1.717     albertel 15249: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15250: dumps the complete (or key matching regexp) namespace into a hash
                   15251: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15252: normally &store()ed into
                   15253: 
                   15254: $range should be either an integer '100' (give me the first 100
                   15255:                                            matching records)
                   15256:               or be  two integers sperated by a - with no spaces
                   15257:                  '30-50' (give me the 30th through the 50th matching
                   15258:                           records)
                   15259: 
                   15260: 
                   15261: =item *
                   15262: 
1.1269    raeburn  15263: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15264: replaces a &store() version of data with a replacement set of data
                   15265: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15266: reference. If $tolog is true, the transaction is logged in the courselog
                   15267: with an action=PUTSTORE.
1.717     albertel 15268: 
                   15269: =item *
                   15270: 
1.243     albertel 15271: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15272: works very similar to store/cstore, but all data is stored in a
                   15273: temporary location and can be reset using tmpreset, $storehash should
                   15274: be a hash reference, returns nothing on success
1.191     harris41 15275: 
                   15276: =item *
                   15277: 
1.243     albertel 15278: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15279: similar to restore, but all data is stored in a temporary location and
                   15280: can be reset using tmpreset. Returns a hash of values on success,
                   15281: error string otherwise.
1.191     harris41 15282: 
                   15283: =item *
                   15284: 
1.243     albertel 15285: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15286: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15287: 
                   15288: =item *
                   15289: 
1.243     albertel 15290: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15291: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15292: 
                   15293: =item *
                   15294: 
1.243     albertel 15295: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15296: namesp ($udom and $uname are optional)
1.191     harris41 15297: 
                   15298: =item *
                   15299: 
1.702     albertel 15300: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15301: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15302: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15303: 
1.702     albertel 15304: $range should be either an integer '100' (give me the first 100
                   15305:                                            matching records)
                   15306:               or be  two integers sperated by a - with no spaces
                   15307:                  '30-50' (give me the 30th through the 50th matching
                   15308:                           records)
1.449     matthew  15309: =item *
                   15310: 
                   15311: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15312: $store can be a scalar, an array reference, or if the amount to be 
                   15313: incremented is > 1, a hash reference.
                   15314: 
                   15315: ($udom and $uname are optional)
1.191     harris41 15316: 
                   15317: =item *
                   15318: 
1.243     albertel 15319: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15320: ($udom and $uname are optional)
1.191     harris41 15321: 
                   15322: =item *
                   15323: 
1.243     albertel 15324: cput($namespace,$storehash,$udom,$uname) : critical put
                   15325: ($udom and $uname are optional)
1.191     harris41 15326: 
                   15327: =item *
                   15328: 
1.748     albertel 15329: newput($namespace,$storehash,$udom,$uname) :
                   15330: 
                   15331: Attempts to store the items in the $storehash, but only if they don't
                   15332: currently exist, if this succeeds you can be certain that you have 
                   15333: successfully created a new key value pair in the $namespace db.
                   15334: 
                   15335: 
                   15336: Args:
                   15337:  $namespace: name of database to store values to
                   15338:  $storehash: hashref to store to the db
                   15339:  $udom: (optional) domain of user containing the db
                   15340:  $uname: (optional) name of user caontaining the db
                   15341: 
                   15342: Returns:
                   15343:  'ok' -> succeeded in storing all keys of $storehash
                   15344:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15345:                         least <key> already existed in the db (other
                   15346:                         requested keys may also already exist)
1.967     bisitz   15347:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15348:  'con_lost' -> unable to contact request server
                   15349:  'refused' -> action was not allowed by remote machine
                   15350: 
                   15351: 
                   15352: =item *
                   15353: 
1.243     albertel 15354: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15355: reference filled in from namesp (encrypts the return communication)
                   15356: ($udom and $uname are optional)
1.191     harris41 15357: 
                   15358: =item *
                   15359: 
1.243     albertel 15360: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15361: critical subroutine
                   15362: 
1.806     raeburn  15363: =item *
                   15364: 
1.860     raeburn  15365: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15366: array reference filled in from namespace found in domain level on either
                   15367: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15368: 
                   15369: =item *
                   15370: 
1.860     raeburn  15371: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15372: domain level either on specified domain server ($uhome) or primary domain 
                   15373: server ($udom and $uhome are optional)
1.806     raeburn  15374: 
1.943     raeburn  15375: =item * 
                   15376: 
1.1240    raeburn  15377: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15378: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15379: the target domain.
                   15380: 
                   15381: May also include additional key => value pairs for the following groups:
                   15382: 
                   15383: =over
                   15384: 
                   15385: =item
                   15386: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15387: 
                   15388: =over
                   15389: 
                   15390: =item defaultquota, authorquota
                   15391: 
                   15392: =back
                   15393: 
                   15394: =item
                   15395: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15396: portfolio for users).
                   15397: 
                   15398: =over
                   15399: 
                   15400: =item
                   15401: aboutme, blog, webdav, portfolio
                   15402: 
                   15403: =back
                   15404: 
                   15405: =item
                   15406: requestcourses: ability to request courses, and how requests are processed.
                   15407: 
                   15408: =over
                   15409: 
                   15410: =item
1.1305    raeburn  15411: official, unofficial, community, textbook, placement
1.1240    raeburn  15412: 
                   15413: =back
                   15414: 
                   15415: =item
                   15416: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15417: 
                   15418: =over
                   15419: 
                   15420: =item
1.1256    raeburn  15421: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15422: 
                   15423: =back
                   15424: 
                   15425: =item
                   15426: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15427: for course's uploaded content.
                   15428: 
                   15429: =over
                   15430: 
                   15431: =item
1.1246    raeburn  15432: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15433: communityquota, textbookquota, placementquota
1.1240    raeburn  15434: 
                   15435: =back
                   15436: 
                   15437: =item
                   15438: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15439: on your servers.
                   15440: 
                   15441: =over
                   15442: 
                   15443: =item 
                   15444: remotesessions, hostedsessions
                   15445: 
                   15446: =back
                   15447: 
                   15448: =back
                   15449: 
                   15450: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15451: utility to create a configuration.db file on a domain's primary library server 
                   15452: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15453: -- corresponding values are authentication type (internal, krb4, krb5,
                   15454: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15455: will be available. Values are retrieved from cache (if current), unless the
                   15456: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15457: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15458: 
                   15459: Typical usage:
1.943     raeburn  15460: 
1.1240    raeburn  15461: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15462: 
1.243     albertel 15463: =back
                   15464: 
                   15465: =head2 Network Status Functions
                   15466: 
                   15467: =over 4
1.191     harris41 15468: 
                   15469: =item *
                   15470: 
1.1137    raeburn  15471: dirlist() : return directory list based on URI (first arg).
                   15472: 
                   15473: Inputs: 1 required, 5 optional.
                   15474: 
                   15475: =over
                   15476: 
                   15477: =item 
                   15478: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15479: 
                   15480: =item
                   15481: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15482: 
                   15483: =item
                   15484: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15485: 
                   15486: =item
                   15487: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15488: 
                   15489: =item
                   15490: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15491: 
                   15492: =item 
                   15493: $alternateRoot - path to prepend in place of path from $uri.
                   15494: 
                   15495: =back
                   15496: 
                   15497: Returns: Array of up to two items.
                   15498: 
                   15499: =over
                   15500: 
                   15501: a reference to an array of files/subdirectories
                   15502: 
                   15503: =over
                   15504: 
                   15505: Each element in the array of files/subdirectories is a & separated list of
                   15506: item name and the result of running stat on the item.  If dirlist was requested
                   15507: for a file instead of a directory, the item name will be ''. For a directory 
                   15508: listing, if the item is a metadata file, the element will end &N&M 
                   15509: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15510: default copyright set (1).  
                   15511: 
                   15512: =back
                   15513: 
                   15514: a scalar containing error condition (if encountered).
                   15515: 
                   15516: =over
                   15517: 
                   15518: =item 
                   15519: no_host (no homeserver identified for $username:$domain).
                   15520: 
                   15521: =item 
                   15522: no_such_host (server contacted for listing not identified as valid host).
                   15523: 
                   15524: =item 
                   15525: con_lost (connection to remote server failed).
                   15526: 
                   15527: =item 
                   15528: refused (invalid $username:$domain received on lond side).
                   15529: 
                   15530: =item 
                   15531: no_such_dir (directory at specified path on lond side does not exist). 
                   15532: 
                   15533: =item 
                   15534: empty (directory at specified path on lond side is empty).
                   15535: 
                   15536: =over
                   15537: 
                   15538: This is currently not encountered because the &ls3, &ls2, 
                   15539: &ls (_handler) routines on the lond side do not filter out
                   15540: . and .. from a directory listing. 
                   15541: 
                   15542: =back
                   15543: 
                   15544: =back
                   15545: 
                   15546: =back
1.191     harris41 15547: 
                   15548: =item *
                   15549: 
1.243     albertel 15550: spareserver() : find server with least workload from spare.tab
                   15551: 
1.986     foxr     15552: 
                   15553: =item *
                   15554: 
                   15555: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15556: if there is no corresponding loncapa host.
                   15557: 
1.243     albertel 15558: =back
                   15559: 
1.986     foxr     15560: 
1.243     albertel 15561: =head2 Apache Request
                   15562: 
                   15563: =over 4
1.191     harris41 15564: 
                   15565: =item *
                   15566: 
1.243     albertel 15567: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15568: localhost, posts hash
                   15569: 
                   15570: =back
                   15571: 
                   15572: =head2 Data to String to Data
                   15573: 
                   15574: =over 4
1.191     harris41 15575: 
                   15576: =item *
                   15577: 
1.243     albertel 15578: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15579: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15580: 
                   15581: =item *
                   15582: 
1.243     albertel 15583: hashref2str($hashref) : convert a hashref into a string complete with
                   15584: escaping and '=' and '&' separators, supports elements that are
                   15585: arrayrefs and hashrefs
1.191     harris41 15586: 
                   15587: =item *
                   15588: 
1.243     albertel 15589: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15590: with escaping and '&' separators, supports elements that are arrayrefs
                   15591: and hashrefs
1.191     harris41 15592: 
                   15593: =item *
                   15594: 
1.243     albertel 15595: str2hash($string) : convert string to hash using unescaping and
                   15596: splitting on '=' and '&', supports elements that are arrayrefs and
                   15597: hashrefs
1.191     harris41 15598: 
                   15599: =item *
                   15600: 
1.243     albertel 15601: str2array($string) : convert string to hash using unescaping and
                   15602: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15603: 
                   15604: =back
                   15605: 
                   15606: =head2 Logging Routines
                   15607: 
                   15608: 
                   15609: These routines allow one to make log messages in the lonnet.log and
                   15610: lonnet.perm logfiles.
1.191     harris41 15611: 
1.1119    foxr     15612: =over 4
                   15613: 
1.191     harris41 15614: =item *
                   15615: 
1.243     albertel 15616: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15617: 
                   15618: =item *
                   15619: 
1.243     albertel 15620: logthis() : append message to the normal lonnet.log file, it gets
                   15621: preiodically rolled over and deleted.
1.191     harris41 15622: 
                   15623: =item *
                   15624: 
1.243     albertel 15625: logperm() : append a permanent message to lonnet.perm.log, this log
                   15626: file never gets deleted by any automated portion of the system, only
                   15627: messages of critical importance should go in here.
                   15628: 
1.1119    foxr     15629: 
1.243     albertel 15630: =back
                   15631: 
                   15632: =head2 General File Helper Routines
                   15633: 
                   15634: =over 4
1.191     harris41 15635: 
                   15636: =item *
                   15637: 
1.481     raeburn  15638: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15639: (a) files in /uploaded
                   15640:   (i) If a local copy of the file exists - 
                   15641:       compares modification date of local copy with last-modified date for 
                   15642:       definitive version stored on home server for course. If local copy is 
                   15643:       stale, requests a new version from the home server and stores it. 
                   15644:       If the original has been removed from the home server, then local copy 
                   15645:       is unlinked.
                   15646:   (ii) If local copy does not exist -
                   15647:       requests the file from the home server and stores it. 
                   15648:   
                   15649:   If $caller is 'uploadrep':  
                   15650:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15651:     for request for files originally uploaded via DOCS. 
                   15652:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15653:   
                   15654:   Otherwise:
                   15655:      This indicates a call from the content generation phase of the request.
                   15656:      -  returns the entire contents of the file or -1.
                   15657:      
                   15658: (b) files in /res
                   15659:    - returns the entire contents of a file or -1; 
                   15660:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15661: 
1.712     albertel 15662: 
                   15663: =item *
                   15664: 
                   15665: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15666:                   reference
                   15667: 
                   15668: returns either a stat() list of data about the file or an empty list
                   15669: if the file doesn't exist or couldn't find out about it (connection
                   15670: problems or user unknown)
                   15671: 
1.191     harris41 15672: =item *
                   15673: 
1.243     albertel 15674: filelocation($dir,$file) : returns file system location of a file
                   15675: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15676: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15677: and a file of ../bob will become /a/bob)
1.191     harris41 15678: 
                   15679: =item *
                   15680: 
                   15681: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15682: filelocation except for hrefs
                   15683: 
                   15684: =item *
                   15685: 
1.1261    raeburn  15686: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15687: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15688: 
1.243     albertel 15689: =back
                   15690: 
1.608     albertel 15691: =head2 Usererfile file routines (/uploaded*)
                   15692: 
                   15693: =over 4
                   15694: 
                   15695: =item *
                   15696: 
                   15697: userfileupload(): main rotine for putting a file in a user or course's
                   15698:                   filespace, arguments are,
                   15699: 
1.620     albertel 15700:  formname - required - this is the name of the element in $env where the
1.608     albertel 15701:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15702:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15703:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15704:  context - if coursedoc, store the file in the course of the active role
                   15705:              of the current user; 
                   15706:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15707:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15708:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15709:          if undefined, it will be placed in "unknown"
                   15710: 
                   15711:  (This routine calls clean_filename() to remove any dangerous
                   15712:  characters from the filename, and then calls finuserfileupload() to
                   15713:  complete the transaction)
                   15714: 
                   15715:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15716:  and /adm/notfound.html if unsuccessful
                   15717: 
                   15718: =item *
                   15719: 
                   15720: clean_filename(): routine for cleaing a filename up for storage in
                   15721:                  userfile space, argument is:
                   15722: 
                   15723:  filename - proposed filename
                   15724: 
                   15725: returns: the new clean filename
                   15726: 
                   15727: =item *
                   15728: 
1.1090    raeburn  15729: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15730: userspace, probably shouldn't be called directly
                   15731: 
                   15732:   docuname: username or courseid of destination for the file
                   15733:   docudom: domain of user/course of destination for the file
                   15734:   formname: same as for userfileupload()
1.1090    raeburn  15735:   fname: filename (including subdirectories) for the file
                   15736:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15737:   allfiles: reference to hash used to store objects found by parser
                   15738:   codebase: reference to hash used for codebases of java objects found by parser
                   15739:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15740:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15741:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15742:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15743:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15744:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15745:   mimetype: reference to scalar to accommodate mime type determined
                   15746:             from File::MMagic if $parser = parse.
1.608     albertel 15747: 
                   15748:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15749:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15750:  was 'overwrite').
                   15751:  
1.608     albertel 15752: 
                   15753: =item *
                   15754: 
                   15755: renameuserfile(): renames an existing userfile to a new name
                   15756: 
                   15757:   Args:
                   15758:    docuname: username or courseid of destination for the file
                   15759:    docudom: domain of user/course of destination for the file
                   15760:    old: current file name (including any subdirs under userfiles)
                   15761:    new: desired file name (including any subdirs under userfiles)
                   15762: 
                   15763: =item *
                   15764: 
                   15765: mkdiruserfile(): creates a directory is a userfiles dir
                   15766: 
                   15767:   Args:
                   15768:    docuname: username or courseid of destination for the file
                   15769:    docudom: domain of user/course of destination for the file
                   15770:    dir: dir to create (including any subdirs under userfiles)
                   15771: 
                   15772: =item *
                   15773: 
                   15774: removeuserfile(): removes a file that exists in userfiles
                   15775: 
                   15776:   Args:
                   15777:    docuname: username or courseid of destination for the file
                   15778:    docudom: domain of user/course of destination for the file
                   15779:    fname: filname to delete (including any subdirs under userfiles)
                   15780: 
                   15781: =item *
                   15782: 
                   15783: removeuploadedurl(): convience function for removeuserfile()
                   15784: 
                   15785:   Args:
                   15786:    url:  a full /uploaded/... url to delete
                   15787: 
1.747     albertel 15788: =item * 
                   15789: 
                   15790: get_portfile_permissions():
                   15791:   Args:
                   15792:     domain: domain of user or course contain the portfolio files
                   15793:     user: name of user or num of course contain the portfolio files
                   15794:   Returns:
                   15795:     hashref of a dump of the proper file_permissions.db
                   15796:    
                   15797: 
                   15798: =item * 
                   15799: 
                   15800: get_access_controls():
                   15801: 
                   15802: Args:
                   15803:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15804:   group: (optional) the group you want the files associated with
                   15805:   file: (optional) the file you want access info on
                   15806: 
                   15807: Returns:
1.749     raeburn  15808:     a hash (keys are file names) of hashes containing
                   15809:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15810:         values are XML containing access control settings (see below) 
1.747     albertel 15811: 
                   15812: Internal notes:
                   15813: 
1.749     raeburn  15814:  access controls are stored in file_permissions.db as key=value pairs.
                   15815:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15816:         where scope -> public,guest,course,group,domains or users.
                   15817:               end -> UNIX time for end of access (0 -> no end date)
                   15818:               start -> UNIX time for start of access
                   15819: 
                   15820:     value -> XML description of access control
                   15821:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15822:             <start></start>
                   15823:             <end></end>
                   15824: 
                   15825:             <password></password>  for scope type = guest
                   15826: 
                   15827:             <domain></domain>     for scope type = course or group
                   15828:             <number></number>
                   15829:             <roles id="">
                   15830:              <role></role>
                   15831:              <access></access>
                   15832:              <section></section>
                   15833:              <group></group>
                   15834:             </roles>
                   15835: 
                   15836:             <dom></dom>         for scope type = domains
                   15837: 
                   15838:             <users>             for scope type = users
                   15839:              <user>
                   15840:               <uname></uname>
                   15841:               <udom></udom>
                   15842:              </user>
                   15843:             </users>
                   15844:            </scope> 
                   15845:               
                   15846:  Access data is also aggregated for each file in an additional key=value pair:
                   15847:  key -> path to file/file_name\0accesscontrol 
                   15848:  value -> reference to hash
                   15849:           hash contains key = value pairs
                   15850:           where key = uniqueID:scope_end_start
                   15851:                 value = UNIX time record was last updated
                   15852: 
                   15853:           Used to improve speed of look-ups of access controls for each file.  
                   15854:  
                   15855:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15856: 
1.1198    raeburn  15857: =item *
                   15858: 
1.749     raeburn  15859: modify_access_controls():
                   15860: 
                   15861: Modifies access controls for a portfolio file
                   15862: Args
                   15863: 1. file name
                   15864: 2. reference to hash of required changes,
                   15865: 3. domain
                   15866: 4. username
                   15867:   where domain,username are the domain of the portfolio owner 
                   15868:   (either a user or a course) 
                   15869: 
                   15870: Returns:
                   15871: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15872: 2. result of deletions ('ok' or 'error', with error message).
                   15873: 3. reference to hash of any new or updated access controls.
                   15874: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15875:    key = integer (inbound ID)
1.1198    raeburn  15876:    value = uniqueID
                   15877: 
                   15878: =item *
                   15879: 
                   15880: get_timebased_id():
                   15881: 
                   15882: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15883: course via the Course Editor (e.g., folders, composite pages, 
                   15884: group bulletin boards).
                   15885: 
                   15886: Args: (first three required; six others optional)
                   15887: 
                   15888: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15889:    docssequence, or name of group
                   15890: 
                   15891: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15892:    e.g., num, boardids
                   15893: 
                   15894: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15895:    file will be named nohist_namespace.db
                   15896: 
                   15897: 4. cdom: domain of course; default is current course domain from %env
                   15898: 
                   15899: 5. cnum: course number; default is current course number from %env
                   15900: 
                   15901: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15902:    unix timestamp to form the suffix, if the plain timestamp is already
                   15903:    in use.  Default is to not do this, but simply increment the unix 
                   15904:    timestamp by 1 until a unique key is obtained.
                   15905: 
                   15906: 7. who: holder of locking key; defaults to user:domain for user.
                   15907: 
                   15908: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15909:    retrying); default is 3.
                   15910: 
                   15911: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15912: 
                   15913: Returns:
                   15914: 
                   15915: 1. suffix obtained (numeric)
                   15916: 
                   15917: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15918: 
                   15919: 3. error: contains (localized) error message if an error occurred.
                   15920: 
1.747     albertel 15921: 
1.608     albertel 15922: =back
                   15923: 
1.243     albertel 15924: =head2 HTTP Helper Routines
                   15925: 
                   15926: =over 4
                   15927: 
1.191     harris41 15928: =item *
                   15929: 
                   15930: escape() : unpack non-word characters into CGI-compatible hex codes
                   15931: 
                   15932: =item *
                   15933: 
                   15934: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15935: 
1.243     albertel 15936: =back
                   15937: 
                   15938: =head1 PRIVATE SUBROUTINES
                   15939: 
                   15940: =head2 Underlying communication routines (Shouldn't call)
                   15941: 
                   15942: =over 4
                   15943: 
                   15944: =item *
                   15945: 
                   15946: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15947: 
                   15948: =item *
                   15949: 
                   15950: reply() : uses subreply to send a message to remote machine, logs all failures
                   15951: 
                   15952: =item *
                   15953: 
                   15954: critical() : passes a critical message to another server; if cannot
                   15955: get through then place message in connection buffer directory and
                   15956: returns con_delayed, if incapable of saving message, returns
                   15957: con_failed
                   15958: 
                   15959: =item *
                   15960: 
                   15961: reconlonc() : tries to reconnect lonc client processes.
                   15962: 
                   15963: =back
                   15964: 
                   15965: =head2 Resource Access Logging
                   15966: 
                   15967: =over 4
                   15968: 
                   15969: =item *
                   15970: 
                   15971: flushcourselogs() : flush (save) buffer logs and access logs
                   15972: 
                   15973: =item *
                   15974: 
                   15975: courselog($what) : save message for course in hash
                   15976: 
                   15977: =item *
                   15978: 
                   15979: courseacclog($what) : save message for course using &courselog().  Perform
                   15980: special processing for specific resource types (problems, exams, quizzes, etc).
                   15981: 
1.191     harris41 15982: =item *
                   15983: 
                   15984: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15985: as a PerlChildExitHandler
1.243     albertel 15986: 
                   15987: =back
                   15988: 
                   15989: =head2 Other
                   15990: 
                   15991: =over 4
                   15992: 
                   15993: =item *
                   15994: 
                   15995: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15996: 
                   15997: =back
                   15998: 
                   15999: =cut
1.877     foxr     16000: 

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