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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1389  ! raeburn     4: # $Id: lonnet.pm,v 1.1388 2018/11/01 18:20:40 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.404     albertel  903: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  904: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  905: 	}
                    906: 	closedir(LONIDS);
                    907:     }
                    908:     my $userloadpercent=0;
                    909:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    910:     if ($maxuserload) {
1.371     albertel  911: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  912:     }
1.372     albertel  913:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  914:     return $userloadpercent;
1.283     www       915: }
                    916: 
1.1       albertel  917: # ------------------------------ Find server with least workload from spare.tab
1.11      www       918: 
1.1       albertel  919: sub spareserver {
1.1083    raeburn   920:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  921:     my $spare_server;
1.370     albertel  922:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  923:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    924:                                                      :  $userloadpercent;
1.1083    raeburn   925:     my ($uint_dom,$remotesessions);
                    926:     if (($udom ne '') && (&domain($udom) ne '')) {
                    927:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    928:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    929:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    930:         $remotesessions = $udomdefaults{'remotesessions'};
                    931:     }
1.1123    raeburn   932:     my $spareshash = &this_host_spares($udom);
                    933:     if (ref($spareshash) eq 'HASH') {
                    934:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    935:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   936:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    937:                                              $try_server));
1.1123    raeburn   938: 	        ($spare_server, $lowest_load) =
                    939: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    940:             }
1.1083    raeburn   941:         }
1.784     albertel  942: 
1.1123    raeburn   943:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    944: 
                    945:         if (!$found_server) {
                    946:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    947: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   948:                     next unless (&spare_can_host($udom,$uint_dom,
                    949:                                                  $remotesessions,$try_server));
1.1123    raeburn   950: 	            ($spare_server, $lowest_load) =
                    951: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    952:                 }
                    953: 	    }
                    954:         }
1.784     albertel  955:     }
                    956: 
                    957:     if (!$want_server_name) {
1.968     raeburn   958:         my $protocol = 'http';
                    959:         if ($protocol{$spare_server} eq 'https') {
                    960:             $protocol = $protocol{$spare_server};
                    961:         }
1.1001    raeburn   962:         if (defined($spare_server)) {
                    963:             my $hostname = &hostname($spare_server);
1.1083    raeburn   964:             if (defined($hostname)) {
1.1001    raeburn   965: 	        $spare_server = $protocol.'://'.$hostname;
                    966:             }
                    967:         }
1.784     albertel  968:     }
                    969:     return $spare_server;
                    970: }
                    971: 
                    972: sub compare_server_load {
1.1253    raeburn   973:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    974: 
                    975:     if ($required) {
                    976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    977:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    978:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    979:         if (($major eq '' && $minor eq '') ||
                    980:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    981:             return ($spare_server,$lowest_load);
                    982:         }
                    983:     }
1.784     albertel  984: 
                    985:     my $loadans     = &reply('load',    $try_server);
                    986:     my $userloadans = &reply('userload',$try_server);
                    987: 
                    988:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   989: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  990:     }
                    991: 
                    992:     my $load;
                    993:     if ($loadans =~ /\d/) {
                    994: 	if ($userloadans =~ /\d/) {
                    995: 	    #both are numbers, pick the bigger one
                    996: 	    $load = ($loadans > $userloadans) ? $loadans 
                    997: 		                              : $userloadans;
1.411     albertel  998: 	} else {
1.784     albertel  999: 	    $load = $loadans;
1.411     albertel 1000: 	}
1.784     albertel 1001:     } else {
                   1002: 	$load = $userloadans;
                   1003:     }
                   1004: 
                   1005:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1006: 	$spare_server = $try_server;
                   1007: 	$lowest_load  = $load;
1.370     albertel 1008:     }
1.784     albertel 1009:     return ($spare_server,$lowest_load);
1.202     matthew  1010: }
1.914     albertel 1011: 
                   1012: # --------------------------- ask offload servers if user already has a session
                   1013: sub find_existing_session {
                   1014:     my ($udom,$uname) = @_;
1.1123    raeburn  1015:     my $spareshash = &this_host_spares($udom);
                   1016:     if (ref($spareshash) eq 'HASH') {
                   1017:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1018:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1019:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1020:             }
                   1021:         }
                   1022:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1023:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1024:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1025:             }
                   1026:         }
1.914     albertel 1027:     }
                   1028:     return;
                   1029: }
                   1030: 
1.1389  ! raeburn  1031: # check if user's browser sent load balancer cookie and server still has session
        !          1032: # and is not overloaded.
        !          1033: sub check_for_balancer_cookie {
        !          1034:     my ($r,$update_mtime) = @_;
        !          1035:     my ($otherserver,$cookie);
        !          1036:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
        !          1037:     if (exists($cookies{'balanceID'})) {
        !          1038:         my $balid = $cookies{'balanceID'};
        !          1039:         $cookie=&LONCAPA::clean_handle($balid->value);
        !          1040:         my $balancedir=$r->dir_config('lonBalanceDir');
        !          1041:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
        !          1042:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
        !          1043:                 my ($possudom,$possuname) = ($1,$2);
        !          1044:                 my $has_session = 0;
        !          1045:                 if ((&domain($possudom) ne '') &&
        !          1046:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
        !          1047:                     my $try_server;
        !          1048:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
        !          1049:                     if ($opened) {
        !          1050:                         flock($idf,LOCK_SH);
        !          1051:                         while (my $line = <$idf>) {
        !          1052:                             chomp($line);
        !          1053:                             if (&hostname($line) ne '') {
        !          1054:                                 $try_server = $line;
        !          1055:                                 last;
        !          1056:                             }
        !          1057:                         }
        !          1058:                         close($idf);
        !          1059:                         if (($try_server) &&
        !          1060:                             (&has_user_session($try_server,$possudom,$possuname))) {
        !          1061:                             my $lowest_load = 30000;
        !          1062:                             ($otherserver,$lowest_load) =
        !          1063:                                 &compare_server_load($try_server,undef,$lowest_load);
        !          1064:                             if ($otherserver ne '' && $lowest_load < 100) {
        !          1065:                                 $has_session = 1;
        !          1066:                             } else {
        !          1067:                                 undef($otherserver);
        !          1068:                             }
        !          1069:                         }
        !          1070:                     }
        !          1071:                 }
        !          1072:                 if ($has_session) {
        !          1073:                     if ($update_mtime) {
        !          1074:                         my $atime = my $mtime = time;
        !          1075:                         utime($atime,$mtime,"$balancedir/$cookie.id");
        !          1076:                     }
        !          1077:                 } else {
        !          1078:                     unlink("$balancedir/$cookie.id");
        !          1079:                 }
        !          1080:             }
        !          1081:         }
        !          1082:     }
        !          1083:     return ($otherserver,$cookie);
        !          1084: }
        !          1085: 
        !          1086: sub delbalcookie {
        !          1087:     my ($cookie,$balancer) =@_;
        !          1088:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
        !          1089:         my ($udom,$uname) = ($1,$2);
        !          1090:         my $uprimary_id = &domain($udom,'primary');
        !          1091:         my $uintdom = &internet_dom($uprimary_id);
        !          1092:         my $intdom = &internet_dom($balancer);
        !          1093:         my $serverhomedom = &host_domain($balancer);
        !          1094:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
        !          1095:             return &reply("delbalcookie:$cookie",$balancer);
        !          1096:         }
        !          1097:     }
        !          1098: }
        !          1099: 
1.914     albertel 1100: # -------------------------------- ask if server already has a session for user
                   1101: sub has_user_session {
                   1102:     my ($lonid,$udom,$uname) = @_;
                   1103:     my $result = &reply(join(':','userhassession',
                   1104: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1105:     return 1 if ($result eq 'ok');
                   1106: 
                   1107:     return 0;
                   1108: }
                   1109: 
1.1076    raeburn  1110: # --------- determine least loaded server in a user's domain which allows login
                   1111: 
                   1112: sub choose_server {
1.1259    raeburn  1113:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1114:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1115:     my %servers = &get_servers($udom);
1.1076    raeburn  1116:     my $lowest_load = 30000;
1.1259    raeburn  1117:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1118:     if ($skiploadbal) {
                   1119:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1120:         unless (defined($cached)) {
                   1121:             my $cachetime = 60*60*24;
                   1122:             my %domconfig =
                   1123:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1124:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1125:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1126:                                            $cachetime);
                   1127:             }
                   1128:         }
                   1129:     }
1.1076    raeburn  1130:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1131:         if ($skiploadbal) {
                   1132:             if (ref($balancers) eq 'HASH') {
                   1133:                 next if (exists($balancers->{$lonhost}));
                   1134:             }
1.1389  ! raeburn  1135:         }
1.1115    raeburn  1136:         my $loginvia;
                   1137:         if ($checkloginvia) {
                   1138:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1139:             if ($loginvia) {
                   1140:                 my ($server,$path) = split(/:/,$loginvia);
                   1141:                 ($login_host, $lowest_load) =
1.1253    raeburn  1142:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1143:                 if ($login_host eq $server) {
                   1144:                     $portal_path = $path;
1.1151    raeburn  1145:                     $isredirect = 1;
1.1116    raeburn  1146:                 }
                   1147:             } else {
                   1148:                 ($login_host, $lowest_load) =
1.1253    raeburn  1149:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1150:                 if ($login_host eq $lonhost) {
                   1151:                     $portal_path = '';
1.1151    raeburn  1152:                     $isredirect = ''; 
1.1116    raeburn  1153:                 }
                   1154:             }
                   1155:         } else {
1.1076    raeburn  1156:             ($login_host, $lowest_load) =
1.1253    raeburn  1157:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1158:         }
                   1159:     }
                   1160:     if ($login_host ne '') {
1.1116    raeburn  1161:         $hostname = &hostname($login_host);
1.1076    raeburn  1162:     }
1.1331    raeburn  1163:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1164: }
                   1165: 
1.202     matthew  1166: # --------------------------------------------- Try to change a user's password
                   1167: 
                   1168: sub changepass {
1.799     raeburn  1169:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1170:     $currentpass = &escape($currentpass);
                   1171:     $newpass     = &escape($newpass);
1.1030    raeburn  1172:     my $lonhost = $perlvar{'lonHostID'};
                   1173:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1174: 		       $server);
                   1175:     if (! $answer) {
                   1176: 	&logthis("No reply on password change request to $server ".
                   1177: 		 "by $uname in domain $udom.");
                   1178:     } elsif ($answer =~ "^ok") {
                   1179:         &logthis("$uname in $udom successfully changed their password ".
                   1180: 		 "on $server.");
                   1181:     } elsif ($answer =~ "^pwchange_failure") {
                   1182: 	&logthis("$uname in $udom was unable to change their password ".
                   1183: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1184: 		 "or pwchange");
                   1185:     } elsif ($answer =~ "^non_authorized") {
                   1186:         &logthis("$uname in $udom did not get their password correct when ".
                   1187: 		 "attempting to change it on $server.");
                   1188:     } elsif ($answer =~ "^auth_mode_error") {
                   1189:         &logthis("$uname in $udom attempted to change their password despite ".
                   1190: 		 "not being locally or internally authenticated on $server.");
                   1191:     } elsif ($answer =~ "^unknown_user") {
                   1192:         &logthis("$uname in $udom attempted to change their password ".
                   1193: 		 "on $server but were unable to because $server is not ".
                   1194: 		 "their home server.");
                   1195:     } elsif ($answer =~ "^refused") {
                   1196: 	&logthis("$server refused to change $uname in $udom password because ".
                   1197: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1198:     } elsif ($answer =~ "invalid_client") {
                   1199:         &logthis("$server refused to change $uname in $udom password because ".
                   1200:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1201:     }
                   1202:     return $answer;
1.1       albertel 1203: }
                   1204: 
1.169     harris41 1205: # ----------------------- Try to determine user's current authentication scheme
                   1206: 
                   1207: sub queryauthenticate {
                   1208:     my ($uname,$udom)=@_;
1.456     albertel 1209:     my $uhome=&homeserver($uname,$udom);
                   1210:     if (!$uhome) {
                   1211: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1212: 	return 'no_host';
                   1213:     }
                   1214:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1215:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1216: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1217:     }
1.456     albertel 1218:     return $answer;
1.169     harris41 1219: }
                   1220: 
1.1       albertel 1221: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1222: 
1.1       albertel 1223: sub authenticate {
1.1073    raeburn  1224:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1225:     $upass=&escape($upass);
                   1226:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1227:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1228:     my $newhome;
1.836     www      1229:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1230: # Maybe the machine was offline and only re-appeared again recently?
                   1231:         &reconlonc();
                   1232: # One more
1.952     raeburn  1233: 	$uhome=&homeserver($uname,$udom,1);
                   1234:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1235:             if (defined(&domain($udom,'primary'))) {
                   1236:                 $newhome=&domain($udom,'primary');
                   1237:             }
                   1238:             if ($newhome ne '') {
                   1239:                 $uhome = $newhome;
                   1240:             }
                   1241:         }
1.836     www      1242: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1243: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1244: 	    return 'no_host';
                   1245:         }
1.1       albertel 1246:     }
1.1073    raeburn  1247:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1248:     if ($answer eq 'authorized') {
1.952     raeburn  1249:         if ($newhome) {
                   1250:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1251:             return 'no_account_on_host'; 
                   1252:         } else {
                   1253:             &logthis("User $uname at $udom authorized by $uhome");
                   1254:             return $uhome;
                   1255:         }
1.471     albertel 1256:     }
                   1257:     if ($answer eq 'non_authorized') {
                   1258: 	&logthis("User $uname at $udom rejected by $uhome");
                   1259: 	return 'no_host'; 
1.9       www      1260:     }
1.471     albertel 1261:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1262:     return 'no_host';
                   1263: }
                   1264: 
1.1073    raeburn  1265: sub can_host_session {
1.1074    raeburn  1266:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1267:     my $canhost = 1;
1.1074    raeburn  1268:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1269:     if (ref($remotesessions) eq 'HASH') {
                   1270:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1271:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1272:                 $canhost = 0;
                   1273:             } else {
                   1274:                 $canhost = 1;
                   1275:             }
                   1276:         }
                   1277:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1278:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1279:                 $canhost = 1;
                   1280:             } else {
                   1281:                 $canhost = 0;
                   1282:             }
                   1283:         }
                   1284:         if ($canhost) {
                   1285:             if ($remotesessions->{'version'} ne '') {
                   1286:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1287:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1288:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1289:                         my $major = $1;
                   1290:                         my $minor = $2;
                   1291:                         if (($major < $reqmajor ) ||
                   1292:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1293:                             $canhost = 0;
                   1294:                         }
                   1295:                     } else {
                   1296:                         $canhost = 0;
                   1297:                     }
                   1298:                 }
                   1299:             }
                   1300:         }
                   1301:     }
                   1302:     if ($canhost) {
                   1303:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1304:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1305:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1306:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1307:                 if (($uint_dom ne '') && 
                   1308:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1309:                     $canhost = 0;
                   1310:                 } else {
                   1311:                     $canhost = 1;
                   1312:                 }
                   1313:             }
                   1314:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1315:                 if (($uint_dom ne '') && 
                   1316:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1317:                     $canhost = 1;
                   1318:                 } else {
                   1319:                     $canhost = 0;
                   1320:                 }
                   1321:             }
                   1322:         }
                   1323:     }
                   1324:     return $canhost;
                   1325: }
                   1326: 
1.1083    raeburn  1327: sub spare_can_host {
                   1328:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1329:     my $canhost=1;
1.1279    raeburn  1330:     my $try_server_hostname = &hostname($try_server);
                   1331:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1332:     my $serverhomedom = &host_domain($serverhomeID);
                   1333:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1334:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1335:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1336:             $canhost = 0;
                   1337:         }
                   1338:     }
                   1339:     if (($canhost) && ($uint_dom)) {
                   1340:         my @intdoms;
                   1341:         my $internet_names = &get_internet_names($try_server);
                   1342:         if (ref($internet_names) eq 'ARRAY') {
                   1343:             @intdoms = @{$internet_names};
                   1344:         }
                   1345:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1346:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1347:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1348:                                          $remotesessions,
                   1349:                                          $defdomdefaults{'hostedsessions'});
                   1350:         }
1.1083    raeburn  1351:     }
                   1352:     return $canhost;
                   1353: }
                   1354: 
1.1123    raeburn  1355: sub this_host_spares {
                   1356:     my ($dom) = @_;
1.1126    raeburn  1357:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1358:     my @hosts = &current_machine_ids();
                   1359:     foreach my $lonhost (@hosts) {
                   1360:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1361:             $dom_in_use = $dom;
                   1362:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1363:             last;
                   1364:         }
                   1365:     }
1.1126    raeburn  1366:     if ($dom_in_use ne '') {
                   1367:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1368:     }
                   1369:     if (ref($result) ne 'HASH') {
                   1370:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1371:         $dom_in_use = &host_domain($lonhost_in_use);
                   1372:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1373:         if (ref($result) ne 'HASH') {
                   1374:             $result = \%spareid;
                   1375:         }
                   1376:     }
                   1377:     return $result;
                   1378: }
                   1379: 
                   1380: sub spares_for_offload  {
                   1381:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1382:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1383:     if (defined($cached)) {
                   1384:         return $result;
                   1385:     } else {
1.1126    raeburn  1386:         my $cachetime = 60*60*24;
                   1387:         my %domconfig =
                   1388:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1389:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1390:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1391:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1392:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1393:                 }
                   1394:             }
                   1395:         }
                   1396:     }
1.1126    raeburn  1397:     return;
1.1123    raeburn  1398: }
                   1399: 
1.1129    raeburn  1400: sub get_lonbalancer_config {
                   1401:     my ($servers) = @_;
                   1402:     my ($currbalancer,$currtargets);
                   1403:     if (ref($servers) eq 'HASH') {
                   1404:         foreach my $server (keys(%{$servers})) {
                   1405:             my %what = (
                   1406:                          spareid => 1,
                   1407:                          perlvar => 1,
                   1408:                        );
                   1409:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1410:             if ($result eq 'ok') {
                   1411:                 if (ref($returnhash) eq 'HASH') {
                   1412:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1413:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1414:                             $currbalancer = $server;
                   1415:                             $currtargets = {};
                   1416:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1417:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1418:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1419:                                 }
                   1420:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1421:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1422:                                 }
                   1423:                             }
                   1424:                             last;
                   1425:                         }
                   1426:                     }
                   1427:                 }
                   1428:             }
                   1429:         }
                   1430:     }
                   1431:     return ($currbalancer,$currtargets);
                   1432: }
                   1433: 
                   1434: sub check_loadbalancing {
1.1331    raeburn  1435:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1436:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1389  ! raeburn  1437:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1438:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1439:     my @hosts = &current_machine_ids();
1.1129    raeburn  1440:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1441:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1442:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1443:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1444:     my $domneedscache;
1.1129    raeburn  1445:     my $cachetime = 60*60*24;
                   1446: 
                   1447:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1448:         $dom_in_use = $udom;
                   1449:         $homeintdom = 1;
                   1450:     } else {
                   1451:         $dom_in_use = $serverhomedom;
                   1452:     }
                   1453:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1454:     unless (defined($cached)) {
                   1455:         my %domconfig =
                   1456:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1457:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1458:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1459:         } else {
                   1460:             $domneedscache = $dom_in_use;
1.1129    raeburn  1461:         }
                   1462:     }
                   1463:     if (ref($result) eq 'HASH') {
1.1389  ! raeburn  1464:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1191    raeburn  1465:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1466:         if ($is_balancer) {
                   1467:             if (ref($currrules) eq 'HASH') {
                   1468:                 if ($homeintdom) {
                   1469:                     if ($uname ne '') {
                   1470:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1471:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1472:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1473:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1474:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1475:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1476:                             }
                   1477:                         }
                   1478:                         if ($rule_in_effect eq '') {
                   1479:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1480:                             if ($userenv{'inststatus'} ne '') {
                   1481:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1482:                                 my ($othertitle,$usertypes,$types) =
                   1483:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1484:                                 if (ref($types) eq 'ARRAY') {
                   1485:                                     foreach my $type (@{$types}) {
                   1486:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1487:                                             if (exists($currrules->{$type})) {
                   1488:                                                 $rule_in_effect = $currrules->{$type};
                   1489:                                             }
                   1490:                                         }
                   1491:                                     }
                   1492:                                 }
                   1493:                             } else {
                   1494:                                 if (exists($currrules->{'default'})) {
                   1495:                                     $rule_in_effect = $currrules->{'default'};
                   1496:                                 }
                   1497:                             }
                   1498:                         }
                   1499:                     } else {
                   1500:                         if (exists($currrules->{'default'})) {
                   1501:                             $rule_in_effect = $currrules->{'default'};
                   1502:                         }
                   1503:                     }
                   1504:                 } else {
                   1505:                     if ($currrules->{'_LC_external'} ne '') {
                   1506:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1507:                     }
                   1508:                 }
                   1509:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1510:                                                        $uname,$udom);
                   1511:             }
                   1512:         }
                   1513:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1514:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1515:         unless (defined($cached)) {
                   1516:             my %domconfig =
                   1517:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1518:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1519:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1520:             } else {
                   1521:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1522:             }
                   1523:         }
                   1524:         if (ref($result) eq 'HASH') {
1.1389  ! raeburn  1525:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1191    raeburn  1526:                 &check_balancer_result($result,@hosts);
                   1527:             if ($is_balancer) {
1.1129    raeburn  1528:                 if (ref($currrules) eq 'HASH') {
                   1529:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1530:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1531:                     }
                   1532:                 }
                   1533:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1534:                                                        $uname,$udom);
                   1535:             }
                   1536:         } else {
                   1537:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1538:                 $is_balancer = 1;
                   1539:                 $offloadto = &this_host_spares($dom_in_use);
                   1540:             }
1.1307    raeburn  1541:             unless (defined($cached)) {
                   1542:                 $domneedscache = $serverhomedom;
                   1543:             }
1.1129    raeburn  1544:         }
                   1545:     } else {
                   1546:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1547:             $is_balancer = 1;
                   1548:             $offloadto = &this_host_spares($dom_in_use);
                   1549:         }
1.1307    raeburn  1550:         unless (defined($cached)) {
                   1551:             $domneedscache = $serverhomedom;
                   1552:         }
                   1553:     }
                   1554:     if ($domneedscache) {
                   1555:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1556:     }
1.1176    raeburn  1557:     if ($is_balancer) {
                   1558:         my $lowest_load = 30000;
                   1559:         if (ref($offloadto) eq 'HASH') {
                   1560:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1561:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1562:                     ($otherserver,$lowest_load) =
                   1563:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1564:                 }
1.1129    raeburn  1565:             }
1.1176    raeburn  1566:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1567: 
1.1176    raeburn  1568:             if (!$found_server) {
                   1569:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1570:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1571:                         ($otherserver,$lowest_load) =
                   1572:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1573:                     }
                   1574:                 }
                   1575:             }
                   1576:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1577:             if (@{$offloadto} == 1) {
                   1578:                 $otherserver = $offloadto->[0];
                   1579:             } elsif (@{$offloadto} > 1) {
                   1580:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1581:                     ($otherserver,$lowest_load) =
                   1582:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1583:                 }
                   1584:             }
                   1585:         }
1.1331    raeburn  1586:         unless ($caller eq 'login') {
                   1587:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1588:                 $is_balancer = 0;
                   1589:                 if ($uname ne '' && $udom ne '') {
                   1590:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389  ! raeburn  1591:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1592:                                  'user.loadbalcheck.time' => time});
                   1593:                     }
1.1176    raeburn  1594:                 }
1.1129    raeburn  1595:             }
                   1596:         }
1.1389  ! raeburn  1597:         unless ($homeintdom) {
        !          1598:             undef($setcookie);
        !          1599:         }
1.1129    raeburn  1600:     }
1.1389  ! raeburn  1601:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1602: }
                   1603: 
1.1191    raeburn  1604: sub check_balancer_result {
                   1605:     my ($result,@hosts) = @_;
1.1389  ! raeburn  1606:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1191    raeburn  1607:     if (ref($result) eq 'HASH') {
                   1608:         if ($result->{'lonhost'} ne '') {
                   1609:             my $currbalancer = $result->{'lonhost'};
                   1610:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1611:                 $is_balancer = 1;
                   1612:                 $currtargets = $result->{'targets'};
                   1613:                 $currrules = $result->{'rules'};
                   1614:             }
                   1615:         } else {
                   1616:             foreach my $key (keys(%{$result})) {
                   1617:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1618:                     (ref($result->{$key}) eq 'HASH')) {
                   1619:                     $is_balancer = 1;
                   1620:                     $currrules = $result->{$key}{'rules'};
                   1621:                     $currtargets = $result->{$key}{'targets'};
1.1389  ! raeburn  1622:                     $setcookie = $result->{$key}{'cookie'};
1.1191    raeburn  1623:                     last;
                   1624:                 }
                   1625:             }
                   1626:         }
                   1627:     }
1.1389  ! raeburn  1628:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1191    raeburn  1629: }
                   1630: 
1.1129    raeburn  1631: sub get_loadbalancer_targets {
                   1632:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1633:     my $offloadto;
1.1175    raeburn  1634:     if ($rule_in_effect eq 'none') {
                   1635:         return [$perlvar{'lonHostID'}];
                   1636:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1637:         $offloadto = $currtargets;
                   1638:     } else {
                   1639:         if ($rule_in_effect eq 'homeserver') {
                   1640:             my $homeserver = &homeserver($uname,$udom);
                   1641:             if ($homeserver ne 'no_host') {
                   1642:                 $offloadto = [$homeserver];
                   1643:             }
                   1644:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1645:             my %domconfig =
                   1646:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1647:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1648:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1649:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1650:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1651:                     }
                   1652:                 }
                   1653:             } else {
1.1178    raeburn  1654:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1655:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1656:                 if (&hostname($remotebalancer) ne '') {
                   1657:                     $offloadto = [$remotebalancer];
                   1658:                 }
                   1659:             }
                   1660:         } elsif (&hostname($rule_in_effect) ne '') {
                   1661:             $offloadto = [$rule_in_effect];
                   1662:         }
                   1663:     }
                   1664:     return $offloadto;
                   1665: }
                   1666: 
1.1127    raeburn  1667: sub internet_dom_servers {
                   1668:     my ($dom) = @_;
                   1669:     my (%uniqservers,%servers);
                   1670:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1671:     my @machinedoms = &machine_domains($primaryserver);
                   1672:     foreach my $mdom (@machinedoms) {
                   1673:         my %currservers = %servers;
                   1674:         my %server = &get_servers($mdom);
                   1675:         %servers = (%currservers,%server);
                   1676:     }
                   1677:     my %by_hostname;
                   1678:     foreach my $id (keys(%servers)) {
                   1679:         push(@{$by_hostname{$servers{$id}}},$id);
                   1680:     }
                   1681:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1682:         if (@{$by_hostname{$hostname}} > 1) {
                   1683:             my $match = 0;
                   1684:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1685:                 if (&host_domain($id) eq $dom) {
                   1686:                     $uniqservers{$id} = $hostname;
                   1687:                     $match = 1;
                   1688:                 }
                   1689:             }
                   1690:             unless ($match) {
                   1691:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1692:             }
                   1693:         } else {
                   1694:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1695:         }
                   1696:     }
                   1697:     return %uniqservers;
                   1698: }
                   1699: 
1.1347    raeburn  1700: sub trusted_domains {
                   1701:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1702:     my ($trusted,$untrusted);
1.1347    raeburn  1703:     if (&domain($calldom) eq '') {
1.1349    raeburn  1704:         return ($trusted,$untrusted);
1.1347    raeburn  1705:     }
                   1706:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1707:         return ($trusted,$untrusted);
1.1347    raeburn  1708:     }
                   1709:     my $callprimary = &domain($calldom,'primary');
                   1710:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1711:     if ($intcalldom eq '') {
1.1349    raeburn  1712:         return ($trusted,$untrusted);
1.1347    raeburn  1713:     }
                   1714: 
                   1715:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1716:     unless (defined($cached)) {
                   1717:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1718:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1719:         $trustconfig = $domconfig{'trust'};
                   1720:     }
                   1721:     if (ref($trustconfig)) {
                   1722:         my (%possexc,%possinc,@allexc,@allinc); 
                   1723:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1724:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1725:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1726:             }
                   1727:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1728:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1729:             }
                   1730:         }
                   1731:         if (keys(%possexc)) {
                   1732:             if (keys(%possinc)) {
                   1733:                 foreach my $key (sort(keys(%possexc))) {
                   1734:                     next if ($key eq $intcalldom);
                   1735:                     unless ($possinc{$key}) {
                   1736:                         push(@allexc,$key);
                   1737:                     }
                   1738:                 }
                   1739:             } else {
                   1740:                 @allexc = sort(keys(%possexc));
                   1741:             }
                   1742:         }
                   1743:         if (keys(%possinc)) {
                   1744:             $possinc{$intcalldom} = 1;
                   1745:             @allinc = sort(keys(%possinc));
                   1746:         }
                   1747:         if ((@allexc > 0) || (@allinc > 0)) {
                   1748:             my %doms_by_intdom;
                   1749:             my %allintdoms = &all_host_intdom();
                   1750:             my %alldoms = &all_host_domain();
                   1751:             foreach my $key (%allintdoms) {
                   1752:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1753:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1754:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1755:                     }
                   1756:                 } else {
                   1757:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1758:                 }
                   1759:             }
                   1760:             foreach my $exc (@allexc) {
                   1761:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349    raeburn  1762:                     $untrusted = $doms_by_intdom{$exc};
1.1347    raeburn  1763:                 }
                   1764:             }
                   1765:             foreach my $inc (@allinc) {
                   1766:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349    raeburn  1767:                     $trusted = $doms_by_intdom{$inc};
1.1347    raeburn  1768:                 }
                   1769:             }
                   1770:         }
                   1771:     }
1.1349    raeburn  1772:     return ($trusted,$untrusted);
1.1347    raeburn  1773: }
                   1774: 
                   1775: sub will_trust {
                   1776:     my ($cmdtype,$domain,$possdom) = @_;
                   1777:     return 1 if ($domain eq $possdom);
                   1778:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1779:     my $willtrust; 
                   1780:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1781:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1782:             $willtrust = 1;
                   1783:         }
                   1784:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1785:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1786:             $willtrust = 1;
                   1787:         }
                   1788:     } else {
                   1789:         $willtrust = 1;
                   1790:     }
                   1791:     return $willtrust;
                   1792: }
                   1793: 
1.1       albertel 1794: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1795: 
1.599     albertel 1796: my %homecache;
1.1       albertel 1797: sub homeserver {
1.230     stredwic 1798:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1799:     my $index="$uname:$udom";
1.426     albertel 1800: 
1.599     albertel 1801:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1802: 
                   1803:     my %servers = &get_servers($udom,'library');
                   1804:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1805:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1806: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1807: 
                   1808: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1809: 	if ($answer eq 'found') {
                   1810: 	    delete($badServerCache{$tryserver}); 
                   1811: 	    return $homecache{$index}=$tryserver;
                   1812: 	} elsif ($answer eq 'no_host') {
                   1813: 	    $badServerCache{$tryserver}=1;
                   1814: 	}
1.1       albertel 1815:     }    
                   1816:     return 'no_host';
1.70      www      1817: }
                   1818: 
1.1300    raeburn  1819: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1820: 
                   1821: sub idget {
1.1300    raeburn  1822:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1823:     my %returnhash=();
1.1300    raeburn  1824:     my @ids=(); 
                   1825:     if (ref($idsref) eq 'ARRAY') {
                   1826:         @ids = @{$idsref};
                   1827:     } else {
                   1828:         return %returnhash; 
                   1829:     }
                   1830:     if ($namespace eq '') {
                   1831:         $namespace = 'ids';
                   1832:     }
1.70      www      1833:     
1.841     albertel 1834:     my %servers = &get_servers($udom,'library');
                   1835:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1836: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1837: 	if ($namespace eq 'ids') {
                   1838: 	    $idlist=~tr/A-Z/a-z/;
                   1839: 	}
                   1840: 	my $reply;
                   1841: 	if ($namespace eq 'ids') {
                   1842: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1843: 	} else {
                   1844: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1845: 	}
1.841     albertel 1846: 	my @answer=();
                   1847: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1848: 	    @answer=split(/\&/,$reply);
                   1849: 	}                    ;
                   1850: 	my $i;
                   1851: 	for ($i=0;$i<=$#ids;$i++) {
                   1852: 	    if ($answer[$i]) {
1.1299    raeburn  1853: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1854: 	    }
1.841     albertel 1855: 	}
1.1300    raeburn  1856:     }
1.70      www      1857:     return %returnhash;
                   1858: }
                   1859: 
                   1860: # ------------------------------------- Find the IDs behind a list of usernames
                   1861: 
                   1862: sub idrget {
                   1863:     my ($udom,@unames)=@_;
                   1864:     my %returnhash=();
1.800     albertel 1865:     foreach my $uname (@unames) {
                   1866:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1867:     }
1.70      www      1868:     return %returnhash;
                   1869: }
                   1870: 
1.1300    raeburn  1871: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1872: 
                   1873: sub idput {
1.1300    raeburn  1874:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1875:     my %servers=();
1.1300    raeburn  1876:     my %ids=();
                   1877:     my %byid = ();
                   1878:     if (ref($idsref) eq 'HASH') {
                   1879:         %ids=%{$idsref};
                   1880:     }
                   1881:     if ($namespace eq '') {
                   1882:         $namespace = 'ids'; 
                   1883:     }
1.800     albertel 1884:     foreach my $uname (keys(%ids)) {
                   1885: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1886:         if ($uhom eq '') {
                   1887:             $uhom=&homeserver($uname,$udom);
                   1888:         }
1.70      www      1889:         if ($uhom ne 'no_host') {
1.800     albertel 1890:             my $esc_unam=&escape($uname);
1.1300    raeburn  1891:             if ($namespace eq 'ids') {
                   1892:                 my $id=&escape($ids{$uname});
                   1893:                 $id=~tr/A-Z/a-z/;
                   1894:                 my $esc_unam=&escape($uname);
                   1895:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1896:             } else {
1.1300    raeburn  1897:                 my @currids = split(/,/,$ids{$uname});
                   1898:                 foreach my $id (@currids) {
                   1899:                     $byid{$uhom}{$id} .= $uname.',';
                   1900:                 }
                   1901:             }
                   1902:         }
                   1903:     }
                   1904:     if ($namespace eq 'clickers') {
                   1905:         foreach my $server (keys(%byid)) {
                   1906:             if (ref($byid{$server}) eq 'HASH') {
                   1907:                 foreach my $id (keys(%{$byid{$server}})) {
                   1908:                     $byid{$server} =~ s/,$//;
                   1909:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1910:                 }
1.70      www      1911:             }
                   1912:         }
1.191     harris41 1913:     }
1.800     albertel 1914:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1915:         $servers{$server} =~ s/\&$//;
                   1916:         if ($namespace eq 'ids') {     
                   1917:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1918:         } else {
                   1919:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1920:         }
1.191     harris41 1921:     }
1.344     www      1922: }
                   1923: 
1.1300    raeburn  1924: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1925: 
                   1926: sub iddel {
1.1300    raeburn  1927:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1928:     my %result=();
1.1300    raeburn  1929:     my %ids=();
                   1930:     my %byid = ();
                   1931:     if (ref($idshashref) eq 'HASH') {
                   1932:         %ids=%{$idshashref};
                   1933:     } else {
1.1231    raeburn  1934:         return %result;
                   1935:     }
1.1300    raeburn  1936:     if ($namespace eq '') {
                   1937:         $namespace = 'ids';
                   1938:     }
1.1231    raeburn  1939:     my %servers=();
1.1300    raeburn  1940:     while (my ($id,$unamestr) = each(%ids)) {
                   1941:         if ($namespace eq 'ids') {
                   1942:             my $uhom = $uhome;
                   1943:             if ($uhom eq '') { 
                   1944:                 $uhom=&homeserver($unamestr,$udom);
                   1945:             }
                   1946:             if ($uhom ne 'no_host') {
                   1947:                 $servers{$uhom}.='&'.&escape($id);
                   1948:             }
                   1949:          } else {
                   1950:             my @curritems = split(/,/,$ids{$id});
                   1951:             foreach my $uname (@curritems) {
                   1952:                 my $uhom = $uhome;
                   1953:                 if ($uhom eq '') {
                   1954:                     $uhom=&homeserver($uname,$udom);
                   1955:                 }
                   1956:                 if ($uhom ne 'no_host') { 
                   1957:                     $byid{$uhom}{$id} .= $uname.',';
                   1958:                 }
                   1959:             }
1.1231    raeburn  1960:         }
1.1300    raeburn  1961:     }
                   1962:     if ($namespace eq 'clickers') {
                   1963:         foreach my $server (keys(%byid)) {
                   1964:             if (ref($byid{$server}) eq 'HASH') {
                   1965:                 foreach my $id (keys(%{$byid{$server}})) {
                   1966:                     $byid{$server}{$id} =~ s/,$//;
                   1967:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1968:                 }
1.1231    raeburn  1969:             }
                   1970:         }
                   1971:     }
                   1972:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1973:         $servers{$server} =~ s/\&$//;
                   1974:         if ($namespace eq 'ids') {
                   1975:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1976:         } elsif ($namespace eq 'clickers') {
                   1977:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1978:         }
1.1231    raeburn  1979:     }
                   1980:     return %result;
                   1981: }
                   1982: 
1.1300    raeburn  1983: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1984: 
                   1985: sub updateclickers {
                   1986:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1987:     my %clickers;
                   1988:     if (ref($idshashref) eq 'HASH') {
                   1989:         %clickers=%{$idshashref};
                   1990:     } else {
                   1991:         return;
                   1992:     }
                   1993:     my $items='';
                   1994:     foreach my $item (keys(%clickers)) {
                   1995:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1996:     }
                   1997:     $items=~s/\&$//;
                   1998:     my $request = "updateclickers:$udom:$action:$items";
                   1999:     if ($critical) {
                   2000:         return &critical($request,$uhome);
                   2001:     } else {
                   2002:         return &reply($request,$uhome);
                   2003:     }
                   2004: }
                   2005: 
1.1023    raeburn  2006: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2007: sub dump_dom {
1.1165    droeschl 2008:     my ($namespace, $udom, $regexp) = @_;
                   2009: 
                   2010:     $udom ||= $env{'user.domain'};
                   2011: 
                   2012:     return () unless $udom;
                   2013: 
                   2014:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2015: }
                   2016: 
1.1023    raeburn  2017: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2018: 
                   2019: sub get_dom {
1.860     raeburn  2020:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2021:     return if ($udom eq 'public');
1.806     raeburn  2022:     my $items='';
                   2023:     foreach my $item (@$storearr) {
                   2024:         $items.=&escape($item).'&';
                   2025:     }
                   2026:     $items=~s/\&$//;
1.860     raeburn  2027:     if (!$udom) {
                   2028:         $udom=$env{'user.domain'};
1.1267    raeburn  2029:         return if ($udom eq 'public');
1.860     raeburn  2030:         if (defined(&domain($udom,'primary'))) {
                   2031:             $uhome=&domain($udom,'primary');
                   2032:         } else {
1.874     albertel 2033:             undef($uhome);
1.860     raeburn  2034:         }
                   2035:     } else {
                   2036:         if (!$uhome) {
                   2037:             if (defined(&domain($udom,'primary'))) {
                   2038:                 $uhome=&domain($udom,'primary');
                   2039:             }
                   2040:         }
                   2041:     }
                   2042:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2043:         my $rep;
                   2044:         if ($namespace =~ /^enc/) {
                   2045:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2046:         } else {
                   2047:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2048:         }
1.866     raeburn  2049:         my %returnhash;
1.875     albertel 2050:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2051:             return %returnhash;
                   2052:         }
1.806     raeburn  2053:         my @pairs=split(/\&/,$rep);
                   2054:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2055:             return @pairs;
                   2056:         }
                   2057:         my $i=0;
                   2058:         foreach my $item (@$storearr) {
                   2059:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2060:             $i++;
                   2061:         }
                   2062:         return %returnhash;
                   2063:     } else {
1.880     banghart 2064:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2065:     }
                   2066: }
                   2067: 
                   2068: # -------------------------------------------- put items in domain db files 
                   2069: 
                   2070: sub put_dom {
1.860     raeburn  2071:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2072:     if (!$udom) {
                   2073:         $udom=$env{'user.domain'};
                   2074:         if (defined(&domain($udom,'primary'))) {
                   2075:             $uhome=&domain($udom,'primary');
                   2076:         } else {
1.874     albertel 2077:             undef($uhome);
1.860     raeburn  2078:         }
                   2079:     } else {
                   2080:         if (!$uhome) {
                   2081:             if (defined(&domain($udom,'primary'))) {
                   2082:                 $uhome=&domain($udom,'primary');
                   2083:             }
                   2084:         }
                   2085:     } 
                   2086:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2087:         my $items='';
                   2088:         foreach my $item (keys(%$storehash)) {
                   2089:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2090:         }
                   2091:         $items=~s/\&$//;
1.1344    raeburn  2092:         if ($namespace =~ /^enc/) {
                   2093:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2094:         } else {
                   2095:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2096:         }
1.806     raeburn  2097:     } else {
1.860     raeburn  2098:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2099:     }
                   2100: }
                   2101: 
1.1023    raeburn  2102: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2103: sub newput_dom {
1.1023    raeburn  2104:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2105:     my $result;
                   2106:     if (!$udom) {
                   2107:         $udom=$env{'user.domain'};
                   2108:     }
1.1023    raeburn  2109:     if ($udom) {
                   2110:         my $uname = &get_domainconfiguser($udom);
                   2111:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2112:     }
                   2113:     return $result;
                   2114: }
                   2115: 
1.1023    raeburn  2116: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2117: sub del_dom {
1.1023    raeburn  2118:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2119:     if (ref($storearr) eq 'ARRAY') {
                   2120:         if (!$udom) {
                   2121:             $udom=$env{'user.domain'};
                   2122:         }
1.1023    raeburn  2123:         if ($udom) {
                   2124:             my $uname = &get_domainconfiguser($udom); 
                   2125:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2126:         }
                   2127:     }
                   2128: }
                   2129: 
1.1023    raeburn  2130: # ----------------------------------construct domainconfig user for a domain 
                   2131: sub get_domainconfiguser {
                   2132:     my ($udom) = @_;
                   2133:     return $udom.'-domainconfig';
                   2134: }
                   2135: 
1.837     raeburn  2136: sub retrieve_inst_usertypes {
                   2137:     my ($udom) = @_;
                   2138:     my (%returnhash,@order);
1.989     raeburn  2139:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2140:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2141:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2142:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2143:     } else {
                   2144:         if (defined(&domain($udom,'primary'))) {
                   2145:             my $uhome=&domain($udom,'primary');
                   2146:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2147:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2148:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2149:                 return (\%returnhash,\@order);
                   2150:             }
                   2151:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2152:             my @pairs=split(/\&/,$hashitems);
                   2153:             foreach my $item (@pairs) {
                   2154:                 my ($key,$value)=split(/=/,$item,2);
                   2155:                 $key = &unescape($key);
                   2156:                 next if ($key =~ /^error: 2 /);
                   2157:                 $returnhash{$key}=&thaw_unescape($value);
                   2158:             }
                   2159:             my @esc_order = split(/\&/,$orderitems);
                   2160:             foreach my $item (@esc_order) {
                   2161:                 push(@order,&unescape($item));
                   2162:             }
                   2163:         } else {
1.1256    raeburn  2164:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2165:         }
1.1256    raeburn  2166:         return (\%returnhash,\@order);
1.837     raeburn  2167:     }
                   2168: }
                   2169: 
1.868     raeburn  2170: sub is_domainimage {
                   2171:     my ($url) = @_;
1.1306    raeburn  2172:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2173:         if (&domain($1) ne '') {
                   2174:             return '1';
                   2175:         }
                   2176:     }
                   2177:     return;
                   2178: }
                   2179: 
1.899     raeburn  2180: sub inst_directory_query {
                   2181:     my ($srch) = @_;
                   2182:     my $udom = $srch->{'srchdomain'};
                   2183:     my %results;
                   2184:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2185:     my $outcome;
1.899     raeburn  2186:     if ($homeserver ne '') {
1.1357    raeburn  2187:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2188:             if ($srch->{'srchby'} eq 'email') {
                   2189:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2190:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2191:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2192:                     (($major == 2) && ($minor < 12))) {
                   2193:                     return;
                   2194:                 }
                   2195:             }
                   2196:         }
1.904     albertel 2197: 	my $queryid=&reply("querysend:instdirsearch:".
                   2198: 			   &escape($srch->{'srchby'}).':'.
                   2199: 			   &escape($srch->{'srchterm'}).':'.
                   2200: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2201: 	my $host=&hostname($homeserver);
                   2202: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2203: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2204: 	    return;
                   2205: 	}
                   2206: 	my $response = &get_query_reply($queryid);
                   2207: 	my $maxtries = 5;
                   2208: 	my $tries = 1;
                   2209: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2210: 	    $response = &get_query_reply($queryid);
                   2211: 	    $tries ++;
                   2212: 	}
                   2213: 
                   2214:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2215:             if ($response eq 'unavailable') {
                   2216:                 $outcome = $response;
                   2217:             } else {
                   2218:                 $outcome = 'ok';
                   2219:                 my @matches = split(/\n/,$response);
                   2220:                 foreach my $match (@matches) {
                   2221:                     my ($key,$value) = split(/=/,$match);
                   2222:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2223:                 }
1.899     raeburn  2224:             }
                   2225:         }
                   2226:     }
1.909     raeburn  2227:     return ($outcome,%results);
1.899     raeburn  2228: }
                   2229: 
                   2230: sub usersearch {
                   2231:     my ($srch) = @_;
                   2232:     my $dom = $srch->{'srchdomain'};
                   2233:     my %results;
                   2234:     my %libserv = &all_library();
                   2235:     my $query = 'usersearch';
                   2236:     foreach my $tryserver (keys(%libserv)) {
                   2237:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2238:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2239:                 if ($srch->{'srchby'} eq 'email') {
                   2240:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2241:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2242:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2243:                              (($major == 2) && ($minor < 12)));
                   2244:                 }
                   2245:             }
1.899     raeburn  2246:             my $host=&hostname($tryserver);
                   2247:             my $queryid=
1.911     raeburn  2248:                 &reply("querysend:".&escape($query).':'.
                   2249:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2250:                        &escape($srch->{'srchtype'}).':'.
                   2251:                        &escape($srch->{'srchterm'}),$tryserver);
                   2252:             if ($queryid !~/^\Q$host\E\_/) {
                   2253:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2254:                 next;
1.899     raeburn  2255:             }
                   2256:             my $reply = &get_query_reply($queryid);
                   2257:             my $maxtries = 1;
                   2258:             my $tries = 1;
                   2259:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2260:                 $reply = &get_query_reply($queryid);
                   2261:                 $tries ++;
                   2262:             }
                   2263:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2264:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2265:             } else {
1.911     raeburn  2266:                 my @matches;
                   2267:                 if ($reply =~ /\n/) {
                   2268:                     @matches = split(/\n/,$reply);
                   2269:                 } else {
                   2270:                     @matches = split(/\&/,$reply);
                   2271:                 }
1.899     raeburn  2272:                 foreach my $match (@matches) {
                   2273:                     my ($uname,$udom,%userhash);
1.911     raeburn  2274:                     foreach my $entry (split(/:/,$match)) {
                   2275:                         my ($key,$value) =
                   2276:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2277:                         $userhash{$key} = $value;
                   2278:                         if ($key eq 'username') {
                   2279:                             $uname = $value;
                   2280:                         } elsif ($key eq 'domain') {
                   2281:                             $udom = $value;
1.911     raeburn  2282:                         }
1.899     raeburn  2283:                     }
                   2284:                     $results{$uname.':'.$udom} = \%userhash;
                   2285:                 }
                   2286:             }
                   2287:         }
                   2288:     }
                   2289:     return %results;
                   2290: }
                   2291: 
1.912     raeburn  2292: sub get_instuser {
                   2293:     my ($udom,$uname,$id) = @_;
                   2294:     my $homeserver = &domain($udom,'primary');
                   2295:     my ($outcome,%results);
                   2296:     if ($homeserver ne '') {
                   2297:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2298:                            &escape($id).':'.&escape($udom),$homeserver);
                   2299:         my $host=&hostname($homeserver);
                   2300:         if ($queryid !~/^\Q$host\E\_/) {
                   2301:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2302:             return;
                   2303:         }
                   2304:         my $response = &get_query_reply($queryid);
                   2305:         my $maxtries = 5;
                   2306:         my $tries = 1;
                   2307:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2308:             $response = &get_query_reply($queryid);
                   2309:             $tries ++;
                   2310:         }
                   2311:         if (!&error($response) && $response ne 'refused') {
                   2312:             if ($response eq 'unavailable') {
                   2313:                 $outcome = $response;
                   2314:             } else {
                   2315:                 $outcome = 'ok';
                   2316:                 my @matches = split(/\n/,$response);
                   2317:                 foreach my $match (@matches) {
                   2318:                     my ($key,$value) = split(/=/,$match);
                   2319:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2320:                 }
                   2321:             }
                   2322:         }
                   2323:     }
                   2324:     my %userinfo;
                   2325:     if (ref($results{$uname}) eq 'HASH') {
                   2326:         %userinfo = %{$results{$uname}};
                   2327:     } 
                   2328:     return ($outcome,%userinfo);
                   2329: }
                   2330: 
1.1290    raeburn  2331: sub get_multiple_instusers {
                   2332:     my ($udom,$users,$caller) = @_;
                   2333:     my ($outcome,$results);
                   2334:     if (ref($users) eq 'HASH') {
                   2335:         my $count = keys(%{$users}); 
                   2336:         my $requested = &freeze_escape($users);
                   2337:         my $homeserver = &domain($udom,'primary');
                   2338:         if ($homeserver ne '') {
                   2339:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2340:             my $host=&hostname($homeserver);
                   2341:             if ($queryid !~/^\Q$host\E\_/) {
                   2342:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2343:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2344:                 return ($outcome,$results);
                   2345:             }
                   2346:             my $response = &get_query_reply($queryid);
                   2347:             my $maxtries = 5;
                   2348:             if ($count > 100) {
                   2349:                 $maxtries = 1+int($count/20);
                   2350:             }
                   2351:             my $tries = 1;
                   2352:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2353:                 $response = &get_query_reply($queryid);
                   2354:                 $tries ++;
                   2355:             }
                   2356:             if ($response eq '') {
                   2357:                 $results = {};
                   2358:                 foreach my $key (keys(%{$users})) {
                   2359:                     my ($uname,$id);
                   2360:                     if ($caller eq 'id') {
                   2361:                         $id = $key;
                   2362:                     } else {
                   2363:                         $uname = $key;
                   2364:                     }
                   2365:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2366:                     $outcome = $resp;
1.1290    raeburn  2367:                     if ($resp eq 'ok') {
                   2368:                         %{$results} = (%{$results}, %info);
                   2369:                     } else {
                   2370:                         last;
                   2371:                     }
                   2372:                 }
                   2373:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2374:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2375:                     $outcome = $response;
                   2376:                 } else {
1.1291    raeburn  2377:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2378:                     if ($outcome eq 'ok') {
                   2379:                         $results = &thaw_unescape($userdata); 
                   2380:                     }
                   2381:                 }
                   2382:             }
                   2383:         }
                   2384:     }
                   2385:     return ($outcome,$results);
                   2386: }
                   2387: 
1.912     raeburn  2388: sub inst_rulecheck {
1.923     raeburn  2389:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2390:     my %returnhash;
                   2391:     if ($udom ne '') {
                   2392:         if (ref($rules) eq 'ARRAY') {
                   2393:             @{$rules} = map {&escape($_);} (@{$rules});
                   2394:             my $rulestr = join(':',@{$rules});
                   2395:             my $homeserver=&domain($udom,'primary');
                   2396:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2397:                 my $response;
                   2398:                 if ($item eq 'username') {                
                   2399:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2400:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2401:                                               $homeserver));
1.923     raeburn  2402:                 } elsif ($item eq 'id') {
                   2403:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2404:                                               ':'.&escape($id).':'.$rulestr,
                   2405:                                               $homeserver));
1.945     raeburn  2406:                 } elsif ($item eq 'selfcreate') {
                   2407:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2408:                                                &escape($udom).':'.&escape($uname).
                   2409:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2410:                 }
1.912     raeburn  2411:                 if ($response ne 'refused') {
                   2412:                     my @pairs=split(/\&/,$response);
                   2413:                     foreach my $item (@pairs) {
                   2414:                         my ($key,$value)=split(/=/,$item,2);
                   2415:                         $key = &unescape($key);
                   2416:                         next if ($key =~ /^error: 2 /);
                   2417:                         $returnhash{$key}=&thaw_unescape($value);
                   2418:                     }
                   2419:                 }
                   2420:             }
                   2421:         }
                   2422:     }
                   2423:     return %returnhash;
                   2424: }
                   2425: 
                   2426: sub inst_userrules {
1.923     raeburn  2427:     my ($udom,$check) = @_;
1.912     raeburn  2428:     my (%ruleshash,@ruleorder);
                   2429:     if ($udom ne '') {
                   2430:         my $homeserver=&domain($udom,'primary');
                   2431:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2432:             my $response;
                   2433:             if ($check eq 'id') {
                   2434:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2435:                                  $homeserver);
1.943     raeburn  2436:             } elsif ($check eq 'email') {
                   2437:                 $response=&reply('instemailrules:'.&escape($udom),
                   2438:                                  $homeserver);
1.923     raeburn  2439:             } else {
                   2440:                 $response=&reply('instuserrules:'.&escape($udom),
                   2441:                                  $homeserver);
                   2442:             }
1.912     raeburn  2443:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2444:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2445:                 ($response ne 'no_such_host')) {
                   2446:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2447:                 my @pairs=split(/\&/,$hashitems);
                   2448:                 foreach my $item (@pairs) {
                   2449:                     my ($key,$value)=split(/=/,$item,2);
                   2450:                     $key = &unescape($key);
                   2451:                     next if ($key =~ /^error: 2 /);
                   2452:                     $ruleshash{$key}=&thaw_unescape($value);
                   2453:                 }
                   2454:                 my @esc_order = split(/\&/,$orderitems);
                   2455:                 foreach my $item (@esc_order) {
                   2456:                     push(@ruleorder,&unescape($item));
                   2457:                 }
                   2458:             }
                   2459:         }
                   2460:     }
                   2461:     return (\%ruleshash,\@ruleorder);
                   2462: }
                   2463: 
1.976     raeburn  2464: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2465: 
                   2466: sub get_domain_defaults {
1.1240    raeburn  2467:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2468:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2469:     my $cachetime = 60*60*24;
1.1240    raeburn  2470:     unless ($ignore_cache) {
                   2471:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2472:         if (defined($cached)) {
                   2473:             if (ref($result) eq 'HASH') {
                   2474:                 return %{$result};
                   2475:             }
1.943     raeburn  2476:         }
                   2477:     }
                   2478:     my %domdefaults;
                   2479:     my %domconfig =
1.989     raeburn  2480:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2481:                                   'requestcourses','inststatus',
1.1183    raeburn  2482:                                   'coursedefaults','usersessions',
1.1258    raeburn  2483:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2484:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2485:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2486:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2487:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2488:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2489:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2490:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2491:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2492:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2493:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2494:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2495:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2496:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2497:     } else {
                   2498:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2499:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2500:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2501:     }
1.976     raeburn  2502:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2503:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2504:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2505:         } else {
                   2506:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2507:         }
1.1177    raeburn  2508:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2509:         foreach my $item (@usertools) {
                   2510:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2511:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2512:             }
                   2513:         }
1.1229    raeburn  2514:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2515:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2516:         }
1.976     raeburn  2517:     }
1.985     raeburn  2518:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2519:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2520:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2521:         }
                   2522:     }
1.1183    raeburn  2523:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2524:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2525:     }
1.989     raeburn  2526:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2527:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2528:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2529:         }
                   2530:     }
1.1047    raeburn  2531:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2532:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2533:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2534:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2535:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2536:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2537:         }
1.1254    raeburn  2538:         foreach my $type (@coursetypes) {
                   2539:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2540:                 unless ($type eq 'community') {
                   2541:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2542:                 }
                   2543:             }
                   2544:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2545:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2546:             }
1.1277    raeburn  2547:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2548:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2549:                     $domdefaults{$type.'postsubtimeout'} = 
                   2550:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2551:                 }
                   2552:             }
1.1230    raeburn  2553:         }
1.1286    raeburn  2554:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2555:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2556:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2557:                 if (@clonecodes) {
                   2558:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2559:                 }
                   2560:             }
                   2561:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2562:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2563:         }
1.1356    raeburn  2564:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2565:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2566:         } 
1.1047    raeburn  2567:     }
1.1073    raeburn  2568:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2569:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2570:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2571:         }
                   2572:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2573:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2574:         }
1.1279    raeburn  2575:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2576:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2577:         }
1.1073    raeburn  2578:     }
1.1254    raeburn  2579:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2580:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2581:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2582:                             'approval','limit');
                   2583:             foreach my $type (@coursetypes) {
                   2584:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2585:                     my @mgrdc = ();
                   2586:                     foreach my $item (@settings) {
                   2587:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2588:                             push(@mgrdc,$item);
                   2589:                         }
                   2590:                     }
                   2591:                     if (@mgrdc) {
                   2592:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2593:                     }
                   2594:                 }
                   2595:             }
                   2596:         }
                   2597:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2598:             foreach my $type (@coursetypes) {
                   2599:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2600:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2601:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2602:                     }
                   2603:                 }
                   2604:             }
                   2605:         }
                   2606:     }
1.1258    raeburn  2607:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2608:         $domdefaults{'catauth'} = 'std';
                   2609:         $domdefaults{'catunauth'} = 'std';
                   2610:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2611:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2612:         }
                   2613:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2614:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2615:         }
                   2616:     }
1.1315    raeburn  2617:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2618:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2619:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2620:         }
1.1338    raeburn  2621:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2622:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2623:         }
                   2624:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2625:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2626:         }
                   2627:     }
1.1320    raeburn  2628:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2629:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2630:         foreach my $prefix (@prefixes) {
                   2631:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2632:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2633:             }
                   2634:         }
                   2635:     }
1.1314    raeburn  2636:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2637:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2638:     }
1.1332    raeburn  2639:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2640:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2641:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2642:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2643:         }
                   2644:     }
1.1219    raeburn  2645:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2646:     return %domdefaults;
                   2647: }
                   2648: 
1.1311    raeburn  2649: sub course_portal_url {
                   2650:     my ($cnum,$cdom) = @_;
                   2651:     my $chome = &homeserver($cnum,$cdom);
                   2652:     my $hostname = &hostname($chome);
                   2653:     my $protocol = $protocol{$chome};
                   2654:     $protocol = 'http' if ($protocol ne 'https');
                   2655:     my %domdefaults = &get_domain_defaults($cdom);
                   2656:     my $firsturl;
                   2657:     if ($domdefaults{'portal_def'}) {
                   2658:         $firsturl = $domdefaults{'portal_def'};
                   2659:     } else {
                   2660:         $firsturl = $protocol.'://'.$hostname;
                   2661:     }
                   2662:     return $firsturl;
                   2663: }
                   2664: 
1.344     www      2665: # --------------------------------------------------- Assign a key to a student
                   2666: 
                   2667: sub assign_access_key {
1.364     www      2668: #
                   2669: # a valid key looks like uname:udom#comments
                   2670: # comments are being appended
                   2671: #
1.498     www      2672:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2673:     $kdom=
1.620     albertel 2674:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2675:     $knum=
1.620     albertel 2676:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2677:     $cdom=
1.620     albertel 2678:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2679:     $cnum=
1.620     albertel 2680:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2681:     $udom=$env{'user.name'} unless (defined($udom));
                   2682:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2683:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2684:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2685:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2686:                                                   # assigned to this person
                   2687:                                                   # - this should not happen,
1.345     www      2688:                                                   # unless something went wrong
                   2689:                                                   # the first time around
                   2690: # ready to assign
1.364     www      2691:         $logentry=$1.'; '.$logentry;
1.496     www      2692:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2693:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2694: # key now belongs to user
1.346     www      2695: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2696:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2697:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2698:                 return 'ok';
                   2699:             } else {
                   2700:                 return 
                   2701:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2702: 	    }
                   2703:         } else {
                   2704:             return 'error: Could not assign key, try again later.';
                   2705:         }
1.364     www      2706:     } elsif (!$existing{$ckey}) {
1.345     www      2707: # the key does not exist
                   2708: 	return 'error: The key does not exist';
                   2709:     } else {
                   2710: # the key is somebody else's
                   2711: 	return 'error: The key is already in use';
                   2712:     }
1.344     www      2713: }
                   2714: 
1.364     www      2715: # ------------------------------------------ put an additional comment on a key
                   2716: 
                   2717: sub comment_access_key {
                   2718: #
                   2719: # a valid key looks like uname:udom#comments
                   2720: # comments are being appended
                   2721: #
                   2722:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2723:     $cdom=
1.620     albertel 2724:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2725:     $cnum=
1.620     albertel 2726:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2727:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2728:     if ($existing{$ckey}) {
                   2729:         $existing{$ckey}.='; '.$logentry;
                   2730: # ready to assign
1.367     www      2731:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2732:                                                  $cdom,$cnum) eq 'ok') {
                   2733: 	    return 'ok';
                   2734:         } else {
                   2735: 	    return 'error: Count not store comment.';
                   2736:         }
                   2737:     } else {
                   2738: # the key does not exist
                   2739: 	return 'error: The key does not exist';
                   2740:     }
                   2741: }
                   2742: 
1.344     www      2743: # ------------------------------------------------------ Generate a set of keys
                   2744: 
                   2745: sub generate_access_keys {
1.364     www      2746:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2747:     $cdom=
1.620     albertel 2748:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2749:     $cnum=
1.620     albertel 2750:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2751:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2752:     unless (($cdom) && ($cnum)) { return 0; }
                   2753:     if ($number>10000) { return 0; }
                   2754:     sleep(2); # make sure don't get same seed twice
                   2755:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2756:     my $total=0;
                   2757:     for (my $i=1;$i<=$number;$i++) {
                   2758:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2759:                   sprintf("%lx",int(100000*rand)).'-'.
                   2760:                   sprintf("%lx",int(100000*rand));
                   2761:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2762:        $newkey=~s/0/h/g; # and also 0 and O
                   2763:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2764:        if ($existing{$newkey}) {
                   2765:            $i--;
                   2766:        } else {
1.364     www      2767: 	  if (&put('accesskeys',
                   2768:               { $newkey => '# generated '.localtime().
1.620     albertel 2769:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2770:                            '; '.$logentry },
                   2771: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2772:               $total++;
                   2773: 	  }
                   2774:        }
                   2775:     }
1.620     albertel 2776:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2777:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2778:     return $total;
                   2779: }
                   2780: 
                   2781: # ------------------------------------------------------- Validate an accesskey
                   2782: 
                   2783: sub validate_access_key {
                   2784:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2785:     $cdom=
1.620     albertel 2786:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2787:     $cnum=
1.620     albertel 2788:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2789:     $udom=$env{'user.domain'} unless (defined($udom));
                   2790:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2791:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2792:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2793: }
                   2794: 
                   2795: # ------------------------------------- Find the section of student in a course
1.652     albertel 2796: sub devalidate_getsection_cache {
                   2797:     my ($udom,$unam,$courseid)=@_;
                   2798:     my $hashid="$udom:$unam:$courseid";
                   2799:     &devalidate_cache_new('getsection',$hashid);
                   2800: }
1.298     matthew  2801: 
1.815     albertel 2802: sub courseid_to_courseurl {
                   2803:     my ($courseid) = @_;
                   2804:     #already url style courseid
                   2805:     return $courseid if ($courseid =~ m{^/});
                   2806: 
                   2807:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2808: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2809: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2810: 	return "/$cdom/$cnum";
                   2811:     }
                   2812: 
                   2813:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2814:     if (exists($courseinfo{'num'})) {
                   2815: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2816:     }
                   2817: 
                   2818:     return undef;
                   2819: }
                   2820: 
1.298     matthew  2821: sub getsection {
                   2822:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2823:     my $cachetime=1800;
1.551     albertel 2824: 
                   2825:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2826:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2827:     if (defined($cached)) { return $result; }
                   2828: 
1.298     matthew  2829:     my %Pending; 
                   2830:     my %Expired;
                   2831:     #
                   2832:     # Each role can either have not started yet (pending), be active, 
                   2833:     #    or have expired.
                   2834:     #
                   2835:     # If there is an active role, we are done.
                   2836:     #
                   2837:     # If there is more than one role which has not started yet, 
                   2838:     #     choose the one which will start sooner
                   2839:     # If there is one role which has not started yet, return it.
                   2840:     #
                   2841:     # If there is more than one expired role, choose the one which ended last.
                   2842:     # If there is a role which has expired, return it.
                   2843:     #
1.815     albertel 2844:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2845:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2846:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2847:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2848:         my $section=$1;
                   2849:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2850:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2851:         my $now=time;
1.548     albertel 2852:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2853:             $Expired{$end}=$section;
                   2854:             next;
                   2855:         }
1.548     albertel 2856:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2857:             $Pending{$start}=$section;
                   2858:             next;
                   2859:         }
1.599     albertel 2860:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2861:     }
                   2862:     #
                   2863:     # Presumedly there will be few matching roles from the above
                   2864:     # loop and the sorting time will be negligible.
                   2865:     if (scalar(keys(%Pending))) {
                   2866:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2867:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2868:     } 
                   2869:     if (scalar(keys(%Expired))) {
                   2870:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2871:         my $time = pop(@sorted);
1.599     albertel 2872:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2873:     }
1.599     albertel 2874:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2875: }
1.70      www      2876: 
1.599     albertel 2877: sub save_cache {
                   2878:     &purge_remembered();
1.722     albertel 2879:     #&Apache::loncommon::validate_page();
1.620     albertel 2880:     undef(%env);
1.780     albertel 2881:     undef($env_loaded);
1.599     albertel 2882: }
1.452     albertel 2883: 
1.599     albertel 2884: my $to_remember=-1;
                   2885: my %remembered;
                   2886: my %accessed;
                   2887: my $kicks=0;
                   2888: my $hits=0;
1.849     albertel 2889: sub make_key {
                   2890:     my ($name,$id) = @_;
1.872     albertel 2891:     if (length($id) > 65 
                   2892: 	&& length(&escape($id)) > 200) {
                   2893: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2894:     }
1.849     albertel 2895:     return &escape($name.':'.$id);
                   2896: }
                   2897: 
1.599     albertel 2898: sub devalidate_cache_new {
                   2899:     my ($name,$id,$debug) = @_;
                   2900:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2901:     my $remembered_id=$name.':'.$id;
1.849     albertel 2902:     $id=&make_key($name,$id);
1.599     albertel 2903:     $memcache->delete($id);
1.1319    damieng  2904:     delete($remembered{$remembered_id});
                   2905:     delete($accessed{$remembered_id});
1.599     albertel 2906: }
                   2907: 
                   2908: sub is_cached_new {
                   2909:     my ($name,$id,$debug) = @_;
1.1319    damieng  2910:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2911:     if (exists($remembered{$remembered_id})) {
                   2912: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2913: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2914: 	$hits++;
1.1319    damieng  2915: 	return ($remembered{$remembered_id},1);
1.599     albertel 2916:     }
1.1319    damieng  2917:     $id=&make_key($name,$id);
1.599     albertel 2918:     my $value = $memcache->get($id);
                   2919:     if (!(defined($value))) {
                   2920: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2921: 	return (undef,undef);
1.416     albertel 2922:     }
1.599     albertel 2923:     if ($value eq '__undef__') {
                   2924: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2925: 	$value=undef;
                   2926:     }
1.1319    damieng  2927:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2928:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2929:     return ($value,1);
                   2930: }
                   2931: 
                   2932: sub do_cache_new {
                   2933:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2934:     my $remembered_id=$name.':'.$id;
1.849     albertel 2935:     $id=&make_key($name,$id);
1.599     albertel 2936:     my $setvalue=$value;
                   2937:     if (!defined($setvalue)) {
                   2938: 	$setvalue='__undef__';
                   2939:     }
1.623     albertel 2940:     if (!defined($time) ) {
                   2941: 	$time=600;
                   2942:     }
1.599     albertel 2943:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2944:     my $result = $memcache->set($id,$setvalue,$time);
                   2945:     if (! $result) {
1.872     albertel 2946: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2947: 	$memcache->disconnect_all();
1.872     albertel 2948:     }
1.600     albertel 2949:     # need to make a copy of $value
1.1319    damieng  2950:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2951:     return $value;
                   2952: }
                   2953: 
                   2954: sub make_room {
1.1319    damieng  2955:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2956: 
1.1319    damieng  2957:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2958:                                     : $value;
1.599     albertel 2959:     if ($to_remember<0) { return; }
1.1319    damieng  2960:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2961:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2962:     my $to_kick;
                   2963:     my $max_time=0;
                   2964:     foreach my $other (keys(%accessed)) {
                   2965: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2966: 	    $to_kick=$other;
                   2967: 	    $max_time=&tv_interval($accessed{$other});
                   2968: 	}
                   2969:     }
                   2970:     delete($remembered{$to_kick});
                   2971:     delete($accessed{$to_kick});
                   2972:     $kicks++;
                   2973:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2974:     return;
                   2975: }
                   2976: 
1.599     albertel 2977: sub purge_remembered {
1.604     albertel 2978:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2979:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2980:     undef(%remembered);
                   2981:     undef(%accessed);
1.428     albertel 2982: }
1.70      www      2983: # ------------------------------------- Read an entry from a user's environment
                   2984: 
                   2985: sub userenvironment {
                   2986:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2987:     my $items;
                   2988:     foreach my $item (@what) {
                   2989:         $items.=&escape($item).'&';
                   2990:     }
                   2991:     $items=~s/\&$//;
1.70      www      2992:     my %returnhash=();
1.1009    raeburn  2993:     my $uhome = &homeserver($unam,$udom);
                   2994:     unless ($uhome eq 'no_host') {
                   2995:         my @answer=split(/\&/, 
                   2996:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2997:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2998:             return %returnhash;
                   2999:         }
1.1009    raeburn  3000:         my $i;
                   3001:         for ($i=0;$i<=$#what;$i++) {
                   3002: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3003:         }
1.70      www      3004:     }
                   3005:     return %returnhash;
1.1       albertel 3006: }
                   3007: 
1.617     albertel 3008: # ---------------------------------------------------------- Get a studentphoto
                   3009: sub studentphoto {
                   3010:     my ($udom,$unam,$ext) = @_;
                   3011:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3012:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3013:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3014:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3015:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3016:             } else {
                   3017:                 my ($result,$perm_reqd)=
1.707     albertel 3018: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3019:                 if ($result eq 'ok') {
                   3020:                     if (!($perm_reqd eq 'yes')) {
                   3021:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3022:                     }
                   3023:                 }
                   3024:             }
                   3025:         }
                   3026:     } else {
                   3027:         my ($result,$perm_reqd) = 
1.707     albertel 3028: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3029:         if ($result eq 'ok') {
                   3030:             if (!($perm_reqd eq 'yes')) {
                   3031:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3032:             }
                   3033:         }
                   3034:     }
                   3035:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3036: }
                   3037: 
                   3038: sub retrievestudentphoto {
                   3039:     my ($udom,$unam,$ext,$type) = @_;
                   3040:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3041:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3042:     if ($ret eq 'ok') {
                   3043:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3044:         if ($type eq 'thumbnail') {
                   3045:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3046:         }
                   3047:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3048:         return $tokenurl;
                   3049:     } else {
                   3050:         if ($type eq 'thumbnail') {
                   3051:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3052:         } else { 
                   3053:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3054:         }
1.617     albertel 3055:     }
                   3056: }
                   3057: 
1.263     www      3058: # -------------------------------------------------------------------- New chat
                   3059: 
                   3060: sub chatsend {
1.724     raeburn  3061:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3062:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3063:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3064:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3065:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3066: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3067: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3068: }
                   3069: 
                   3070: # ------------------------------------------ Find current version of a resource
                   3071: 
                   3072: sub getversion {
                   3073:     my $fname=&clutter(shift);
1.1189    raeburn  3074:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3075:     return &currentversion(&filelocation('',$fname));
                   3076: }
                   3077: 
                   3078: sub currentversion {
                   3079:     my $fname=shift;
                   3080:     my $author=$fname;
                   3081:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3082:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3083:     my $home=&homeserver($uname,$udom);
1.292     www      3084:     if ($home eq 'no_host') { 
                   3085:         return -1; 
                   3086:     }
1.1112    www      3087:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3088:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3089: 	return -1;
                   3090:     }
1.1112    www      3091:     return $answer;
1.263     www      3092: }
                   3093: 
1.1111    www      3094: #
                   3095: # Return special version number of resource if set by override, empty otherwise
                   3096: #
                   3097: sub usedversion {
                   3098:     my $fname=shift;
                   3099:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3100:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3101:     if ($urlversion) { return $urlversion; }
                   3102:     return '';
                   3103: }
                   3104: 
1.1       albertel 3105: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3106: 
1.1       albertel 3107: sub subscribe {
                   3108:     my $fname=shift;
1.761     raeburn  3109:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3110:     $fname=~s/[\n\r]//g;
1.1       albertel 3111:     my $author=$fname;
                   3112:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3113:     my ($udom,$uname)=split(/\//,$author);
                   3114:     my $home=homeserver($uname,$udom);
1.335     albertel 3115:     if ($home eq 'no_host') {
                   3116:         return 'not_found';
1.1       albertel 3117:     }
                   3118:     my $answer=reply("sub:$fname",$home);
1.64      www      3119:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3120: 	$answer.=' by '.$home;
                   3121:     }
1.1       albertel 3122:     return $answer;
                   3123: }
                   3124:     
1.8       www      3125: # -------------------------------------------------------------- Replicate file
                   3126: 
                   3127: sub repcopy {
                   3128:     my $filename=shift;
1.23      www      3129:     $filename=~s/\/+/\//g;
1.1142    raeburn  3130:     my $londocroot = $perlvar{'lonDocRoot'};
                   3131:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3132:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3133:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3134: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3135: 	return &repcopy_userfile($filename);
                   3136:     }
1.532     albertel 3137:     $filename=~s/[\n\r]//g;
1.8       www      3138:     my $transname="$filename.in.transfer";
1.828     www      3139: # FIXME: this should flock
1.607     raeburn  3140:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3141:     my $remoteurl=subscribe($filename);
1.64      www      3142:     if ($remoteurl =~ /^con_lost by/) {
                   3143: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3144:            return 'unavailable';
1.8       www      3145:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3146: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3147: 	   return 'not_found';
1.64      www      3148:     } elsif ($remoteurl =~ /^rejected by/) {
                   3149: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3150:            return 'forbidden';
1.20      www      3151:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3152:            return 'ok';
1.8       www      3153:     } else {
1.290     www      3154:         my $author=$filename;
                   3155:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3156:         my ($udom,$uname)=split(/\//,$author);
                   3157:         my $home=homeserver($uname,$udom);
                   3158:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3159:            my @parts=split(/\//,$filename);
                   3160:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3161:            if ($path ne "$londocroot/res") {
1.8       www      3162:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3163: 	       return 'bad_request';
1.8       www      3164:            }
                   3165:            my $count;
                   3166:            for ($count=5;$count<$#parts;$count++) {
                   3167:                $path.="/$parts[$count]";
                   3168:                if ((-e $path)!=1) {
                   3169: 		   mkdir($path,0777);
                   3170:                }
                   3171:            }
                   3172:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3173:            my $response;
                   3174:            if ($remoteurl =~ m{/raw/}) {
                   3175:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3176:            } else {
                   3177:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3178:            }
1.8       www      3179:            if ($response->is_error()) {
                   3180: 	       unlink($transname);
                   3181:                my $message=$response->status_line;
1.672     albertel 3182:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3183:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3184:                return 'unavailable';
1.8       www      3185:            } else {
1.16      www      3186: 	       if ($remoteurl!~/\.meta$/) {
                   3187:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3188:                   my $mresponse;
                   3189:                   if ($remoteurl =~ m{/raw/}) {
                   3190:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3191:                   } else {
                   3192:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3193:                   }
1.16      www      3194:                   if ($mresponse->is_error()) {
                   3195: 		      unlink($filename.'.meta');
                   3196:                       &logthis(
1.672     albertel 3197:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3198:                   }
                   3199: 	       }
1.8       www      3200:                rename($transname,$filename);
1.607     raeburn  3201:                return 'ok';
1.8       www      3202:            }
1.290     www      3203:        }
1.8       www      3204:     }
1.330     www      3205: }
                   3206: 
                   3207: # ------------------------------------------------ Get server side include body
                   3208: sub ssi_body {
1.381     albertel 3209:     my ($filelink,%form)=@_;
1.606     matthew  3210:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3211:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3212:     }
1.953     www      3213:     my $output='';
                   3214:     my $response;
1.980     raeburn  3215:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3216:        ($output,$response)=&externalssi($filelink);
1.953     www      3217:     } else {
1.1004    droeschl 3218:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3219:        $filelink .= 'inhibitmenu=yes';
1.953     www      3220:        ($output,$response)=&ssi($filelink,%form);
                   3221:     }
1.778     albertel 3222:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3223:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3224:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3225:     if (wantarray) {
                   3226:         return ($output, $response);
                   3227:     } else {
                   3228:         return $output;
                   3229:     }
1.8       www      3230: }
                   3231: 
1.15      www      3232: # --------------------------------------------------------- Server Side Include
                   3233: 
1.782     albertel 3234: sub absolute_url {
                   3235:     my ($host_name) = @_;
                   3236:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3237:     if ($host_name eq '') {
                   3238: 	$host_name = $ENV{'SERVER_NAME'};
                   3239:     }
                   3240:     return $protocol.$host_name;
                   3241: }
                   3242: 
1.942     foxr     3243: #
                   3244: #   Server side include.
                   3245: # Parameters:
                   3246: #  fn     Possibly encrypted resource name/id.
                   3247: #  form   Hash that describes how the rendering should be done
                   3248: #         and other things.
1.944     foxr     3249: # Returns:
1.950     raeburn  3250: #   Scalar context: The content of the response.
                   3251: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3252: #     
1.15      www      3253: sub ssi {
                   3254: 
1.944     foxr     3255:     my ($fn,%form)=@_;
1.23      www      3256:     my $request;
1.711     albertel 3257: 
                   3258:     $form{'no_update_last_known'}=1;
1.895     albertel 3259:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3260:     if (%form) {
1.782     albertel 3261:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3262:       $request->content(join('&',map { 
                   3263:             my $name = escape($_);
                   3264:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3265:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3266:             : &escape($form{$_}) );    
                   3267:         } keys(%form)));
1.23      www      3268:     } else {
1.782     albertel 3269:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3270:     }
                   3271: 
1.15      www      3272:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3273:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3274:     my $islocal;
                   3275:     if (($env{'request.course.id'}) &&
                   3276:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3277:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3278:         ($form{'grade_symb'} ne '') &&
                   3279:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3280:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3281:         $islocal = 1;
                   3282:     }
1.1384    raeburn  3283:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3284:                                                 '','','',$islocal);
1.1182    foxr     3285: 
1.944     foxr     3286:     if (wantarray) {
1.1345    raeburn  3287: 	return ($response->content, $response);
1.944     foxr     3288:     } else {
1.1345    raeburn  3289: 	return $response->content;
1.942     foxr     3290:     }
1.324     www      3291: }
                   3292: 
                   3293: sub externalssi {
                   3294:     my ($url)=@_;
                   3295:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3296:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3297:     if (wantarray) {
                   3298:         return ($response->content, $response);
                   3299:     } else {
                   3300:         return $response->content;
                   3301:     }
1.15      www      3302: }
1.254     www      3303: 
1.1354    raeburn  3304: 
                   3305: # If the local copy of a replicated resource is outdated, trigger a  
                   3306: # connection from the homeserver to flush the delayed queue. If no update 
                   3307: # happens, remove local copies of outdated resource (and corresponding
                   3308: # metadata file).
                   3309: 
1.1352    raeburn  3310: sub remove_stale_resfile {
                   3311:     my ($url) = @_;
1.1354    raeburn  3312:     my $removed;
1.1352    raeburn  3313:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3314:         my $audom = $1;
                   3315:         my $auname = $2;
1.1353    raeburn  3316:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3317:             my $homeserver = &homeserver($auname,$audom);
                   3318:             unless (($homeserver eq 'no_host') ||
                   3319:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3320:                 my $fname = &filelocation('',$url);
                   3321:                 if (-e $fname) {
                   3322:                     my $protocol = $protocol{$homeserver};
                   3323:                     $protocol = 'http' if ($protocol ne 'https');
                   3324:                     my $hostname = &hostname($homeserver);
                   3325:                     if ($hostname) {
                   3326:                         my $uri = &declutter($url);
                   3327:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3328:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3329:                         if ($response->is_success()) {
                   3330:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3331:                             my $locmodtime = (stat($fname))[9];
                   3332:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3333:                                 my $stale;
                   3334:                                 my $answer = &reply('pong',$homeserver);
                   3335:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3336:                                     sleep(0.2);
                   3337:                                     $locmodtime = (stat($fname))[9];
                   3338:                                     if ($locmodtime < $remmodtime) {
                   3339:                                         my $posstransfer = $fname.'.in.transfer';
                   3340:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3341:                                             $removed = 1;
                   3342:                                         } else {
                   3343:                                             $stale = 1;
                   3344:                                         }
                   3345:                                     } else {
                   3346:                                         $removed = 1;
                   3347:                                     }
                   3348:                                 } else {
                   3349:                                     $stale = 1;
                   3350:                                 }
                   3351:                                 if ($stale) {
                   3352:                                     unlink($fname);
                   3353:                                     if ($uri!~/\.meta$/) {
                   3354:                                         unlink($fname.'.meta');
                   3355:                                     }
                   3356:                                     &reply("unsub:$fname",$homeserver);
                   3357:                                     $removed = 1;
1.1352    raeburn  3358:                                 }
                   3359:                             }
                   3360:                         }
                   3361:                     }
                   3362:                 }
                   3363:             }
                   3364:         }
                   3365:     }
1.1354    raeburn  3366:     return $removed;
1.1352    raeburn  3367: }
                   3368: 
1.492     albertel 3369: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3370: 
                   3371: sub allowuploaded {
                   3372:     my ($srcurl,$url)=@_;
                   3373:     $url=&clutter(&declutter($url));
                   3374:     my $dir=$url;
                   3375:     $dir=~s/\/[^\/]+$//;
                   3376:     my %httpref=();
                   3377:     my $httpurl=&hreflocation('',$url);
                   3378:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3379:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3380: }
1.477     raeburn  3381: 
1.1193    raeburn  3382: #
                   3383: # Determine if the current user should be able to edit a particular resource,
                   3384: # when viewing in course context.
                   3385: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3386: #     Functions.
                   3387: # (b) When displaying folder contents in course editor, used to determine if
                   3388: #     "Edit" link will be displayed alongside resource.
                   3389: #
1.1196    raeburn  3390: #  input: six args -- filename (decluttered), course number, course domain,
                   3391: #                   url, symb (if registered) and group (if this is a group
                   3392: #                   item -- e.g., bulletin board, group page etc.).
                   3393: #  output: array of five scalars -- 
1.1193    raeburn  3394: #          $cfile -- url for file editing if editable on current server
                   3395: #          $home -- homeserver of resource (i.e., for author if published,
                   3396: #                                           or course if uploaded.).
                   3397: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3398: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3399: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3400: #
                   3401: 
                   3402: sub can_edit_resource {
1.1194    raeburn  3403:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3404:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3405: #
                   3406: # For aboutme pages user can only edit his/her own.
                   3407: #
1.1199    raeburn  3408:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3409:         my ($sdom,$sname) = ($1,$2);
                   3410:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3411:             $home = $env{'user.home'};
                   3412:             $cfile = $resurl;
                   3413:             if ($env{'form.forceedit'}) {
                   3414:                 $forceview = 1;
                   3415:             } else {
                   3416:                 $forceedit = 1;
                   3417:             }
                   3418:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3419:         } else {
                   3420:             return;
                   3421:         }
                   3422:     }
                   3423: 
                   3424:     if ($env{'request.course.id'}) {
                   3425:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3426:         if ($group ne '') {
                   3427: # if this is a group homepage or group bulletin board, check group privs
                   3428:             my $allowed = 0;
1.1197    raeburn  3429:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3430:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3431:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3432:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3433:                     $allowed = 1;
                   3434:                 }
1.1197    raeburn  3435:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3436:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3437:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3438:                     $allowed = 1;
                   3439:                 }
                   3440:             }
                   3441:             if ($allowed) {
                   3442:                 $home=&homeserver($cnum,$cdom);
                   3443:                 if ($env{'form.forceedit'}) {
                   3444:                     $forceview = 1;
                   3445:                 } else {
                   3446:                     $forceedit = 1;
                   3447:                 }
                   3448:                 $cfile = $resurl;
                   3449:             } else {
                   3450:                 return;
                   3451:             }
                   3452:         } else {
1.1208    raeburn  3453:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3454:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3455:                     return;
                   3456:                 }
                   3457:             } elsif (!$crsedit) {
1.1194    raeburn  3458: #
                   3459: # No edit allowed where CC has switched to student role.
                   3460: #
                   3461:                 return;
                   3462:             }
                   3463:         }
                   3464:     }
                   3465: 
1.1193    raeburn  3466:     if ($file ne '') {
                   3467:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3468:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3469:                 $uploaded = 1;
                   3470:                 $incourse = 1;
1.1193    raeburn  3471:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3472:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3473:                     if ($env{'form.forceedit'}) {
                   3474:                         $forceview = 1;
                   3475:                     } else {
                   3476:                         $forceedit = 1;
                   3477:                     }
1.1194    raeburn  3478:                 }
                   3479:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3480:                 $incourse = 1;
                   3481:                 if ($env{'form.forceedit'}) {
                   3482:                     $forceview = 1;
                   3483:                 } else {
                   3484:                     $forceedit = 1;
                   3485:                 }
                   3486:                 $cfile = $resurl;
                   3487:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3488:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3489:                     $incourse = 1;
                   3490:                     if ($env{'form.forceedit'}) {
                   3491:                         $forceview = 1;
                   3492:                     } else {
                   3493:                         $forceedit = 1;
                   3494:                     }
                   3495:                     $cfile = $resurl;
1.1199    raeburn  3496:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3497:                     $incourse = 1;
                   3498:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3499:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3500:                     $incourse = 1;
1.1199    raeburn  3501:                     if ($env{'form.forceedit'}) {
                   3502:                         $forceview = 1;
                   3503:                     } else {
                   3504:                         $forceedit = 1;
                   3505:                     }
                   3506:                     $cfile = $resurl;
1.1343    raeburn  3507:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3508:                     $incourse = 1;
                   3509:                     if ($env{'form.forceedit'}) {
                   3510:                         $forceview = 1;
                   3511:                     } else {
                   3512:                         $forceedit = 1;
                   3513:                     }
                   3514:                     $cfile = $resurl;
1.1208    raeburn  3515:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3516:                     $incourse = 1;
                   3517:                     if ($env{'form.forceedit'}) {
                   3518:                         $forceview = 1;
                   3519:                     } else {
                   3520:                         $forceedit = 1;
                   3521:                     }
                   3522:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3523:                 }
                   3524:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3525:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3526:                 if (&is_on_map($template)) { 
                   3527:                     $incourse = 1;
                   3528:                     $forceview = 1;
                   3529:                     $cfile = $template;
1.1193    raeburn  3530:                 }
1.1199    raeburn  3531:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3532:                     $incourse = 1;
                   3533:                     if ($env{'form.forceedit'}) {
                   3534:                         $forceview = 1;
                   3535:                     } else {
                   3536:                         $forceedit = 1;
                   3537:                     }
                   3538:                     $cfile = $resurl;
1.1343    raeburn  3539:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3540:                 $incourse = 1;
                   3541:                 if ($env{'form.forceedit'}) {
                   3542:                     $forceview = 1;
                   3543:                 } else {
                   3544:                     $forceedit = 1;
                   3545:                 }
                   3546:                 $cfile = $resurl;
1.1199    raeburn  3547:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3548:                 $incourse = 1;
                   3549:                 $forceview = 1;
                   3550:                 if ($symb) {
                   3551:                     my ($map,$id,$res)=&decode_symb($symb);
                   3552:                     $env{'request.symb'} = $symb;
                   3553:                     $cfile = &clutter($res);
                   3554:                 } else {
                   3555:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3556:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3557:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3558:                         $cfile = '/adm/wrapper'.$escfile;
                   3559:                     } else {
                   3560:                         $escfile =~ s{^http://}{};
                   3561:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3562:                     }
1.1199    raeburn  3563:                 }
1.1234    raeburn  3564:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3565:                 if ($env{'form.forceedit'}) {
                   3566:                     $forceview = 1;
                   3567:                 } else {
                   3568:                     $forceedit = 1;
                   3569:                 }
                   3570:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3571:             }
                   3572:         }
1.1194    raeburn  3573:         if ($uploaded || $incourse) {
                   3574:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3575:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3576:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3577:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3578:             # Check that the user has permission to edit this resource
                   3579:             my $setpriv = 1;
                   3580:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3581:             if (defined($cfudom)) {
                   3582:                 $home=&homeserver($cfuname,$cfudom);
                   3583:                 $cfile=$file;
                   3584:             }
                   3585:         }
1.1194    raeburn  3586:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3587:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3588:             my @ids=&current_machine_ids();
                   3589:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3590:                 $switchserver=1;
                   3591:             }
                   3592:         }
                   3593:     }
1.1194    raeburn  3594:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3595: }
                   3596: 
                   3597: sub is_course_upload {
                   3598:     my ($file,$cnum,$cdom) = @_;
                   3599:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3600:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3601:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3602:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3603:         return 1;
                   3604:     }
                   3605:     return;
                   3606: }
                   3607: 
1.1194    raeburn  3608: sub in_course {
1.1195    raeburn  3609:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3610:     if ($hideprivileged) {
                   3611:         my $skipuser;
1.1219    raeburn  3612:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3613:         my @possdoms = ($cdom);  
                   3614:         if ($coursehash{'checkforpriv'}) { 
                   3615:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3616:         }
                   3617:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3618:             $skipuser = 1;
                   3619:             if ($coursehash{'nothideprivileged'}) {
                   3620:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3621:                     my $user;
                   3622:                     if ($item =~ /:/) {
                   3623:                         $user = $item;
                   3624:                     } else {
                   3625:                         $user = join(':',split(/[\@]/,$item));
                   3626:                     }
                   3627:                     if ($user eq $uname.':'.$udom) {
                   3628:                         undef($skipuser);
                   3629:                         last;
                   3630:                     }
                   3631:                 }
                   3632:             }
                   3633:             if ($skipuser) {
                   3634:                 return 0;
                   3635:             }
                   3636:         }
                   3637:     }
1.1194    raeburn  3638:     $type ||= 'any';
                   3639:     if (!defined($cdom) || !defined($cnum)) {
                   3640:         my $cid  = $env{'request.course.id'};
                   3641:         $cdom = $env{'course.'.$cid.'.domain'};
                   3642:         $cnum = $env{'course.'.$cid.'.num'};
                   3643:     }
                   3644:     my $typesref;
1.1195    raeburn  3645:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3646:         $typesref = ['active','previous','future'];
                   3647:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3648:         $typesref = [$type];
                   3649:     }
                   3650:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3651:                               $typesref,undef,[$cdom]);
                   3652:     my ($tmp) = keys(%roles);
                   3653:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3654:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3655:     if (@course_roles > 0) {
                   3656:         return 1;
                   3657:     }
                   3658:     return 0;
                   3659: }
                   3660: 
1.478     albertel 3661: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3662: # input: action, courseID, current domain, intended
1.637     raeburn  3663: #        path to file, source of file, instruction to parse file for objects,
                   3664: #        ref to hash for embedded objects,
                   3665: #        ref to hash for codebase of java objects.
1.1095    raeburn  3666: #        reference to scalar to accommodate mime type determined
                   3667: #          from File::MMagic if $parser = parse.
1.637     raeburn  3668: #
1.485     raeburn  3669: # output: url to file (if action was uploaddoc), 
                   3670: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3671: #
1.478     albertel 3672: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3673: # course.
1.477     raeburn  3674: #
1.478     albertel 3675: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3676: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3677: #          course's home server.
1.477     raeburn  3678: #
1.478     albertel 3679: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3680: #          be copied from $source (current location) to 
                   3681: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3682: #         and will then be copied to
                   3683: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3684: #         course's home server.
1.485     raeburn  3685: #
1.481     raeburn  3686: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3687: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3688: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3689: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3690: #         in course's home server.
1.637     raeburn  3691: #
1.477     raeburn  3692: 
                   3693: sub process_coursefile {
1.1095    raeburn  3694:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3695:         $mimetype)=@_;
1.477     raeburn  3696:     my $fetchresult;
1.638     albertel 3697:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3698:     if ($action eq 'propagate') {
1.638     albertel 3699:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3700: 			     $home);
1.481     raeburn  3701:     } else {
1.477     raeburn  3702:         my $fpath = '';
                   3703:         my $fname = $file;
1.478     albertel 3704:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3705:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3706:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3707:         if ($action eq 'copy') {
                   3708:             if ($source eq '') {
                   3709:                 $fetchresult = 'no source file';
                   3710:                 return $fetchresult;
                   3711:             } else {
                   3712:                 my $destination = $filepath.'/'.$fname;
                   3713:                 rename($source,$destination);
                   3714:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3715:                                  $home);
1.481     raeburn  3716:             }
                   3717:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3718:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3719:             print $fh $env{'form.'.$source};
1.481     raeburn  3720:             close($fh);
1.637     raeburn  3721:             if ($parser eq 'parse') {
1.1024    raeburn  3722:                 my $mm = new File::MMagic;
1.1095    raeburn  3723:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3724:                 if ($type eq 'text/html') {
1.1024    raeburn  3725:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3726:                     unless ($parse_result eq 'ok') {
                   3727:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3728:                     }
1.637     raeburn  3729:                 }
1.1095    raeburn  3730:                 if (ref($mimetype)) {
                   3731:                     $$mimetype = $type;
                   3732:                 } 
1.637     raeburn  3733:             }
1.477     raeburn  3734:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3735:                                  $home);
1.481     raeburn  3736:             if ($fetchresult eq 'ok') {
                   3737:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3738:             } else {
                   3739:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3740:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3741:                 return '/adm/notfound.html';
                   3742:             }
1.477     raeburn  3743:         }
                   3744:     }
1.485     raeburn  3745:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3746:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3747:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3748:     }
                   3749:     return $fetchresult;
                   3750: }
                   3751: 
1.637     raeburn  3752: sub build_filepath {
                   3753:     my ($fpath) = @_;
                   3754:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3755:     unless ($fpath eq '') {
                   3756:         my @parts=split('/',$fpath);
                   3757:         foreach my $part (@parts) {
                   3758:             $filepath.= '/'.$part;
                   3759:             if ((-e $filepath)!=1) {
                   3760:                 mkdir($filepath,0777);
                   3761:             }
                   3762:         }
                   3763:     }
                   3764:     return $filepath;
                   3765: }
                   3766: 
                   3767: sub store_edited_file {
1.638     albertel 3768:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3769:     my $file = $primary_url;
                   3770:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3771:     my $fpath = '';
                   3772:     my $fname = $file;
                   3773:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3774:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3775:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3776:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3777:     print $fh $content;
                   3778:     close($fh);
1.638     albertel 3779:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3780:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3781: 			  $home);
1.637     raeburn  3782:     if ($$fetchresult eq 'ok') {
                   3783:         return '/uploaded/'.$fpath.'/'.$fname;
                   3784:     } else {
1.638     albertel 3785:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3786: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3787:         return '/adm/notfound.html';
                   3788:     }
                   3789: }
                   3790: 
1.531     albertel 3791: sub clean_filename {
1.831     albertel 3792:     my ($fname,$args)=@_;
1.315     www      3793: # Replace Windows backslashes by forward slashes
1.257     www      3794:     $fname=~s/\\/\//g;
1.831     albertel 3795:     if (!$args->{'keep_path'}) {
                   3796:         # Get rid of everything but the actual filename
                   3797: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3798:     }
1.315     www      3799: # Replace spaces by underscores
                   3800:     $fname=~s/\s+/\_/g;
                   3801: # Replace all other weird characters by nothing
1.831     albertel 3802:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3803: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3804: # numbers
                   3805:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3806:     return $fname;
                   3807: }
1.1051    raeburn  3808: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3809: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3810: # image with the same aspect ratio as the original, but with dimensions which do 
                   3811: # not exceed $resizewidth and $resizeheight.
                   3812:  
1.984     neumanie 3813: sub resizeImage {
1.1051    raeburn  3814:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3815:     my $ima = Image::Magick->new;
                   3816:     my $resized;
                   3817:     if (-e $img_path) {
                   3818:         $ima->Read($img_path);
                   3819:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3820:             my $width = $ima->Get('width');
                   3821:             my $height = $ima->Get('height');
                   3822:             if ($width > $resizewidth) {
                   3823: 	        my $factor = $width/$resizewidth;
                   3824:                 my $newheight = $height/$factor;
                   3825:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3826:                 $resized = 1;
                   3827:             }
                   3828:         }
                   3829:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3830:             my $width = $ima->Get('width');
                   3831:             my $height = $ima->Get('height');
                   3832:             if ($height > $resizeheight) {
                   3833:                 my $factor = $height/$resizeheight;
                   3834:                 my $newwidth = $width/$factor;
                   3835:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3836:                 $resized = 1;
                   3837:             }
                   3838:         }
                   3839:         if ($resized) {
                   3840:             $ima->Write($img_path);
                   3841:         }
                   3842:     }
                   3843:     return;
1.977     amueller 3844: }
                   3845: 
1.608     albertel 3846: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3847: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3848: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3849: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3850: #                                    canceloverwrite, or ''. 
                   3851: #                   if 'coursedoc': upload to the current course
                   3852: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3853: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3854: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3855: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3856: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3857: #        $allfiles - reference to hash for embedded objects
                   3858: #        $codebase - reference to hash for codebase of java objects
                   3859: #        $desuname - username for permanent storage of uploaded file
                   3860: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3861: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3862: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3863: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3864: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3865: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3866: #                    from File::MMagic.
1.858     raeburn  3867: # 
1.686     albertel 3868: # output: url of file in userspace, or error: <message> 
                   3869: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3870: 
1.531     albertel 3871: sub userfileupload {
1.1090    raeburn  3872:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3873:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3874:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3875:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3876:     $fname=&clean_filename($fname);
1.1090    raeburn  3877:     # See if there is anything left
1.257     www      3878:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3879:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3880:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3881:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3882:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3883:         my $now = time;
1.1090    raeburn  3884:         my $filepath;
1.1095    raeburn  3885:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3886:              $filepath = 'tmp/helprequests/'.$now;
                   3887:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3888:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3889:                          '_'.$env{'user.domain'}.'/pending';
                   3890:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3891:             my ($docuname,$docudom);
1.1350    raeburn  3892:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3893:                 $docudom = $destudom;
                   3894:             } else {
                   3895:                 $docudom = $env{'user.domain'};
                   3896:             }
1.1350    raeburn  3897:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3898:                 $docuname = $destuname;
                   3899:             } else {
                   3900:                 $docuname = $env{'user.name'};
                   3901:             }
                   3902:             if (exists($env{'form.group'})) {
                   3903:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3904:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3905:             }
                   3906:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3907:             if ($context eq 'canceloverwrite') {
                   3908:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3909:                 if (-e  $tempfile) {
                   3910:                     my @info = stat($tempfile);
                   3911:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3912:                         unlink($tempfile);
                   3913:                     }
                   3914:                 }
                   3915:                 return;
1.523     raeburn  3916:             }
                   3917:         }
1.1090    raeburn  3918:         # Create the directory if not present
1.741     raeburn  3919:         my @parts=split(/\//,$filepath);
                   3920:         my $fullpath = $perlvar{'lonDaemons'};
                   3921:         for (my $i=0;$i<@parts;$i++) {
                   3922:             $fullpath .= '/'.$parts[$i];
                   3923:             if ((-e $fullpath)!=1) {
                   3924:                 mkdir($fullpath,0777);
                   3925:             }
                   3926:         }
1.1359    raeburn  3927:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3928:         print $fh $env{'form.'.$formname};
                   3929:         close($fh);
1.1090    raeburn  3930:         if ($context eq 'existingfile') {
                   3931:             my @info = stat($fullpath.'/'.$fname);
                   3932:             return ($fullpath.'/'.$fname,$info[9]);
                   3933:         } else {
                   3934:             return $fullpath.'/'.$fname;
                   3935:         }
1.523     raeburn  3936:     }
1.995     raeburn  3937:     if ($subdir eq 'scantron') {
                   3938:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3939:     } else {
1.995     raeburn  3940:         $fname="$subdir/$fname";
                   3941:     }
1.1090    raeburn  3942:     if ($context eq 'coursedoc') {
1.638     albertel 3943: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3944: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3945:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3946:             return &finishuserfileupload($docuname,$docudom,
                   3947: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3948: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3949:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3950:         } else {
1.1218    raeburn  3951:             if ($env{'form.folder'}) {
                   3952:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3953:             }
1.638     albertel 3954:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3955: 				       $fname,$formname,$parser,
1.1095    raeburn  3956: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3957:         }
1.719     banghart 3958:     } elsif (defined($destuname)) {
                   3959:         my $docuname=$destuname;
                   3960:         my $docudom=$destudom;
1.860     raeburn  3961: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3962: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3963:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3964:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3965:     } else {
1.638     albertel 3966:         my $docuname=$env{'user.name'};
                   3967:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3968:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3969:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3970:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3971:         }
1.860     raeburn  3972: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3973: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3974:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3975:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3976:     }
1.271     www      3977: }
                   3978: 
                   3979: sub finishuserfileupload {
1.860     raeburn  3980:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3981:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3982:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3983:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3984:   
1.860     raeburn  3985:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3986:     $file=$fname;
                   3987:     if ($fname=~m|/|) {
                   3988:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3989: 	$path.=$fnamepath.'/';
                   3990:     }
1.259     www      3991:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3992:     my $count;
                   3993:     for ($count=4;$count<=$#parts;$count++) {
                   3994:         $filepath.="/$parts[$count]";
                   3995:         if ((-e $filepath)!=1) {
                   3996: 	    mkdir($filepath,0777);
                   3997:         }
                   3998:     }
1.984     neumanie 3999: 
1.258     www      4000: # Save the file
                   4001:     {
1.1359    raeburn  4002: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4003: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4004: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4005: 	    return '/adm/notfound.html';
                   4006: 	}
1.1090    raeburn  4007:         if ($context eq 'overwrite') {
1.1117    foxr     4008:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4009:             my $target = $filepath.'/'.$file;
                   4010:             if (-e $source) {
                   4011:                 my @info = stat($source);
                   4012:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4013:                     unless (&File::Copy::move($source,$target)) {
                   4014:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4015:                         return "Moving from $source failed";
                   4016:                     }
                   4017:                 } else {
                   4018:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4019:                 }
                   4020:             } else {
                   4021:                 return "Temporary file: $source missing";
                   4022:             }
                   4023:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4024: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4025: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4026: 	    return '/adm/notfound.html';
                   4027: 	}
1.570     albertel 4028: 	close(FH);
1.1051    raeburn  4029:         if ($resizewidth && $resizeheight) {
                   4030:             my $mm = new File::MMagic;
                   4031:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4032:             if ($mime_type =~ m{^image/}) {
                   4033: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4034:             }  
1.977     amueller 4035: 	}
1.258     www      4036:     }
1.1152    raeburn  4037:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4038:         if (ref($mimetype)) {
                   4039:             if ($$mimetype eq '') {
                   4040:                 my $mm = new File::MMagic;
                   4041:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4042:                 $$mimetype = $type;
                   4043:             }
                   4044:         }
                   4045:     }
1.637     raeburn  4046:     if ($parser eq 'parse') {
1.1152    raeburn  4047:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4048:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4049:                                                        $allfiles,$codebase);
                   4050:             unless ($parse_result eq 'ok') {
                   4051:                 &logthis('Failed to parse '.$filepath.$file.
                   4052: 	   	         ' for embedded media: '.$parse_result); 
                   4053:             }
1.637     raeburn  4054:         }
                   4055:     }
1.860     raeburn  4056:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4057:         my $input = $filepath.'/'.$file;
                   4058:         my $output = $filepath.'/'.'tn-'.$file;
                   4059:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4060:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4061:         system({$args[0]} @args);
1.860     raeburn  4062:         if (-e $filepath.'/'.'tn-'.$file) {
                   4063:             $fetchthumb  = 1; 
                   4064:         }
                   4065:     }
1.858     raeburn  4066:  
1.259     www      4067: # Notify homeserver to grep it
                   4068: #
1.984     neumanie 4069:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4070:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4071:     if ($fetchresult eq 'ok') {
1.860     raeburn  4072:         if ($fetchthumb) {
                   4073:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4074:             if ($thumbresult ne 'ok') {
                   4075:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4076:                          $docuhome.': '.$thumbresult);
                   4077:             }
                   4078:         }
1.259     www      4079: #
1.258     www      4080: # Return the URL to it
1.494     albertel 4081:         return '/uploaded/'.$path.$file;
1.263     www      4082:     } else {
1.494     albertel 4083:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4084: 		 ': '.$fetchresult);
1.263     www      4085:         return '/adm/notfound.html';
1.858     raeburn  4086:     }
1.493     albertel 4087: }
                   4088: 
1.637     raeburn  4089: sub extract_embedded_items {
1.961     raeburn  4090:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4091:     my @state = ();
1.1164    raeburn  4092:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4093:     my %javafiles = (
                   4094:                       codebase => '',
                   4095:                       code => '',
                   4096:                       archive => ''
                   4097:                     );
                   4098:     my %mediafiles = (
                   4099:                       src => '',
                   4100:                       movie => '',
                   4101:                      );
1.648     raeburn  4102:     my $p;
                   4103:     if ($content) {
                   4104:         $p = HTML::LCParser->new($content);
                   4105:     } else {
1.961     raeburn  4106:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4107:     }
1.641     albertel 4108:     while (my $t=$p->get_token()) {
1.640     albertel 4109: 	if ($t->[0] eq 'S') {
                   4110: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4111: 	    push(@state, $tagname);
1.648     raeburn  4112:             if (lc($tagname) eq 'allow') {
                   4113:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4114:             }
1.640     albertel 4115: 	    if (lc($tagname) eq 'img') {
                   4116: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4117: 	    }
1.886     albertel 4118: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4119:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4120:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4121:                 }
1.886     albertel 4122: 	    }
1.645     raeburn  4123:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4124:                 my $src;
1.645     raeburn  4125:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4126:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4127:                 } else {
1.1164    raeburn  4128:                     if ($attr->{'src'} ne '') {
                   4129:                         $src = $attr->{'src'};
                   4130:                         &add_filetype($allfiles,$src,'src');
                   4131:                     }
                   4132:                 }
                   4133:                 my $text = $p->get_trimmed_text();
                   4134:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4135:                     my @swfargs = split(/,/,$1);
                   4136:                     foreach my $item (@swfargs) {
                   4137:                         $item =~ s/["']//g;
                   4138:                         $item =~ s/^\s+//;
                   4139:                         $item =~ s/\s+$//;
                   4140:                     }
                   4141:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4142:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4143:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4144:                         } else {
                   4145:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4146:                         }
                   4147:                     }
1.645     raeburn  4148:                 }
                   4149:             }
                   4150:             if (lc($tagname) eq 'link') {
                   4151:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4152:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4153:                 }
                   4154:             }
1.640     albertel 4155: 	    if (lc($tagname) eq 'object' ||
                   4156: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4157: 		foreach my $item (keys(%javafiles)) {
                   4158: 		    $javafiles{$item} = '';
                   4159: 		}
1.1164    raeburn  4160:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4161:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4162:                 }
1.640     albertel 4163: 	    }
                   4164: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4165: 		my $name = lc($attr->{'name'});
                   4166: 		foreach my $item (keys(%javafiles)) {
                   4167: 		    if ($name eq $item) {
                   4168: 			$javafiles{$item} = $attr->{'value'};
                   4169: 			last;
                   4170: 		    }
                   4171: 		}
1.1164    raeburn  4172:                 my $pathfrom;
1.640     albertel 4173: 		foreach my $item (keys(%mediafiles)) {
                   4174: 		    if ($name eq $item) {
1.1164    raeburn  4175:                         $pathfrom = $attr->{'value'};
                   4176:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4177: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4178: 			last;
                   4179: 		    }
                   4180: 		}
1.1164    raeburn  4181:                 if ($name eq 'flashvars') {
                   4182:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4183:                 }
                   4184:                 if ($pathfrom ne '') {
                   4185:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4186:                                          $pathfrom);
                   4187:                 }
1.640     albertel 4188: 	    }
                   4189: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4190: 		foreach my $item (keys(%javafiles)) {
                   4191: 		    if ($attr->{$item}) {
                   4192: 			$javafiles{$item} = $attr->{$item};
                   4193: 			last;
                   4194: 		    }
                   4195: 		}
                   4196: 		foreach my $item (keys(%mediafiles)) {
                   4197: 		    if ($attr->{$item}) {
                   4198: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4199: 			last;
                   4200: 		    }
                   4201: 		}
1.1164    raeburn  4202:                 if (lc($tagname) eq 'embed') {
                   4203:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4204:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4205:                                              $attr->{'src'});
                   4206:                     }
                   4207:                 }
1.640     albertel 4208: 	    }
1.1243    raeburn  4209:             if (lc($tagname) eq 'iframe') {
                   4210:                 my $src = $attr->{'src'} ;
                   4211:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4212:                     &add_filetype($allfiles,$src,'src');
                   4213:                 } elsif ($src =~ m{^/}) {
                   4214:                     if ($env{'request.course.id'}) {
                   4215:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4216:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4217:                         my $url = &hreflocation('',$fullpath);
                   4218:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4219:                             my $relpath = $1;
                   4220:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4221:                                 &add_filetype($allfiles,$1,'src');
                   4222:                             }
                   4223:                         }
                   4224:                     }
                   4225:                 }
                   4226:             }
1.1164    raeburn  4227:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4228:                 pop(@state);
1.1164    raeburn  4229:             }
1.640     albertel 4230: 	} elsif ($t->[0] eq 'E') {
                   4231: 	    my ($tagname) = ($t->[1]);
                   4232: 	    if ($javafiles{'codebase'} ne '') {
                   4233: 		$javafiles{'codebase'} .= '/';
                   4234: 	    }  
                   4235: 	    if (lc($tagname) eq 'applet' ||
                   4236: 		lc($tagname) eq 'object' ||
                   4237: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4238: 		) {
                   4239: 		foreach my $item (keys(%javafiles)) {
                   4240: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4241: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4242: 			&add_filetype($allfiles,$file,$item);
                   4243: 		    }
                   4244: 		}
                   4245: 	    } 
                   4246: 	    pop @state;
                   4247: 	}
                   4248:     }
1.1164    raeburn  4249:     foreach my $id (sort(keys(%flashvars))) {
                   4250:         if ($shockwave{$id} ne '') {
                   4251:             my @pairs = split(/\&/,$flashvars{$id});
                   4252:             foreach my $pair (@pairs) {
                   4253:                 my ($key,$value) = split(/\=/,$pair);
                   4254:                 if ($key eq 'thumb') {
                   4255:                     &add_filetype($allfiles,$value,$key);
                   4256:                 } elsif ($key eq 'content') {
                   4257:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4258:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4259:                     if ($ext ne '') {
                   4260:                         &add_filetype($allfiles,$path.$value,$ext);
                   4261:                     }
                   4262:                 }
                   4263:             }
                   4264:         }
                   4265:     }
1.637     raeburn  4266:     return 'ok';
                   4267: }
                   4268: 
1.639     albertel 4269: sub add_filetype {
                   4270:     my ($allfiles,$file,$type)=@_;
                   4271:     if (exists($allfiles->{$file})) {
                   4272: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4273: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4274: 	}
                   4275:     } else {
                   4276: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4277:     }
                   4278: }
                   4279: 
1.1164    raeburn  4280: sub embedded_dependency {
                   4281:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4282:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4283:         if (($identifier ne '') &&
                   4284:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4285:             ($pathfrom ne '')) {
                   4286:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4287:             foreach my $dep (@{$related->{$identifier}}) {
                   4288:                 &add_filetype($allfiles,$path.$dep,'object');
                   4289:             }
                   4290:         }
                   4291:     }
                   4292:     return;
                   4293: }
                   4294: 
1.493     albertel 4295: sub removeuploadedurl {
1.984     neumanie 4296:     my ($url)=@_;	
                   4297:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4298:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4299: }
                   4300: 
                   4301: sub removeuserfile {
                   4302:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4303:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4304:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4305:     if ($result eq 'ok') {	
1.798     raeburn  4306:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4307:             my $metafile = $fname.'.meta';
                   4308:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4309: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4310:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4311:             my $sqlresult = 
1.823     albertel 4312:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4313:                                         'portfolio_metadata',$group,
                   4314:                                         'delete');
1.798     raeburn  4315:         }
                   4316:     }
                   4317:     return $result;
1.257     www      4318: }
1.15      www      4319: 
1.530     albertel 4320: sub mkdiruserfile {
                   4321:     my ($docuname,$docudom,$dir)=@_;
                   4322:     my $home=&homeserver($docuname,$docudom);
                   4323:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4324: }
                   4325: 
1.531     albertel 4326: sub renameuserfile {
                   4327:     my ($docuname,$docudom,$old,$new)=@_;
                   4328:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4329:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4330:                         &escape("$old").':'.&escape("$new"),$home);
                   4331:     if ($result eq 'ok') {
                   4332:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4333:             my $oldmeta = $old.'.meta';
                   4334:             my $newmeta = $new.'.meta';
                   4335:             my $metaresult = 
                   4336:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4337: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4338:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4339:             my $sqlresult = 
1.823     albertel 4340:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4341:                                         'portfolio_metadata',$group,
                   4342:                                         'delete');
1.798     raeburn  4343:         }
                   4344:     }
                   4345:     return $result;
1.531     albertel 4346: }
                   4347: 
1.14      www      4348: # ------------------------------------------------------------------------- Log
                   4349: 
                   4350: sub log {
                   4351:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4352:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4353: }
                   4354: 
                   4355: # ------------------------------------------------------------------ Course Log
1.352     www      4356: #
                   4357: # This routine flushes several buffers of non-mission-critical nature
                   4358: #
1.157     www      4359: 
                   4360: sub flushcourselogs {
1.352     www      4361:     &logthis('Flushing log buffers');
                   4362: #
                   4363: # course logs
                   4364: # This is a log of all transactions in a course, which can be used
                   4365: # for data mining purposes
                   4366: #
                   4367: # It also collects the courseid database, which lists last transaction
                   4368: # times and course titles for all courseids
                   4369: #
                   4370:     my %courseidbuffer=();
1.921     raeburn  4371:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4372:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4373: 		          &escape($courselogs{$crsid}),
                   4374: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4375: 	    delete $courselogs{$crsid};
                   4376:         } else {
                   4377:             &logthis('Failed to flush log buffer for '.$crsid);
                   4378:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4379:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4380:                         " exceeded maximum size, deleting.</font>");
                   4381:                delete $courselogs{$crsid};
                   4382:             }
1.352     www      4383:         }
1.920     raeburn  4384:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4385:             'description' => $coursedescrbuf{$crsid},
                   4386:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4387:             'type'        => $coursetypebuf{$crsid},
                   4388:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4389:         };
1.191     harris41 4390:     }
1.352     www      4391: #
                   4392: # Write course id database (reverse lookup) to homeserver of courses 
                   4393: # Is used in pickcourse
                   4394: #
1.840     albertel 4395:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4396:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4397:                                     $courseidbuffer{$crs_home},
                   4398:                                     $crs_home,'timeonly');
1.352     www      4399:     }
                   4400: #
                   4401: # File accesses
                   4402: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4403: #
1.449     matthew  4404:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4405:         if ($entry =~ /___count$/) {
                   4406:             my ($dom,$name);
1.807     albertel 4407:             ($dom,$name,undef)=
1.811     albertel 4408: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4409:             if (! defined($dom) || $dom eq '' || 
                   4410:                 ! defined($name) || $name eq '') {
1.620     albertel 4411:                 my $cid = $env{'request.course.id'};
                   4412:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4413:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4414:             }
1.450     matthew  4415:             my $value = $accesshash{$entry};
                   4416:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4417:             my %temphash=($url => $value);
1.449     matthew  4418:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4419:             if ($result eq 'ok') {
                   4420:                 delete $accesshash{$entry};
                   4421:             }
                   4422:         } else {
1.811     albertel 4423:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4424:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4425:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4426:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4427:                 delete $accesshash{$entry};
                   4428:             }
1.185     www      4429:         }
1.191     harris41 4430:     }
1.352     www      4431: #
                   4432: # Roles
                   4433: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4434: #
1.800     albertel 4435:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4436:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4437: 	    split(/\:/,$entry);
                   4438:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4439:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4440:                 $rudom,$runame) eq 'ok') {
                   4441: 	    delete $userrolehash{$entry};
                   4442:         }
                   4443:     }
1.662     raeburn  4444: #
1.1334    raeburn  4445: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4446: #
                   4447:     my %domrolebuffer = ();
1.1000    raeburn  4448:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4449:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4450:         if ($domrolebuffer{$rudom}) {
                   4451:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4452:                       '='.&escape($domainrolehash{$entry});
                   4453:         } else {
                   4454:             $domrolebuffer{$rudom}.=&escape($entry).
                   4455:                       '='.&escape($domainrolehash{$entry});
                   4456:         }
                   4457:         delete $domainrolehash{$entry};
                   4458:     }
                   4459:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4460: 	my %servers;
                   4461: 	if (defined(&domain($dom,'primary'))) {
                   4462: 	    my $primary=&domain($dom,'primary');
                   4463: 	    my $hostname=&hostname($primary);
                   4464: 	    $servers{$primary} = $hostname;
                   4465: 	} else { 
                   4466: 	    %servers = &get_servers($dom,'library');
                   4467: 	}
1.841     albertel 4468: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4469: 	    if (&reply('domroleput:'.$dom.':'.
                   4470: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4471: 		last;
                   4472: 	    } else {  
1.841     albertel 4473: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4474: 	    }
1.662     raeburn  4475:         }
                   4476:     }
1.186     www      4477:     $dumpcount++;
1.157     www      4478: }
                   4479: 
                   4480: sub courselog {
                   4481:     my $what=shift;
1.158     www      4482:     $what=time.':'.$what;
1.620     albertel 4483:     unless ($env{'request.course.id'}) { return ''; }
                   4484:     $coursedombuf{$env{'request.course.id'}}=
                   4485:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4486:     $coursenumbuf{$env{'request.course.id'}}=
                   4487:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4488:     $coursehombuf{$env{'request.course.id'}}=
                   4489:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4490:     $coursedescrbuf{$env{'request.course.id'}}=
                   4491:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4492:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4493:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4494:     $courseownerbuf{$env{'request.course.id'}}=
                   4495:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4496:     $coursetypebuf{$env{'request.course.id'}}=
                   4497:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4498:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4499: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4500:     } else {
1.620     albertel 4501: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4502:     }
1.620     albertel 4503:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4504: 	&flushcourselogs();
                   4505:     }
1.158     www      4506: }
                   4507: 
                   4508: sub courseacclog {
                   4509:     my $fnsymb=shift;
1.620     albertel 4510:     unless ($env{'request.course.id'}) { return ''; }
                   4511:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4512:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4513:         $what.=':POST';
1.583     matthew  4514:         # FIXME: Probably ought to escape things....
1.800     albertel 4515: 	foreach my $key (keys(%env)) {
                   4516:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4517:                 my $formitem = $1;
                   4518:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4519:                     $what.=':'.$formitem.'='.$env{$key};
                   4520:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4521:                     $what.=':'.$formitem.'='.$env{$key};
                   4522:                 }
1.158     www      4523:             }
1.191     harris41 4524:         }
1.583     matthew  4525:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4526:         # FIXME: We should not be depending on a form parameter that someone
                   4527:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4528:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4529:             $what.= ':POST';
                   4530:             # FIXME: Probably ought to escape things....
                   4531:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4532:                                  'crsdiscuss') {
1.620     albertel 4533:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4534:             }
                   4535:         }
1.158     www      4536:     }
                   4537:     &courselog($what);
1.149     www      4538: }
                   4539: 
1.185     www      4540: sub countacc {
                   4541:     my $url=&declutter(shift);
1.458     matthew  4542:     return if (! defined($url) || $url eq '');
1.620     albertel 4543:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4544: #
                   4545: # Mark that this url was used in this course
                   4546: #
1.620     albertel 4547:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4548: #
                   4549: # Increase the access count for this resource in this child process
                   4550: #
1.281     www      4551:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4552:     $accesshash{$key}++;
1.185     www      4553: }
1.349     www      4554: 
1.361     www      4555: sub linklog {
                   4556:     my ($from,$to)=@_;
                   4557:     $from=&declutter($from);
                   4558:     $to=&declutter($to);
                   4559:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4560:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4561: }
1.1160    www      4562: 
                   4563: sub statslog {
                   4564:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4565:     if ($users<2) { return; }
                   4566:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4567:             'course'       => $env{'request.course.id'},
                   4568:             'sections'     => '"all"',
                   4569:             'num_students' => $users,
                   4570:             'part'         => $part,
                   4571:             'symb'         => $symb,
                   4572:             'mean_tries'   => $av_attempts,
                   4573:             'deg_of_diff'  => $degdiff});
                   4574:     foreach my $key (keys(%dynstore)) {
                   4575:         $accesshash{$key}=$dynstore{$key};
                   4576:     }
                   4577: }
1.361     www      4578:   
1.349     www      4579: sub userrolelog {
                   4580:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4581:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4582:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4583:        $userrolehash
                   4584:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4585:                     =$tend.':'.$tstart;
1.662     raeburn  4586:     }
1.1169    droeschl 4587:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4588:        $userrolehash
                   4589:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4590:                     =$tend.':'.$tstart;
                   4591:     }
1.1334    raeburn  4592:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4593:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4594:        $domainrolehash
                   4595:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4596:                     = $tend.':'.$tstart;
                   4597:     }
1.351     www      4598: }
                   4599: 
1.957     raeburn  4600: sub courserolelog {
                   4601:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4602:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4603:         my $cdom = $1;
                   4604:         my $cnum = $2;
                   4605:         my $sec = $3;
                   4606:         my $namespace = 'rolelog';
                   4607:         my %storehash = (
                   4608:                            role    => $trole,
                   4609:                            start   => $tstart,
                   4610:                            end     => $tend,
                   4611:                            selfenroll => $selfenroll,
                   4612:                            context    => $context,
                   4613:                         );
                   4614:         if ($trole eq 'gr') {
                   4615:             $namespace = 'groupslog';
                   4616:             $storehash{'group'} = $sec;
                   4617:         } else {
                   4618:             $storehash{'section'} = $sec;
                   4619:         }
1.1188    raeburn  4620:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4621:                    $domain,$cnum,$cdom);
1.1184    raeburn  4622:         if (($trole ne 'st') || ($sec ne '')) {
                   4623:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4624:         }
                   4625:     }
                   4626:     return;
                   4627: }
                   4628: 
1.1184    raeburn  4629: sub domainrolelog {
                   4630:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4631:     if ($area =~ m{^/($match_domain)/$}) {
                   4632:         my $cdom = $1;
                   4633:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4634:         my $namespace = 'rolelog';
                   4635:         my %storehash = (
                   4636:                            role    => $trole,
                   4637:                            start   => $tstart,
                   4638:                            end     => $tend,
                   4639:                            context => $context,
                   4640:                         );
1.1188    raeburn  4641:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4642:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4643:     }
                   4644:     return;
                   4645: 
                   4646: }
                   4647: 
                   4648: sub coauthorrolelog {
                   4649:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4650:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4651:         my $audom = $1;
                   4652:         my $auname = $2;
                   4653:         my $namespace = 'rolelog';
                   4654:         my %storehash = (
                   4655:                            role    => $trole,
                   4656:                            start   => $tstart,
                   4657:                            end     => $tend,
                   4658:                            context => $context,
                   4659:                         );
1.1188    raeburn  4660:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4661:                    $domain,$auname,$audom);
1.1184    raeburn  4662:     }
                   4663:     return;
                   4664: }
                   4665: 
1.351     www      4666: sub get_course_adv_roles {
1.948     raeburn  4667:     my ($cid,$codes) = @_;
1.620     albertel 4668:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4669:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4670:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4671:     my %nothide=();
1.800     albertel 4672:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4673:         if ($user !~ /:/) {
                   4674: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4675:         } else {
                   4676:             $nothide{$user}=1;
                   4677:         }
1.470     www      4678:     }
1.1219    raeburn  4679:     my @possdoms = ($coursehash{'domain'});
                   4680:     if ($coursehash{'checkforpriv'}) {
                   4681:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4682:     }
1.351     www      4683:     my %returnhash=();
                   4684:     my %dumphash=
                   4685:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4686:     my $now=time;
1.997     raeburn  4687:     my %privileged;
1.1000    raeburn  4688:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4689: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4690:         if (($tstart) && ($tstart<0)) { next; }
                   4691:         if (($tend) && ($tend<$now)) { next; }
                   4692:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4693:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4694: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4695:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4696:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4697: 	if ($role eq 'cr') { next; }
1.948     raeburn  4698:         if ($codes) {
                   4699:             if ($section) { $role .= ':'.$section; }
                   4700:             if ($returnhash{$role}) {
                   4701:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4702:             } else {
                   4703:                 $returnhash{$role}=$username.':'.$domain;
                   4704:             }
1.351     www      4705:         } else {
1.988     raeburn  4706:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4707:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4708:             if ($returnhash{$key}) {
                   4709: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4710:             } else {
                   4711:                 $returnhash{$key}=$username.':'.$domain;
                   4712:             }
1.351     www      4713:         }
1.948     raeburn  4714:     }
1.400     www      4715:     return %returnhash;
                   4716: }
                   4717: 
                   4718: sub get_my_roles {
1.937     raeburn  4719:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4720:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4721:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4722:     my (%dumphash,%nothide);
1.1086    raeburn  4723:     if ($context eq 'userroles') {
1.1166    raeburn  4724:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4725:     } else {
1.1219    raeburn  4726:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4727:         if ($hidepriv) {
                   4728:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4729:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4730:                 if ($user !~ /:/) {
                   4731:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4732:                 } else {
                   4733:                     $nothide{$user} = 1;
                   4734:                 }
                   4735:             }
                   4736:         }
1.858     raeburn  4737:     }
1.400     www      4738:     my %returnhash=();
                   4739:     my $now=time;
1.999     raeburn  4740:     my %privileged;
1.800     albertel 4741:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4742:         my ($role,$tend,$tstart);
                   4743:         if ($context eq 'userroles') {
1.1149    raeburn  4744:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4745: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4746:         } else {
                   4747:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4748:         }
1.400     www      4749:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4750:         my $status = 'active';
1.939     raeburn  4751:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4752:             $status = 'previous';
                   4753:         } 
                   4754:         if (($tstart) && ($now<$tstart)) {
                   4755:             $status = 'future';
                   4756:         }
                   4757:         if (ref($types) eq 'ARRAY') {
                   4758:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4759:                 next;
                   4760:             } 
                   4761:         } else {
                   4762:             if ($status ne 'active') {
                   4763:                 next;
                   4764:             }
                   4765:         }
1.867     raeburn  4766:         my ($rolecode,$username,$domain,$section,$area);
                   4767:         if ($context eq 'userroles') {
1.1186    raeburn  4768:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4769:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4770:         } else {
                   4771:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4772:         }
1.832     raeburn  4773:         if (ref($roledoms) eq 'ARRAY') {
                   4774:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4775:                 next;
                   4776:             }
                   4777:         }
                   4778:         if (ref($roles) eq 'ARRAY') {
                   4779:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4780:                 if ($role =~ /^cr\//) {
                   4781:                     if (!grep(/^cr$/,@{$roles})) {
                   4782:                         next;
                   4783:                     }
1.1104    raeburn  4784:                 } elsif ($role =~ /^gr\//) {
                   4785:                     if (!grep(/^gr$/,@{$roles})) {
                   4786:                         next;
                   4787:                     }
1.922     raeburn  4788:                 } else {
                   4789:                     next;
                   4790:                 }
1.832     raeburn  4791:             }
1.867     raeburn  4792:         }
1.937     raeburn  4793:         if ($hidepriv) {
1.1219    raeburn  4794:             my @privroles = ('dc','su');
1.999     raeburn  4795:             if ($context eq 'userroles') {
1.1219    raeburn  4796:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4797:             } else {
1.1219    raeburn  4798:                 my $possdoms = [$domain];
                   4799:                 if (ref($roledoms) eq 'ARRAY') {
                   4800:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4801:                 }
1.1219    raeburn  4802:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4803:                     if (!$nothide{$username.':'.$domain}) {
                   4804:                         next;
                   4805:                     }
                   4806:                 }
1.937     raeburn  4807:             }
                   4808:         }
1.933     raeburn  4809:         if ($withsec) {
                   4810:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4811:                 $tstart.':'.$tend;
                   4812:         } else {
                   4813:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4814:         }
1.832     raeburn  4815:     }
1.373     www      4816:     return %returnhash;
1.399     www      4817: }
                   4818: 
1.1333    raeburn  4819: sub get_all_adhocroles {
                   4820:     my ($dom) = @_;
                   4821:     my @roles_by_num = ();
                   4822:     my %domdefaults = &get_domain_defaults($dom);
                   4823:     my (%description,%access_in_dom,%access_info);
                   4824:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4825:         my $count = 0;
                   4826:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4827:         my %ordered;
                   4828:         foreach my $role (sort(keys(%domcurrent))) {
                   4829:             my ($order,$desc,$access_in_dom);
                   4830:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4831:                 $order = $domcurrent{$role}{'order'};
                   4832:                 $desc = $domcurrent{$role}{'desc'};
                   4833:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4834:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4835:             }
                   4836:             if ($order eq '') {
                   4837:                 $order = $count;
                   4838:             }
                   4839:             $ordered{$order} = $role;
                   4840:             if ($desc ne '') {
                   4841:                 $description{$role} = $desc;
                   4842:             } else {
                   4843:                 $description{$role}= $role;
                   4844:             }
                   4845:             $count++;
                   4846:         }
                   4847:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4848:             push(@roles_by_num,$ordered{$item});
                   4849:         }
                   4850:     }
                   4851:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4852: }
                   4853: 
1.1332    raeburn  4854: sub get_my_adhocroles {
1.1333    raeburn  4855:     my ($cid,$checkreg) = @_;
                   4856:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4857:     if ($env{'request.course.id'} eq $cid) {
                   4858:         $cdom = $env{'course.'.$cid.'.domain'};
                   4859:         $cnum = $env{'course.'.$cid.'.num'};
                   4860:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4861:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4862:         $cdom = $1;
                   4863:         $cnum = $2;
                   4864:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4865:                                      $cdom,$cnum);
                   4866:     }
                   4867:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4868:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4869:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4870:         if ($rosterhash{$user} ne '') {
                   4871:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4872:             return ([],{}) if ($type eq 'auto');
                   4873:         }
                   4874:     }
                   4875:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4876:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4877:             my $then=$env{'user.login.time'};
                   4878:             my $update=$env{'user.update.time'};
1.1335    raeburn  4879:             if (!$update) {
                   4880:                 $update = $then;
                   4881:             }
                   4882:             my @liveroles;
1.1334    raeburn  4883:             foreach my $role ('dh','da') {
                   4884:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4885:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4886:                     my $limit = $update;
                   4887:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4888:                         $limit = $then;
                   4889:                     }
1.1335    raeburn  4890:                     my $activerole = 1;
                   4891:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4892:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4893:                     if ($activerole) {
                   4894:                         push(@liveroles,$role);
                   4895:                     }
1.1334    raeburn  4896:                 }
1.1332    raeburn  4897:             }
1.1335    raeburn  4898:             if (@liveroles) {
1.1332    raeburn  4899:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4900:                     my ($accessref,$accessinfo,%access_in_dom);
                   4901:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4902:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4903:                         if (@{$roles_by_num}) {
1.1332    raeburn  4904:                             my %settings;
                   4905:                             if ($env{'request.course.id'} eq $cid) {
                   4906:                                 foreach my $envkey (keys(%env)) {
                   4907:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4908:                                         $settings{$1} = $env{$envkey};
                   4909:                                     }
                   4910:                                 }
                   4911:                             } else {
                   4912:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4913:                             }
                   4914:                             my %setincrs;
                   4915:                             if ($settings{'internal.adhocaccess'}) {
                   4916:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4917:                             }
                   4918:                             my @statuses;
                   4919:                             if ($env{'environment.inststatus'}) {
                   4920:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4921:                             }
                   4922:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4923:                             if (ref($accessref) eq 'HASH') {
                   4924:                                 %access_in_dom = %{$accessref};
                   4925:                             }
                   4926:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4927:                                 my ($curraccess,@okstatus,@personnel);
                   4928:                                 if ($setincrs{$role}) {
                   4929:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4930:                                     if ($curraccess eq 'status') {
                   4931:                                         @okstatus = split(/\&/,$rest);
                   4932:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4933:                                         @personnel = split(/\&/,$rest);
                   4934:                                     }
                   4935:                                 } else {
                   4936:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4937:                                     if (ref($accessinfo) eq 'HASH') {
                   4938:                                         if ($curraccess eq 'status') {
                   4939:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4940:                                                 @okstatus = @{$accessinfo->{$role}};
                   4941:                                             }
                   4942:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4943:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4944:                                                 @personnel = @{$accessinfo->{$role}};
                   4945:                                             }
1.1332    raeburn  4946:                                         }
                   4947:                                     }
                   4948:                                 }
                   4949:                                 if ($curraccess eq 'none') {
                   4950:                                     next;
                   4951:                                 } elsif ($curraccess eq 'all') {
                   4952:                                     push(@possroles,$role);
1.1336    raeburn  4953:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4954:                                     if (grep(/^dh$/,@liveroles)) {
                   4955:                                         push(@possroles,$role);
                   4956:                                     } else {
                   4957:                                         next;
                   4958:                                     }
1.1336    raeburn  4959:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4960:                                     if (grep(/^da$/,@liveroles)) {
                   4961:                                         push(@possroles,$role);
                   4962:                                     } else {
                   4963:                                         next;
                   4964:                                     }
1.1332    raeburn  4965:                                 } elsif ($curraccess eq 'status') {
                   4966:                                     if (@okstatus) {
                   4967:                                         if (!@statuses) {
                   4968:                                             if (grep(/^default$/,@okstatus)) {
                   4969:                                                 push(@possroles,$role);
                   4970:                                             }
                   4971:                                         } else {
                   4972:                                             foreach my $status (@okstatus) {
                   4973:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4974:                                                     push(@possroles,$role);
                   4975:                                                     last;
                   4976:                                                 }
                   4977:                                             }
                   4978:                                         }
                   4979:                                     }
                   4980:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4981:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4982:                                         if ($curraccess eq 'exc') {
                   4983:                                             push(@possroles,$role);
                   4984:                                         }
                   4985:                                     } elsif ($curraccess eq 'inc') {
                   4986:                                         push(@possroles,$role);
                   4987:                                     }
                   4988:                                 }
                   4989:                             }
                   4990:                         }
                   4991:                     }
                   4992:                 }
                   4993:             }
                   4994:         }
                   4995:     }
1.1333    raeburn  4996:     unless (ref($description) eq 'HASH') {
                   4997:         if (ref($roles_by_num) eq 'ARRAY') {
                   4998:             my %desc;
                   4999:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5000:             $description = \%desc;
                   5001:         } else {
                   5002:             $description = {};
                   5003:         }
                   5004:     }
                   5005:     return (\@possroles,$description);
1.1332    raeburn  5006: }
                   5007: 
1.399     www      5008: # ----------------------------------------------------- Frontpage Announcements
                   5009: #
                   5010: #
                   5011: 
                   5012: sub postannounce {
                   5013:     my ($server,$text)=@_;
1.844     albertel 5014:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5015:     unless ($text=~/\w/) { $text=''; }
                   5016:     return &reply('setannounce:'.&escape($text),$server);
                   5017: }
                   5018: 
                   5019: sub getannounce {
1.448     albertel 5020: 
1.1359    raeburn  5021:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5022: 	my $announcement='';
1.800     albertel 5023: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5024: 	close($fh);
1.399     www      5025: 	if ($announcement=~/\w/) { 
                   5026: 	    return 
                   5027:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5028:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5029: 	} else {
                   5030: 	    return '';
                   5031: 	}
                   5032:     } else {
                   5033: 	return '';
                   5034:     }
1.351     www      5035: }
1.353     www      5036: 
                   5037: # ---------------------------------------------------------- Course ID routines
                   5038: # Deal with domain's nohist_courseid.db files
                   5039: #
                   5040: 
                   5041: sub courseidput {
1.921     raeburn  5042:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5043:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5044:     my $outcome;
                   5045:     if ($caller eq 'timeonly') {
                   5046:         my $cids = '';
                   5047:         foreach my $item (keys(%$storehash)) {
                   5048:             $cids.=&escape($item).'&';
                   5049:         }
                   5050:         $cids=~s/\&$//;
                   5051:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5052:                           $coursehome);       
                   5053:     } else {
                   5054:         my $items = '';
                   5055:         foreach my $item (keys(%$storehash)) {
                   5056:             $items.= &escape($item).'='.
                   5057:                      &freeze_escape($$storehash{$item}).'&';
                   5058:         }
                   5059:         $items=~s/\&$//;
                   5060:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5061:                           $coursehome);
1.918     raeburn  5062:     }
                   5063:     if ($outcome eq 'unknown_cmd') {
                   5064:         my $what;
                   5065:         foreach my $cid (keys(%$storehash)) {
                   5066:             $what .= &escape($cid).'=';
1.921     raeburn  5067:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5068:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5069:             }
                   5070:             $what =~ s/\:$/&/;
                   5071:         }
                   5072:         $what =~ s/\&$//;  
                   5073:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5074:     } else {
                   5075:         return $outcome;
                   5076:     }
1.353     www      5077: }
                   5078: 
                   5079: sub courseiddump {
1.921     raeburn  5080:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5081:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5082:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5083:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5084:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5085:     my $as_hash = 1;
                   5086:     my %returnhash;
                   5087:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5088:     my %libserv = &all_library();
                   5089:     foreach my $tryserver (keys(%libserv)) {
                   5090:         if ( (  $hostidflag == 1 
                   5091: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5092: 	     || (!defined($hostidflag)) ) {
                   5093: 
1.918     raeburn  5094: 	    if (($domfilter eq '') ||
                   5095: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5096:                 my $rep;
                   5097:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5098:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5099:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5100:                                 &escape($descfilter), &escape($instcodefilter), 
                   5101:                                 &escape($ownerfilter), &escape($coursefilter),
                   5102:                                 &escape($typefilter), &escape($regexp_ok), 
                   5103:                                 $as_hash, &escape($selfenrollonly), 
                   5104:                                 &escape($catfilter), $showhidden, $caller, 
                   5105:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5106:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5107:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5108:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5109:                 } else {
                   5110:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5111:                              $sincefilter.':'.&escape($descfilter).':'.
                   5112:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5113:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5114:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5115:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5116:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5117:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5118:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5119:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5120:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5121:                 }
                   5122:                      
1.918     raeburn  5123:                 my @pairs=split(/\&/,$rep);
                   5124:                 foreach my $item (@pairs) {
                   5125:                     my ($key,$value)=split(/\=/,$item,2);
                   5126:                     $key = &unescape($key);
                   5127:                     next if ($key =~ /^error: 2 /);
                   5128:                     my $result = &thaw_unescape($value);
                   5129:                     if (ref($result) eq 'HASH') {
                   5130:                         $returnhash{$key}=$result;
                   5131:                     } else {
1.921     raeburn  5132:                         my @responses = split(/:/,$value);
                   5133:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5134:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5135:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5136:                         }
1.1008    raeburn  5137:                     }
1.353     www      5138:                 }
                   5139:             }
                   5140:         }
                   5141:     }
                   5142:     return %returnhash;
                   5143: }
                   5144: 
1.1055    raeburn  5145: sub courselastaccess {
                   5146:     my ($cdom,$cnum,$hostidref) = @_;
                   5147:     my %returnhash;
                   5148:     if ($cdom && $cnum) {
                   5149:         my $chome = &homeserver($cnum,$cdom);
                   5150:         if ($chome ne 'no_host') {
                   5151:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5152:             &extract_lastaccess(\%returnhash,$rep);
                   5153:         }
                   5154:     } else {
                   5155:         if (!$cdom) { $cdom=''; }
                   5156:         my %libserv = &all_library();
                   5157:         foreach my $tryserver (keys(%libserv)) {
                   5158:             if (ref($hostidref) eq 'ARRAY') {
                   5159:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5160:             } 
                   5161:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5162:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5163:                 &extract_lastaccess(\%returnhash,$rep);
                   5164:             }
                   5165:         }
                   5166:     }
                   5167:     return %returnhash;
                   5168: }
                   5169: 
                   5170: sub extract_lastaccess {
                   5171:     my ($returnhash,$rep) = @_;
                   5172:     if (ref($returnhash) eq 'HASH') {
                   5173:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5174:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5175:                  $rep eq '') {
                   5176:             my @pairs=split(/\&/,$rep);
                   5177:             foreach my $item (@pairs) {
                   5178:                 my ($key,$value)=split(/\=/,$item,2);
                   5179:                 $key = &unescape($key);
                   5180:                 next if ($key =~ /^error: 2 /);
                   5181:                 $returnhash->{$key} = &thaw_unescape($value);
                   5182:             }
                   5183:         }
                   5184:     }
                   5185:     return;
                   5186: }
                   5187: 
1.658     raeburn  5188: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5189: 
                   5190: sub dcmailput {
1.685     raeburn  5191:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5192:     my $status = &Apache::lonnet::critical(
1.740     www      5193:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5194:        &escape($message),$server);
1.662     raeburn  5195:     return $status;
                   5196: }
                   5197: 
1.658     raeburn  5198: sub dcmaildump {
                   5199:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5200:     my %returnhash=();
1.846     albertel 5201: 
                   5202:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5203:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5204:                                                          &escape($enddate).':';
                   5205: 	my @esc_senders=map { &escape($_)} @$senders;
                   5206: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5207: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5208:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5209:             if (($key) && ($value)) {
                   5210:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5211:             }
                   5212:         }
                   5213:     }
                   5214:     return %returnhash;
                   5215: }
1.662     raeburn  5216: # ---------------------------------------------------------- Domain roles
                   5217: 
                   5218: sub get_domain_roles {
                   5219:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5220:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5221:         $startdate = '.';
                   5222:     }
1.1018    raeburn  5223:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5224:         $enddate = '.';
                   5225:     }
1.922     raeburn  5226:     my $rolelist;
                   5227:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5228:         $rolelist = join('&',@{$roles});
1.922     raeburn  5229:     }
1.662     raeburn  5230:     my %personnel = ();
1.841     albertel 5231: 
                   5232:     my %servers = &get_servers($dom,'library');
                   5233:     foreach my $tryserver (keys(%servers)) {
                   5234: 	%{$personnel{$tryserver}}=();
                   5235: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5236: 					    &escape($startdate).':'.
                   5237: 					    &escape($enddate).':'.
                   5238: 					    &escape($rolelist), $tryserver))) {
                   5239: 	    my ($key,$value) = split(/\=/,$line,2);
                   5240: 	    if (($key) && ($value)) {
                   5241: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5242: 	    }
                   5243: 	}
1.662     raeburn  5244:     }
                   5245:     return %personnel;
                   5246: }
1.658     raeburn  5247: 
1.1332    raeburn  5248: sub get_active_domroles {
                   5249:     my ($dom,$roles) = @_;
                   5250:     return () unless (ref($roles) eq 'ARRAY');
                   5251:     my $now = time;
                   5252:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5253:     my %domroles;
                   5254:     foreach my $server (keys(%dompersonnel)) {
                   5255:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5256:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5257:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5258:         }
                   5259:     }
                   5260:     return %domroles;
                   5261: }
                   5262: 
1.1057    www      5263: # ----------------------------------------------------------- Interval timing 
1.149     www      5264: 
1.1153    www      5265: {
                   5266: # Caches needed for speedup of navmaps
                   5267: # We don't want to cache this for very long at all (5 seconds at most)
                   5268: # 
                   5269: # The user for whom we cache
                   5270: my $cachedkey='';
                   5271: # The cached times for this user
                   5272: my %cachedtimes=();
                   5273: # When this was last done
1.1282    raeburn  5274: my $cachedtime='';
1.1153    www      5275: 
                   5276: sub load_all_first_access {
1.1308    raeburn  5277:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5278:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5279:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5280:         (!$ignorecache)) {
1.1154    raeburn  5281:         return;
                   5282:     }
                   5283:     $cachedtime=time;
                   5284:     $cachedkey=$uname.':'.$udom;
                   5285:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5286: }
                   5287: 
1.504     albertel 5288: sub get_first_access {
1.1308    raeburn  5289:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5290:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5291:     if ($argsymb) { $symb=$argsymb; }
                   5292:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5293:     if ($argmap) { $map = $argmap; }
1.926     albertel 5294:     if ($type eq 'course') {
                   5295: 	$res='course';
                   5296:     } elsif ($type eq 'map') {
1.588     albertel 5297: 	$res=&symbread($map);
                   5298:     } else {
                   5299: 	$res=$symb;
                   5300:     }
1.1308    raeburn  5301:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5302:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5303: }
                   5304: 
                   5305: sub set_first_access {
1.1162    raeburn  5306:     my ($type,$interval)=@_;
1.790     albertel 5307:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5308:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5309:     if ($type eq 'course') {
                   5310: 	$res='course';
                   5311:     } elsif ($type eq 'map') {
1.588     albertel 5312: 	$res=&symbread($map);
                   5313:     } else {
                   5314: 	$res=$symb;
                   5315:     }
1.1153    www      5316:     $cachedkey='';
1.1162    raeburn  5317:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5318:     if ($firstaccess) {
                   5319:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5320:                  "to set new value (type: $type, extent: $res) for $uname:$udom ". 
                   5321:                  "in $courseid"); 
                   5322:         return 'already_set';
                   5323:     } else {
1.1162    raeburn  5324:         my $start = time;
                   5325: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5326:                           $udom,$uname);
                   5327:         if ($putres eq 'ok') {
                   5328:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5329:                  $udom,$uname); 
                   5330:             &appenv(
                   5331:                      {
                   5332:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5333:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5334:                      }
                   5335:                   );
1.1365    raeburn  5336:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5337:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5338:             }
1.1386    raeburn  5339:         } elsif ($putres ne 'refused') {
                   5340:             &logthis("Result: $putres when attempting to set first access time ".
                   5341:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5342:         }
                   5343:         return $putres;
1.505     albertel 5344:     }
                   5345:     return 'already_set';
1.504     albertel 5346: }
1.1153    www      5347: }
1.1282    raeburn  5348: 
1.110     www      5349: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5350: 
                   5351: sub expirespread {
                   5352:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5353:     my $cid=$env{'request.course.id'}; 
1.110     www      5354:     if ($cid) {
                   5355:        my $now=time;
                   5356:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5357:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5358:                             $env{'course.'.$cid.'.num'}.
1.110     www      5359: 	        	    ':nohist_expirationdates:'.
                   5360:                             &escape($key).'='.$now,
1.620     albertel 5361:                             $env{'course.'.$cid.'.home'})
1.110     www      5362:     }
                   5363:     return 'ok';
1.14      www      5364: }
                   5365: 
1.109     www      5366: # ----------------------------------------------------- Devalidate Spreadsheets
                   5367: 
                   5368: sub devalidate {
1.325     www      5369:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5370:     my $cid=$env{'request.course.id'}; 
1.109     www      5371:     if ($cid) {
1.391     matthew  5372:         # delete the stored spreadsheets for
                   5373:         # - the student level sheet of this user in course's homespace
                   5374:         # - the assessment level sheet for this resource 
                   5375:         #   for this user in user's homespace
1.553     albertel 5376: 	# - current conditional state info
1.325     www      5377: 	my $key=$uname.':'.$udom.':';
1.109     www      5378:         my $status=
1.299     matthew  5379: 	    &del('nohist_calculatedsheets',
1.391     matthew  5380: 		 [$key.'studentcalc:'],
1.620     albertel 5381: 		 $env{'course.'.$cid.'.domain'},
                   5382: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5383: 		.' '.
                   5384: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5385: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5386:         unless ($status eq 'ok ok') {
                   5387:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5388:                     $uname.' at '.$udom.' for '.
1.109     www      5389: 		    $symb.': '.$status);
1.133     albertel 5390:         }
1.553     albertel 5391: 	&delenv('user.state.'.$cid);
1.109     www      5392:     }
                   5393: }
                   5394: 
1.265     albertel 5395: sub get_scalar {
                   5396:     my ($string,$end) = @_;
                   5397:     my $value;
                   5398:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5399: 	$value = $1;
                   5400:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5401: 	$value = $1;
                   5402:     }
                   5403:     return &unescape($value);
                   5404: }
                   5405: 
                   5406: sub array2str {
                   5407:   my (@array) = @_;
                   5408:   my $result=&arrayref2str(\@array);
                   5409:   $result=~s/^__ARRAY_REF__//;
                   5410:   $result=~s/__END_ARRAY_REF__$//;
                   5411:   return $result;
                   5412: }
                   5413: 
1.204     albertel 5414: sub arrayref2str {
                   5415:   my ($arrayref) = @_;
1.265     albertel 5416:   my $result='__ARRAY_REF__';
1.204     albertel 5417:   foreach my $elem (@$arrayref) {
1.265     albertel 5418:     if(ref($elem) eq 'ARRAY') {
                   5419:       $result.=&arrayref2str($elem).'&';
                   5420:     } elsif(ref($elem) eq 'HASH') {
                   5421:       $result.=&hashref2str($elem).'&';
                   5422:     } elsif(ref($elem)) {
                   5423:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5424:     } else {
                   5425:       $result.=&escape($elem).'&';
                   5426:     }
                   5427:   }
                   5428:   $result=~s/\&$//;
1.265     albertel 5429:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5430:   return $result;
                   5431: }
                   5432: 
1.168     albertel 5433: sub hash2str {
1.204     albertel 5434:   my (%hash) = @_;
                   5435:   my $result=&hashref2str(\%hash);
1.265     albertel 5436:   $result=~s/^__HASH_REF__//;
                   5437:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5438:   return $result;
                   5439: }
                   5440: 
                   5441: sub hashref2str {
                   5442:   my ($hashref)=@_;
1.265     albertel 5443:   my $result='__HASH_REF__';
1.800     albertel 5444:   foreach my $key (sort(keys(%$hashref))) {
                   5445:     if (ref($key) eq 'ARRAY') {
                   5446:       $result.=&arrayref2str($key).'=';
                   5447:     } elsif (ref($key) eq 'HASH') {
                   5448:       $result.=&hashref2str($key).'=';
                   5449:     } elsif (ref($key)) {
1.265     albertel 5450:       $result.='=';
1.800     albertel 5451:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5452:     } else {
1.1132    raeburn  5453: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5454:     }
                   5455: 
1.800     albertel 5456:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5457:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5458:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5459:       $result.=&hashref2str($hashref->{$key}).'&';
                   5460:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5461:        $result.='&';
1.800     albertel 5462:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5463:     } else {
1.800     albertel 5464:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5465:     }
                   5466:   }
1.168     albertel 5467:   $result=~s/\&$//;
1.265     albertel 5468:   $result .= '__END_HASH_REF__';
1.168     albertel 5469:   return $result;
                   5470: }
                   5471: 
                   5472: sub str2hash {
1.265     albertel 5473:     my ($string)=@_;
                   5474:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5475:     return %$hash;
                   5476: }
                   5477: 
                   5478: sub str2hashref {
1.168     albertel 5479:   my ($string) = @_;
1.265     albertel 5480: 
                   5481:   my %hash;
                   5482: 
                   5483:   if($string !~ /^__HASH_REF__/) {
                   5484:       if (! ($string eq '' || !defined($string))) {
                   5485: 	  $hash{'error'}='Not hash reference';
                   5486:       }
                   5487:       return (\%hash, $string);
                   5488:   }
                   5489: 
                   5490:   $string =~ s/^__HASH_REF__//;
                   5491: 
                   5492:   while($string !~ /^__END_HASH_REF__/) {
                   5493:       #key
                   5494:       my $key='';
                   5495:       if($string =~ /^__HASH_REF__/) {
                   5496:           ($key, $string)=&str2hashref($string);
                   5497:           if(defined($key->{'error'})) {
                   5498:               $hash{'error'}='Bad data';
                   5499:               return (\%hash, $string);
                   5500:           }
                   5501:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5502:           ($key, $string)=&str2arrayref($string);
                   5503:           if($key->[0] eq 'Array reference error') {
                   5504:               $hash{'error'}='Bad data';
                   5505:               return (\%hash, $string);
                   5506:           }
                   5507:       } else {
                   5508:           $string =~ s/^(.*?)=//;
1.267     albertel 5509: 	  $key=&unescape($1);
1.265     albertel 5510:       }
                   5511:       $string =~ s/^=//;
                   5512: 
                   5513:       #value
                   5514:       my $value='';
                   5515:       if($string =~ /^__HASH_REF__/) {
                   5516:           ($value, $string)=&str2hashref($string);
                   5517:           if(defined($value->{'error'})) {
                   5518:               $hash{'error'}='Bad data';
                   5519:               return (\%hash, $string);
                   5520:           }
                   5521:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5522:           ($value, $string)=&str2arrayref($string);
                   5523:           if($value->[0] eq 'Array reference error') {
                   5524:               $hash{'error'}='Bad data';
                   5525:               return (\%hash, $string);
                   5526:           }
                   5527:       } else {
                   5528: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5529:       }
                   5530:       $string =~ s/^&//;
                   5531: 
                   5532:       $hash{$key}=$value;
1.204     albertel 5533:   }
1.265     albertel 5534: 
                   5535:   $string =~ s/^__END_HASH_REF__//;
                   5536: 
                   5537:   return (\%hash, $string);
1.204     albertel 5538: }
                   5539: 
                   5540: sub str2array {
1.265     albertel 5541:     my ($string)=@_;
                   5542:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5543:     return @$array;
                   5544: }
                   5545: 
                   5546: sub str2arrayref {
1.204     albertel 5547:   my ($string) = @_;
1.265     albertel 5548:   my @array;
                   5549: 
                   5550:   if($string !~ /^__ARRAY_REF__/) {
                   5551:       if (! ($string eq '' || !defined($string))) {
                   5552: 	  $array[0]='Array reference error';
                   5553:       }
                   5554:       return (\@array, $string);
                   5555:   }
                   5556: 
                   5557:   $string =~ s/^__ARRAY_REF__//;
                   5558: 
                   5559:   while($string !~ /^__END_ARRAY_REF__/) {
                   5560:       my $value='';
                   5561:       if($string =~ /^__HASH_REF__/) {
                   5562:           ($value, $string)=&str2hashref($string);
                   5563:           if(defined($value->{'error'})) {
                   5564:               $array[0] ='Array reference error';
                   5565:               return (\@array, $string);
                   5566:           }
                   5567:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5568:           ($value, $string)=&str2arrayref($string);
                   5569:           if($value->[0] eq 'Array reference error') {
                   5570:               $array[0] ='Array reference error';
                   5571:               return (\@array, $string);
                   5572:           }
                   5573:       } else {
                   5574: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5575:       }
                   5576:       $string =~ s/^&//;
                   5577: 
                   5578:       push(@array, $value);
1.191     harris41 5579:   }
1.265     albertel 5580: 
                   5581:   $string =~ s/^__END_ARRAY_REF__//;
                   5582: 
                   5583:   return (\@array, $string);
1.168     albertel 5584: }
                   5585: 
1.167     albertel 5586: # -------------------------------------------------------------------Temp Store
                   5587: 
1.168     albertel 5588: sub tmpreset {
                   5589:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5590:   if (!$symb) {
                   5591:     $symb=&symbread();
1.620     albertel 5592:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5593:   }
                   5594:   $symb=escape($symb);
                   5595: 
1.620     albertel 5596:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5597:   $namespace=~s/\//\_/g;
                   5598:   $namespace=~s/\W//g;
                   5599: 
1.620     albertel 5600:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5601:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5602:   if ($domain eq 'public' && $stuname eq 'public') {
                   5603:       $stuname=$ENV{'REMOTE_ADDR'};
                   5604:   }
1.1117    foxr     5605:   my $path=LONCAPA::tempdir();
1.168     albertel 5606:   my %hash;
                   5607:   if (tie(%hash,'GDBM_File',
                   5608: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5609: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5610:     foreach my $key (keys(%hash)) {
1.180     albertel 5611:       if ($key=~ /:$symb/) {
1.168     albertel 5612: 	delete($hash{$key});
                   5613:       }
                   5614:     }
                   5615:   }
                   5616: }
                   5617: 
1.167     albertel 5618: sub tmpstore {
1.168     albertel 5619:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5620: 
                   5621:   if (!$symb) {
                   5622:     $symb=&symbread();
1.620     albertel 5623:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5624:   }
                   5625:   $symb=escape($symb);
                   5626: 
                   5627:   if (!$namespace) {
                   5628:     # I don't think we would ever want to store this for a course.
                   5629:     # it seems this will only be used if we don't have a course.
1.620     albertel 5630:     #$namespace=$env{'request.course.id'};
1.168     albertel 5631:     #if (!$namespace) {
1.620     albertel 5632:       $namespace=$env{'request.state'};
1.168     albertel 5633:     #}
                   5634:   }
                   5635:   $namespace=~s/\//\_/g;
                   5636:   $namespace=~s/\W//g;
1.620     albertel 5637:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5638:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5639:   if ($domain eq 'public' && $stuname eq 'public') {
                   5640:       $stuname=$ENV{'REMOTE_ADDR'};
                   5641:   }
1.168     albertel 5642:   my $now=time;
                   5643:   my %hash;
1.1117    foxr     5644:   my $path=LONCAPA::tempdir();
1.168     albertel 5645:   if (tie(%hash,'GDBM_File',
                   5646: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5647: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5648:     $hash{"version:$symb"}++;
                   5649:     my $version=$hash{"version:$symb"};
                   5650:     my $allkeys=''; 
                   5651:     foreach my $key (keys(%$storehash)) {
                   5652:       $allkeys.=$key.':';
1.591     albertel 5653:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5654:     }
                   5655:     $hash{"$version:$symb:timestamp"}=$now;
                   5656:     $allkeys.='timestamp';
                   5657:     $hash{"$version:keys:$symb"}=$allkeys;
                   5658:     if (untie(%hash)) {
                   5659:       return 'ok';
                   5660:     } else {
                   5661:       return "error:$!";
                   5662:     }
                   5663:   } else {
                   5664:     return "error:$!";
                   5665:   }
                   5666: }
1.167     albertel 5667: 
1.168     albertel 5668: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5669: 
1.168     albertel 5670: sub tmprestore {
                   5671:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5672: 
1.168     albertel 5673:   if (!$symb) {
                   5674:     $symb=&symbread();
1.620     albertel 5675:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5676:   }
                   5677:   $symb=escape($symb);
                   5678: 
1.620     albertel 5679:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5680: 
1.620     albertel 5681:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5682:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5683:   if ($domain eq 'public' && $stuname eq 'public') {
                   5684:       $stuname=$ENV{'REMOTE_ADDR'};
                   5685:   }
1.168     albertel 5686:   my %returnhash;
                   5687:   $namespace=~s/\//\_/g;
                   5688:   $namespace=~s/\W//g;
                   5689:   my %hash;
1.1117    foxr     5690:   my $path=LONCAPA::tempdir();
1.168     albertel 5691:   if (tie(%hash,'GDBM_File',
                   5692: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5693: 	  &GDBM_READER(),0640)) {
1.168     albertel 5694:     my $version=$hash{"version:$symb"};
                   5695:     $returnhash{'version'}=$version;
                   5696:     my $scope;
                   5697:     for ($scope=1;$scope<=$version;$scope++) {
                   5698:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5699:       my @keys=split(/:/,$vkeys);
                   5700:       my $key;
                   5701:       $returnhash{"$scope:keys"}=$vkeys;
                   5702:       foreach $key (@keys) {
1.591     albertel 5703: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5704: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5705:       }
                   5706:     }
1.168     albertel 5707:     if (!(untie(%hash))) {
                   5708:       return "error:$!";
                   5709:     }
                   5710:   } else {
                   5711:     return "error:$!";
                   5712:   }
                   5713:   return %returnhash;
1.167     albertel 5714: }
                   5715: 
1.9       www      5716: # ----------------------------------------------------------------------- Store
                   5717: 
                   5718: sub store {
1.1269    raeburn  5719:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5720:     my $home='';
                   5721: 
1.168     albertel 5722:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5723: 
1.213     www      5724:     $symb=&symbclean($symb);
1.122     albertel 5725:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5726: 
1.620     albertel 5727:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5728:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5729: 
                   5730:     &devalidate($symb,$stuname,$domain);
1.109     www      5731: 
                   5732:     $symb=escape($symb);
1.187     www      5733:     if (!$namespace) { 
1.620     albertel 5734:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5735:           return ''; 
                   5736:        } 
                   5737:     }
1.620     albertel 5738:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5739: 
                   5740:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5741:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5742: 
1.12      www      5743:     my $namevalue='';
1.800     albertel 5744:     foreach my $key (keys(%$storehash)) {
                   5745:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5746:     }
1.12      www      5747:     $namevalue=~s/\&$//;
1.187     www      5748:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5749:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5750: }
                   5751: 
1.47      www      5752: # -------------------------------------------------------------- Critical Store
                   5753: 
                   5754: sub cstore {
1.1269    raeburn  5755:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5756:     my $home='';
                   5757: 
1.168     albertel 5758:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5759: 
1.213     www      5760:     $symb=&symbclean($symb);
1.122     albertel 5761:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5762: 
1.620     albertel 5763:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5764:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5765: 
                   5766:     &devalidate($symb,$stuname,$domain);
1.109     www      5767: 
                   5768:     $symb=escape($symb);
1.187     www      5769:     if (!$namespace) { 
1.620     albertel 5770:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5771:           return ''; 
                   5772:        } 
                   5773:     }
1.620     albertel 5774:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5775: 
                   5776:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5777:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5778: 
1.47      www      5779:     my $namevalue='';
1.800     albertel 5780:     foreach my $key (keys(%$storehash)) {
                   5781:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5782:     }
1.47      www      5783:     $namevalue=~s/\&$//;
1.187     www      5784:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5785:     return critical
1.1269    raeburn  5786:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5787: }
                   5788: 
1.9       www      5789: # --------------------------------------------------------------------- Restore
                   5790: 
                   5791: sub restore {
1.124     www      5792:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5793:     my $home='';
                   5794: 
1.168     albertel 5795:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5796: 
1.122     albertel 5797:     if (!$symb) {
1.1224    raeburn  5798:         return if ($namespace eq 'courserequests');
                   5799:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5800:     } else {
1.1224    raeburn  5801:         unless ($namespace eq 'courserequests') {
                   5802:             $symb=&escape(&symbclean($symb));
                   5803:         }
1.122     albertel 5804:     }
1.188     www      5805:     if (!$namespace) { 
1.620     albertel 5806:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5807:           return ''; 
                   5808:        } 
                   5809:     }
1.620     albertel 5810:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5811:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5812:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5813:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5814: 
1.12      www      5815:     my %returnhash=();
1.800     albertel 5816:     foreach my $line (split(/\&/,$answer)) {
                   5817: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5818:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5819:     }
1.75      www      5820:     my $version;
                   5821:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5822:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5823:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5824:        }
1.75      www      5825:     }
1.13      www      5826:     return %returnhash;
1.34      www      5827: }
                   5828: 
                   5829: # ---------------------------------------------------------- Course Description
1.1118    foxr     5830: #
                   5831: #  
1.34      www      5832: 
                   5833: sub coursedescription {
1.731     albertel 5834:     my ($courseid,$args)=@_;
1.34      www      5835:     $courseid=~s/^\///;
1.49      www      5836:     $courseid=~s/\_/\//g;
1.34      www      5837:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5838:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5839:     my $normalid=$cdomain.'_'.$cnum;
                   5840:     # need to always cache even if we get errors otherwise we keep 
                   5841:     # trying and trying and trying to get the course description.
                   5842:     my %envhash=();
                   5843:     my %returnhash=();
1.731     albertel 5844:     
                   5845:     my $expiretime=600;
                   5846:     if ($env{'request.course.id'} eq $normalid) {
                   5847: 	$expiretime=120;
                   5848:     }
                   5849: 
                   5850:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5851:     if (!$args->{'freshen_cache'}
                   5852: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5853: 	foreach my $key (keys(%env)) {
                   5854: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5855: 	    my ($setting) = $1;
                   5856: 	    $returnhash{$setting} = $env{$key};
                   5857: 	}
                   5858: 	return %returnhash;
                   5859:     }
                   5860: 
1.1118    foxr     5861:     # get the data again
                   5862: 
1.731     albertel 5863:     if (!$args->{'one_time'}) {
                   5864: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5865:     }
1.811     albertel 5866: 
1.34      www      5867:     if ($chome ne 'no_host') {
1.302     albertel 5868:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5869:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5870: 	   my $username = $env{'user.name'}; # Defult username
                   5871: 	   if(defined $args->{'user'}) {
                   5872: 	       $username = $args->{'user'};
                   5873: 	   }
1.129     albertel 5874:            $returnhash{'home'}= $chome;
                   5875: 	   $returnhash{'domain'} = $cdomain;
                   5876: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5877:            if (!defined($returnhash{'type'})) {
                   5878:                $returnhash{'type'} = 'Course';
                   5879:            }
1.130     albertel 5880:            while (my ($name,$value) = each %returnhash) {
1.53      www      5881:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5882:            }
1.270     www      5883:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5884:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5885: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5886:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5887:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5888:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5889:        }
                   5890:     }
1.731     albertel 5891:     if (!$args->{'one_time'}) {
1.949     raeburn  5892: 	&appenv(\%envhash);
1.731     albertel 5893:     }
1.302     albertel 5894:     return %returnhash;
1.461     www      5895: }
                   5896: 
1.1080    raeburn  5897: sub update_released_required {
                   5898:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5899:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5900:         $cid = $env{'request.course.id'};
                   5901:         $cdom = $env{'course.'.$cid.'.domain'};
                   5902:         $cnum = $env{'course.'.$cid.'.num'};
                   5903:         $chome = $env{'course.'.$cid.'.home'};
                   5904:     }
                   5905:     if ($needsrelease) {
                   5906:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5907:         my $needsupdate;
                   5908:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5909:             $needsupdate = 1;
                   5910:         } else {
                   5911:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5912:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5913:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5914:                 $needsupdate = 1;
                   5915:             }
                   5916:         }
                   5917:         if ($needsupdate) {
                   5918:             my %needshash = (
                   5919:                              'internal.releaserequired' => $needsrelease,
                   5920:                             );
                   5921:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5922:             if ($putresult eq 'ok') {
                   5923:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5924:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5925:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5926:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5927:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5928:                 }
                   5929:             }
                   5930:         }
                   5931:     }
                   5932:     return;
                   5933: }
                   5934: 
1.461     www      5935: # -------------------------------------------------See if a user is privileged
                   5936: 
                   5937: sub privileged {
1.1219    raeburn  5938:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5939:     my $now = time;
1.1219    raeburn  5940:     my $roles;
                   5941:     if (ref($possroles) eq 'ARRAY') {
                   5942:         $roles = $possroles; 
                   5943:     } else {
                   5944:         $roles = ['dc','su'];
                   5945:     }
                   5946:     if (ref($possdomains) eq 'ARRAY') {
                   5947:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5948:         foreach my $dom (@{$possdomains}) {
                   5949:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5950:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5951:                 foreach my $role (@{$roles}) {
                   5952:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5953:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5954:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5955:                             return 1 unless (($end && $end < $now) ||
                   5956:                                              ($start && $start > $now));
                   5957:                         }
                   5958:                     }
                   5959:                 }
                   5960:             }
                   5961:         }
                   5962:     } else {
                   5963:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5964:         my $now = time;
1.1170    droeschl 5965: 
1.1275    musolffc 5966:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5967:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5968:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5969:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5970:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5971:             }
1.1219    raeburn  5972:         }
                   5973:     }
                   5974:     return 0;
                   5975: }
1.1170    droeschl 5976: 
1.1219    raeburn  5977: sub privileged_by_domain {
                   5978:     my ($domains,$roles) = @_;
                   5979:     my %privileged = ();
                   5980:     my $cachetime = 60*60*24;
                   5981:     my $now = time;
                   5982:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5983:         return %privileged;
                   5984:     }
                   5985:     foreach my $dom (@{$domains}) {
                   5986:         next if (ref($privileged{$dom}) eq 'HASH');
                   5987:         my $needroles;
                   5988:         foreach my $role (@{$roles}) {
                   5989:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5990:             if (defined($cached)) {
                   5991:                 if (ref($result) eq 'HASH') {
                   5992:                     $privileged{$dom}{$role} = $result;
                   5993:                 }
                   5994:             } else {
                   5995:                 $needroles = 1;
                   5996:             }
                   5997:         }
                   5998:         if ($needroles) {
                   5999:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6000:             $privileged{$dom} = {};
                   6001:             foreach my $server (keys(%dompersonnel)) {
                   6002:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6003:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6004:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6005:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6006:                         next if ($end && $end < $now);
                   6007:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6008:                             $dompersonnel{$server}{$item};
                   6009:                     }
                   6010:                 }
                   6011:             }
                   6012:             if (ref($privileged{$dom}) eq 'HASH') {
                   6013:                 foreach my $role (@{$roles}) {
                   6014:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6015:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6016:                     } else {
                   6017:                         my %hash = ();
                   6018:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6019:                     }
                   6020:                 }
                   6021:             }
                   6022:         }
                   6023:     }
                   6024:     return %privileged;
1.9       www      6025: }
1.1       albertel 6026: 
1.103     harris41 6027: # -------------------------------------------------------- Get user privileges
1.11      www      6028: 
                   6029: sub rolesinit {
1.1169    droeschl 6030:     my ($domain, $username) = @_;
                   6031:     my %userroles = ('user.login.time' => time);
                   6032:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6033: 
                   6034:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6035:     # also, blocking can be triggered by an activating timer
                   6036:     # it's saved in the user's %env.
                   6037:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6038:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6039:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6040:         %timerintchk, %timerintenv);
                   6041: 
1.1162    raeburn  6042:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6043:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6044:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6045:     }
1.1169    droeschl 6046: 
1.1162    raeburn  6047:     foreach my $key (keys(%timerinterval)) {
                   6048:         my ($cid,$rest) = split(/\0/,$key);
                   6049:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6050:     }
1.1169    droeschl 6051: 
1.11      www      6052:     my %allroles=();
1.1162    raeburn  6053:     my %allgroups=();
1.11      www      6054: 
1.1274    raeburn  6055:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6056:         my $role = $rolesdump{$area};
                   6057:         $area =~ s/\_\w\w$//;
                   6058: 
                   6059:         my ($trole, $tend, $tstart, $group_privs);
                   6060: 
                   6061:         if ($role =~ /^cr/) {
                   6062:         # Custom role, defined by a user 
                   6063:         # e.g., user.role.cr/msu/smith/mynewrole
                   6064:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6065:                 $trole = $1;
                   6066:                 ($tend, $tstart) = split('_', $2);
                   6067:             } else {
                   6068:                 $trole = $role;
                   6069:             }
                   6070:         } elsif ($role =~ m|^gr/|) {
                   6071:         # Role of member in a group, defined within a course/community
                   6072:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6073:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6074:             next if $tstart eq '-1';
                   6075:             ($trole, $group_privs) = split(/\//, $trole);
                   6076:             $group_privs = &unescape($group_privs);
                   6077:         } else {
                   6078:         # Just a normal role, defined in roles.tab
                   6079:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6080:         }
                   6081: 
                   6082:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6083:                  $username);
                   6084:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6085: 
                   6086:         # role expired or not available yet?
                   6087:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6088:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6089: 
                   6090:         next if $area eq '' or $trole eq '';
                   6091: 
                   6092:         my $spec = "$trole.$area";
                   6093:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6094: 
                   6095:         if ($trole =~ /^cr\//) {
                   6096:         # Custom role, defined by a user
                   6097:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6098:         } elsif ($trole eq 'gr') {
                   6099:         # Role of a member in a group, defined within a course/community
                   6100:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6101:             next;
                   6102:         } else {
                   6103:         # Normal role, defined in roles.tab
                   6104:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6105:         }
                   6106: 
                   6107:         my $cid = $tdomain.'_'.$trest;
                   6108:         unless ($firstaccchk{$cid}) {
                   6109:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6110:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6111:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6112:                         $coursetimerstarts{$cid}{$item}; 
                   6113:                 }
                   6114:             }
                   6115:             $firstaccchk{$cid} = 1;
                   6116:         }
                   6117:         unless ($timerintchk{$cid}) {
                   6118:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6119:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6120:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6121:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6122:                 }
1.12      www      6123:             }
1.1169    droeschl 6124:             $timerintchk{$cid} = 1;
1.191     harris41 6125:         }
1.11      www      6126:     }
1.1169    droeschl 6127: 
1.1341    raeburn  6128:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6129:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6130:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6131:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6132: 
1.1162    raeburn  6133:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6134: }
                   6135: 
1.567     raeburn  6136: sub set_arearole {
1.1215    raeburn  6137:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6138:     unless ($nolog) {
1.567     raeburn  6139: # log the associated role with the area
1.1215    raeburn  6140:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6141:     }
1.743     albertel 6142:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6143: }
                   6144: 
                   6145: sub custom_roleprivs {
                   6146:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6147:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6148:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6149:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6150:         my ($rdummy,$roledef)=
                   6151:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6152:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6153:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6154:             if (defined($syspriv)) {
1.1043    raeburn  6155:                 if ($trest =~ /^$match_community$/) {
                   6156:                     $syspriv =~ s/bre\&S//; 
                   6157:                 }
1.567     raeburn  6158:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6159:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6160:             }
                   6161:             if ($tdomain ne '') {
                   6162:                 if (defined($dompriv)) {
                   6163:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6164:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6165:                 }
                   6166:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6167:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6168:                         my $rolename = $1;
                   6169:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6170:                     }
1.567     raeburn  6171:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6172:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6173:                 }
                   6174:             }
                   6175:         }
                   6176:     }
                   6177: }
                   6178: 
1.1332    raeburn  6179: sub course_adhocrole_privs {
                   6180:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6181:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6182:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6183:         my (%currprivs,%storeprivs);
                   6184:         foreach my $item (split(/:/,$coursepriv)) {
                   6185:             my ($priv,$restrict) = split(/\&/,$item);
                   6186:             $currprivs{$priv} = $restrict;
                   6187:         }
                   6188:         my (%possadd,%possremove,%full);
                   6189:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6190:             my ($priv,$restrict)=split(/\&/,$item);
                   6191:             $full{$priv} = $restrict;
                   6192:         }
                   6193:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6194:              next if ($item eq '');
                   6195:              my ($rule,$rest) = split(/=/,$item);
                   6196:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6197:              foreach my $priv (split(/:/,$rest)) {
                   6198:                  if ($priv ne '') {
                   6199:                      if ($rule eq 'off') {
                   6200:                          $possremove{$priv} = 1;
                   6201:                      } else {
                   6202:                          $possadd{$priv} = 1;
                   6203:                      }
                   6204:                  }
                   6205:              }
                   6206:          }
                   6207:          foreach my $priv (sort(keys(%full))) {
                   6208:              if (exists($currprivs{$priv})) {
                   6209:                  unless (exists($possremove{$priv})) {
                   6210:                      $storeprivs{$priv} = $currprivs{$priv};
                   6211:                  }
                   6212:              } elsif (exists($possadd{$priv})) {
                   6213:                  $storeprivs{$priv} = $full{$priv};
                   6214:              }
                   6215:          }
                   6216:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6217:      }
                   6218:      return $coursepriv;
                   6219: }
                   6220: 
1.678     raeburn  6221: sub group_roleprivs {
                   6222:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6223:     my $access = 1;
                   6224:     my $now = time;
                   6225:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6226:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6227:     if ($access) {
1.811     albertel 6228:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6229:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6230:     }
                   6231: }
1.567     raeburn  6232: 
                   6233: sub standard_roleprivs {
                   6234:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6235:     if (defined($pr{$trole.':s'})) {
                   6236:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6237:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6238:     }
                   6239:     if ($tdomain ne '') {
                   6240:         if (defined($pr{$trole.':d'})) {
                   6241:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6242:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6243:         }
                   6244:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6245:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6246:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6247:         }
                   6248:     }
                   6249: }
                   6250: 
                   6251: sub set_userprivs {
1.1064    raeburn  6252:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6253:     my $author=0;
                   6254:     my $adv=0;
1.1341    raeburn  6255:     my $rar=0;
1.678     raeburn  6256:     my %grouproles = ();
                   6257:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6258:         my @groupkeys; 
1.1000    raeburn  6259:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6260:             push(@groupkeys,$role);
                   6261:         }
                   6262:         if (ref($groups_roles) eq 'HASH') {
                   6263:             foreach my $key (keys(%{$groups_roles})) {
                   6264:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6265:                     push(@groupkeys,$key);
                   6266:                 }
                   6267:             }
                   6268:         }
                   6269:         if (@groupkeys > 0) {
                   6270:             foreach my $role (@groupkeys) {
                   6271:                 my ($trole,$area,$sec,$extendedarea);
                   6272:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6273:                     $trole = $1;
                   6274:                     $area = $2;
                   6275:                     $sec = $3;
                   6276:                     $extendedarea = $area.$sec;
                   6277:                     if (exists($$allgroups{$area})) {
                   6278:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6279:                             my $spec = $trole.'.'.$extendedarea;
                   6280:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6281:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6282:                         }
1.678     raeburn  6283:                     }
                   6284:                 }
                   6285:             }
                   6286:         }
                   6287:     }
1.800     albertel 6288:     foreach my $group (keys(%grouproles)) {
                   6289:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6290:     }
1.800     albertel 6291:     foreach my $role (keys(%{$allroles})) {
                   6292:         my %thesepriv;
1.941     raeburn  6293:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6294:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6295:             if ($item ne '') {
                   6296:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6297:                 if ($restrictions eq '') {
                   6298:                     $thesepriv{$privilege}='F';
                   6299:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6300:                     $thesepriv{$privilege}.=$restrictions;
                   6301:                 }
                   6302:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6303:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6304:             }
                   6305:         }
                   6306:         my $thesestr='';
1.1104    raeburn  6307:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6308: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6309: 	}
                   6310:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6311:     }
1.1341    raeburn  6312:     return ($author,$adv,$rar);
1.567     raeburn  6313: }
                   6314: 
1.994     raeburn  6315: sub role_status {
1.1104    raeburn  6316:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6317:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6318:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6319:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6320:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6321:             $$where = '/'.$two;
1.994     raeburn  6322:             $$trolecode=$$role.'.'.$$where;
                   6323:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6324:             $$tstatus='is';
1.1104    raeburn  6325:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6326:                 $$tstatus='future';
1.1034    raeburn  6327:                 if ($$tstart<$now) {
                   6328:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6329:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6330:                             my (%allroles,%allgroups,$group_privs,
                   6331:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6332:                             my %userroles = (
                   6333:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6334:                             );
1.1064    raeburn  6335:                             @rolecodes = ('cm'); 
1.1002    raeburn  6336:                             my $spec=$$role.'.'.$$where;
                   6337:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6338:                             if ($$role =~ /^cr\//) {
                   6339:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6340:                                 push(@rolecodes,'cr');
1.1002    raeburn  6341:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6342:                                 push(@rolecodes,$$role);
1.1002    raeburn  6343:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6344:                                                     $env{'user.name'});
1.1064    raeburn  6345:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6346:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6347:                                 $group_privs = &unescape($group_privs);
                   6348:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6349:                                 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  6350:                                 &get_groups_roles($tdomain,$trest,
                   6351:                                                   \%course_roles,\@rolecodes,
                   6352:                                                   \%groups_roles);
1.1002    raeburn  6353:                             } else {
1.1064    raeburn  6354:                                 push(@rolecodes,$$role);
1.1002    raeburn  6355:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6356:                             }
1.1341    raeburn  6357:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6358:                                                                    \%groups_roles);
1.1064    raeburn  6359:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6360:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6361:                         }
                   6362:                     }
1.1034    raeburn  6363:                     $$tstatus = 'is';
1.1002    raeburn  6364:                 }
1.994     raeburn  6365:             }
                   6366:             if ($$tend) {
1.1104    raeburn  6367:                 if ($$tend<$update) {
1.994     raeburn  6368:                     $$tstatus='expired';
                   6369:                 } elsif ($$tend<$now) {
                   6370:                     $$tstatus='will_not';
                   6371:                 }
                   6372:             }
                   6373:         }
                   6374:     }
                   6375: }
                   6376: 
1.1104    raeburn  6377: sub get_groups_roles {
                   6378:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6379:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6380:                   (ref($rolecodes) eq 'ARRAY') && 
                   6381:                   (ref($groups_roles) eq 'HASH')); 
                   6382:     if (keys(%{$cdom_courseroles}) > 0) {
                   6383:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6384:         if ($cdom ne '' && $cnum ne '') {
                   6385:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6386:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6387:                     my $crsrole = $1;
                   6388:                     my $crssec = $2;
                   6389:                     if ($crsrole =~ /^cr/) {
                   6390:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6391:                             push(@{$rolecodes},'cr');
                   6392:                         }
                   6393:                     } else {
                   6394:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6395:                             push(@{$rolecodes},$crsrole);
                   6396:                         }
                   6397:                     }
                   6398:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6399:                     if ($crssec ne '') {
                   6400:                         $rolekey .= "/$crssec";
                   6401:                     }
                   6402:                     $rolekey .= './';
                   6403:                     $groups_roles->{$rolekey} = $rolecodes;
                   6404:                 }
                   6405:             }
                   6406:         }
                   6407:     }
                   6408:     return;
                   6409: }
                   6410: 
                   6411: sub delete_env_groupprivs {
                   6412:     my ($where,$courseroles,$possroles) = @_;
                   6413:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6414:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6415:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6416:         %{$courseroles->{$udom}} =
                   6417:             &get_my_roles('','','userroles',['active'],
                   6418:                           $possroles,[$udom],1);
                   6419:     }
                   6420:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6421:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6422:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6423:             my $area = '/'.$cdom.'/'.$cnum;
                   6424:             my $privkey = "user.priv.$crsrole.$area";
                   6425:             if ($crssec ne '') {
                   6426:                 $privkey .= '/'.$crssec;
                   6427:             }
                   6428:             $privkey .= ".$area/$group";
                   6429:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6430:         }
                   6431:     }
                   6432:     return;
                   6433: }
                   6434: 
1.994     raeburn  6435: sub check_adhoc_privs {
1.1329    raeburn  6436:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6437:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6438:     if ($sec) {
                   6439:         $cckey .= '/'.$sec;
                   6440:     } 
1.1185    raeburn  6441:     my $setprivs;
1.994     raeburn  6442:     if ($env{$cckey}) {
                   6443:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6444:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6445:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6446:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6447:             $setprivs = 1;
1.994     raeburn  6448:         }
                   6449:     } else {
1.1330    raeburn  6450:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6451:         $setprivs = 1;
1.994     raeburn  6452:     }
1.1185    raeburn  6453:     return $setprivs;
1.994     raeburn  6454: }
                   6455: 
                   6456: sub set_adhoc_privileges {
1.1326    raeburn  6457: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6458:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6459:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6460:     if ($sec ne '') {
                   6461:         $area .= '/'.$sec;
                   6462:     }
1.994     raeburn  6463:     my $spec = $role.'.'.$area;
                   6464:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6465:                                   $env{'user.name'},1);
1.1326    raeburn  6466:     my %rolehash = ();
1.1332    raeburn  6467:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6468:         my $rolename = $1;
1.1326    raeburn  6469:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6470:         my %domdef = &get_domain_defaults($dcdom);
                   6471:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6472:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6473:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6474:             }
                   6475:         }
1.1326    raeburn  6476:     } else {
                   6477:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6478:     }
1.1341    raeburn  6479:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6480:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6481:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6482:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6483:         &appenv( {'request.role'        => $spec,
                   6484:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6485:                   'request.course.sec'  => $sec,
1.1088    raeburn  6486:                  }
                   6487:                );
                   6488:         my $tadv=0;
                   6489:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6490:         &appenv({'request.role.adv'    => $tadv});
                   6491:     }
1.994     raeburn  6492: }
                   6493: 
1.12      www      6494: # --------------------------------------------------------------- get interface
                   6495: 
                   6496: sub get {
1.131     albertel 6497:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6498:    my $items='';
1.800     albertel 6499:    foreach my $item (@$storearr) {
                   6500:        $items.=&escape($item).'&';
1.191     harris41 6501:    }
1.12      www      6502:    $items=~s/\&$//;
1.620     albertel 6503:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6504:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6505:    my $uhome=&homeserver($uname,$udomain);
                   6506: 
1.133     albertel 6507:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6508:    my @pairs=split(/\&/,$rep);
1.273     albertel 6509:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6510:      return @pairs;
                   6511:    }
1.15      www      6512:    my %returnhash=();
1.42      www      6513:    my $i=0;
1.800     albertel 6514:    foreach my $item (@$storearr) {
                   6515:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6516:       $i++;
1.191     harris41 6517:    }
1.15      www      6518:    return %returnhash;
1.27      www      6519: }
                   6520: 
                   6521: # --------------------------------------------------------------- del interface
                   6522: 
                   6523: sub del {
1.133     albertel 6524:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6525:    my $items='';
1.800     albertel 6526:    foreach my $item (@$storearr) {
                   6527:        $items.=&escape($item).'&';
1.191     harris41 6528:    }
1.984     neumanie 6529: 
1.27      www      6530:    $items=~s/\&$//;
1.620     albertel 6531:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6532:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6533:    my $uhome=&homeserver($uname,$udomain);
                   6534:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6535: }
                   6536: 
                   6537: # -------------------------------------------------------------- dump interface
                   6538: 
1.1180    droeschl 6539: sub unserialize {
                   6540:     my ($rep, $escapedkeys) = @_;
                   6541: 
                   6542:     return {} if $rep =~ /^error/;
                   6543: 
                   6544:     my %returnhash=();
1.1252    raeburn  6545: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6546: 	    my ($key, $value) = split(/=/, $item, 2);
                   6547: 	    $key = unescape($key) unless $escapedkeys;
                   6548: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6549: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6550: 	}
                   6551:     #return %returnhash;
                   6552:     return \%returnhash;
                   6553: }        
                   6554: 
                   6555: # see Lond::dump_with_regexp
                   6556: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6557: sub dump {
1.1180    droeschl 6558:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6559:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6560:     if (!$uname) { $uname=$env{'user.name'}; }
                   6561:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6562: 
1.1266    raeburn  6563:     if ($regexp) {
                   6564:         $regexp=&escape($regexp);
                   6565:     } else {
                   6566:         $regexp='.';
                   6567:     }
1.1180    droeschl 6568:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6569:         # user is hosted on this machine
1.1266    raeburn  6570:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6571:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6572:         return %{unserialize($reply, $escapedkeys)};
                   6573:     }
1.1166    raeburn  6574:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6575:     my @pairs=split(/\&/,$rep);
                   6576:     my %returnhash=();
1.1098    foxr     6577:     if (!($rep =~ /^error/ )) {
                   6578: 	foreach my $item (@pairs) {
                   6579: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6580:         $key = unescape($key) unless $escapedkeys;
                   6581:         #$key = &unescape($key);
1.1098    foxr     6582: 	    next if ($key =~ /^error: 2 /);
                   6583: 	    $returnhash{$key}=&thaw_unescape($value);
                   6584: 	}
1.755     albertel 6585:     }
                   6586:     return %returnhash;
1.407     www      6587: }
                   6588: 
1.1098    foxr     6589: 
1.717     albertel 6590: # --------------------------------------------------------- dumpstore interface
                   6591: 
                   6592: sub dumpstore {
                   6593:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6594:    # same as dump but keys must be escaped. They may contain colon separated
                   6595:    # lists of values that may themself contain colons (e.g. symbs).
                   6596:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6597: }
                   6598: 
1.407     www      6599: # -------------------------------------------------------------- keys interface
                   6600: 
                   6601: sub getkeys {
                   6602:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6603:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6604:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6605:    my $uhome=&homeserver($uname,$udomain);
                   6606:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6607:    my @keyarray=();
1.800     albertel 6608:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6609:       next if ($key =~ /^error: 2 /);
1.800     albertel 6610:       push(@keyarray,&unescape($key));
1.407     www      6611:    }
                   6612:    return @keyarray;
1.318     matthew  6613: }
                   6614: 
1.319     matthew  6615: # --------------------------------------------------------------- currentdump
                   6616: sub currentdump {
1.328     matthew  6617:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6618:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6619:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6620:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6621:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6622:    my $rep;
                   6623: 
                   6624:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6625:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6626:                    $courseid)));
                   6627:    } else {
                   6628:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6629:    }
                   6630: 
1.318     matthew  6631:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6632:    #
1.318     matthew  6633:    my %returnhash=();
1.319     matthew  6634:    #
1.1343    raeburn  6635:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6636:        # an old lond will not know currentdump
                   6637:        # Do a dump and make it look like a currentdump
1.822     albertel 6638:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6639:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6640:        my %hash = @tmp;
                   6641:        @tmp=();
1.424     matthew  6642:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6643:    } else {
                   6644:        my @pairs=split(/\&/,$rep);
1.800     albertel 6645:        foreach my $pair (@pairs) {
                   6646:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6647:            my ($symb,$param) = split(/:/,$key);
                   6648:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6649:                                                         &thaw_unescape($value);
1.319     matthew  6650:        }
1.191     harris41 6651:    }
1.12      www      6652:    return %returnhash;
1.424     matthew  6653: }
                   6654: 
                   6655: sub convert_dump_to_currentdump{
                   6656:     my %hash = %{shift()};
                   6657:     my %returnhash;
                   6658:     # Code ripped from lond, essentially.  The only difference
                   6659:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6660:     # we might run in to problems with parameter names =~ /^v\./
                   6661:     while (my ($key,$value) = each(%hash)) {
                   6662:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6663: 	$symb  = &unescape($symb);
                   6664: 	$param = &unescape($param);
1.424     matthew  6665:         next if ($v eq 'version' || $symb eq 'keys');
                   6666:         next if (exists($returnhash{$symb}) &&
                   6667:                  exists($returnhash{$symb}->{$param}) &&
                   6668:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6669:         $returnhash{$symb}->{$param}=$value;
                   6670:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6671:     }
                   6672:     #
                   6673:     # Remove all of the keys in the hashes which keep track of
                   6674:     # the version of the parameter.
                   6675:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6676:         # use a foreach because we are going to delete from the hash.
                   6677:         foreach my $key (keys(%$param_hash)) {
                   6678:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6679:         }
                   6680:     }
                   6681:     return \%returnhash;
1.12      www      6682: }
                   6683: 
1.627     albertel 6684: # ------------------------------------------------------ critical inc interface
                   6685: 
                   6686: sub cinc {
                   6687:     return &inc(@_,'critical');
                   6688: }
                   6689: 
1.449     matthew  6690: # --------------------------------------------------------------- inc interface
                   6691: 
                   6692: sub inc {
1.627     albertel 6693:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6694:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6695:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6696:     my $uhome=&homeserver($uname,$udomain);
                   6697:     my $items='';
                   6698:     if (! ref($store)) {
                   6699:         # got a single value, so use that instead
                   6700:         $items = &escape($store).'=&';
                   6701:     } elsif (ref($store) eq 'SCALAR') {
                   6702:         $items = &escape($$store).'=&';        
                   6703:     } elsif (ref($store) eq 'ARRAY') {
                   6704:         $items = join('=&',map {&escape($_);} @{$store});
                   6705:     } elsif (ref($store) eq 'HASH') {
                   6706:         while (my($key,$value) = each(%{$store})) {
                   6707:             $items.= &escape($key).'='.&escape($value).'&';
                   6708:         }
                   6709:     }
                   6710:     $items=~s/\&$//;
1.627     albertel 6711:     if ($critical) {
                   6712: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6713:     } else {
                   6714: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6715:     }
1.449     matthew  6716: }
                   6717: 
1.12      www      6718: # --------------------------------------------------------------- put interface
                   6719: 
                   6720: sub put {
1.134     albertel 6721:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6722:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6723:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6724:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6725:    my $items='';
1.800     albertel 6726:    foreach my $item (keys(%$storehash)) {
                   6727:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6728:    }
1.12      www      6729:    $items=~s/\&$//;
1.134     albertel 6730:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6731: }
                   6732: 
1.631     albertel 6733: # ------------------------------------------------------------ newput interface
                   6734: 
                   6735: sub newput {
                   6736:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6737:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6738:    if (!$uname) { $uname=$env{'user.name'}; }
                   6739:    my $uhome=&homeserver($uname,$udomain);
                   6740:    my $items='';
                   6741:    foreach my $key (keys(%$storehash)) {
                   6742:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6743:    }
                   6744:    $items=~s/\&$//;
                   6745:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6746: }
                   6747: 
                   6748: # ---------------------------------------------------------  putstore interface
                   6749: 
1.524     raeburn  6750: sub putstore {
1.1269    raeburn  6751:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6752:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6753:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6754:    my $uhome=&homeserver($uname,$udomain);
                   6755:    my $items='';
1.715     albertel 6756:    foreach my $key (keys(%$storehash)) {
                   6757:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6758:    }
1.715     albertel 6759:    $items=~s/\&$//;
1.716     albertel 6760:    my $esc_symb=&escape($symb);
                   6761:    my $esc_v=&escape($version);
1.715     albertel 6762:    my $reply =
1.716     albertel 6763:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6764: 	      $uhome);
1.1269    raeburn  6765:    if (($tolog) && ($reply eq 'ok')) {
                   6766:        my $namevalue='';
                   6767:        foreach my $key (keys(%{$storehash})) {
                   6768:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6769:        }
                   6770:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6771:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6772:                      '&version='.$esc_v.
                   6773:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6774:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6775:    }
1.715     albertel 6776:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6777:        # gfall back to way things use to be done
1.715     albertel 6778:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6779: 			    $uname);
1.524     raeburn  6780:    }
1.715     albertel 6781:    return $reply;
                   6782: }
                   6783: 
                   6784: sub old_putstore {
1.716     albertel 6785:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6786:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6787:     if (!$uname) { $uname=$env{'user.name'}; }
                   6788:     my $uhome=&homeserver($uname,$udomain);
                   6789:     my %newstorehash;
1.800     albertel 6790:     foreach my $item (keys(%$storehash)) {
                   6791: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6792: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6793:     }
                   6794:     my $items='';
                   6795:     my %allitems = ();
1.800     albertel 6796:     foreach my $item (keys(%newstorehash)) {
                   6797: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6798: 	    my $key = $1.':keys:'.$2;
                   6799: 	    $allitems{$key} .= $3.':';
                   6800: 	}
1.800     albertel 6801: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6802:     }
1.800     albertel 6803:     foreach my $item (keys(%allitems)) {
                   6804: 	$allitems{$item} =~ s/\:$//;
                   6805: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6806:     }
                   6807:     $items=~s/\&$//;
                   6808:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6809: }
                   6810: 
1.47      www      6811: # ------------------------------------------------------ critical put interface
                   6812: 
                   6813: sub cput {
1.134     albertel 6814:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6815:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6816:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6817:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6818:    my $items='';
1.800     albertel 6819:    foreach my $item (keys(%$storehash)) {
                   6820:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6821:    }
1.47      www      6822:    $items=~s/\&$//;
1.134     albertel 6823:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6824: }
                   6825: 
                   6826: # -------------------------------------------------------------- eget interface
                   6827: 
                   6828: sub eget {
1.133     albertel 6829:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6830:    my $items='';
1.800     albertel 6831:    foreach my $item (@$storearr) {
                   6832:        $items.=&escape($item).'&';
1.191     harris41 6833:    }
1.12      www      6834:    $items=~s/\&$//;
1.620     albertel 6835:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6836:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6837:    my $uhome=&homeserver($uname,$udomain);
                   6838:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6839:    my @pairs=split(/\&/,$rep);
                   6840:    my %returnhash=();
1.42      www      6841:    my $i=0;
1.800     albertel 6842:    foreach my $item (@$storearr) {
                   6843:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6844:       $i++;
1.191     harris41 6845:    }
1.12      www      6846:    return %returnhash;
                   6847: }
                   6848: 
1.667     albertel 6849: # ------------------------------------------------------------ tmpput interface
                   6850: sub tmpput {
1.802     raeburn  6851:     my ($storehash,$server,$context)=@_;
1.667     albertel 6852:     my $items='';
1.800     albertel 6853:     foreach my $item (keys(%$storehash)) {
                   6854: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6855:     }
                   6856:     $items=~s/\&$//;
1.802     raeburn  6857:     if (defined($context)) {
                   6858:         $items .= ':'.&escape($context);
                   6859:     }
1.667     albertel 6860:     return &reply("tmpput:$items",$server);
                   6861: }
                   6862: 
                   6863: # ------------------------------------------------------------ tmpget interface
                   6864: sub tmpget {
1.688     albertel 6865:     my ($token,$server)=@_;
                   6866:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6867:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6868:     my %returnhash;
1.1328    raeburn  6869:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6870:         return %returnhash;
                   6871:     }
1.667     albertel 6872:     foreach my $item (split(/\&/,$rep)) {
                   6873: 	my ($key,$value)=split(/=/,$item);
                   6874: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6875:     }
                   6876:     return %returnhash;
                   6877: }
                   6878: 
1.1113    raeburn  6879: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6880: sub tmpdel {
                   6881:     my ($token,$server)=@_;
                   6882:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6883:     return &reply("tmpdel:$token",$server);
                   6884: }
                   6885: 
1.1198    raeburn  6886: # ------------------------------------------------------------ get_timebased_id 
                   6887: 
                   6888: sub get_timebased_id {
                   6889:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6890:         $maxtries) = @_;
                   6891:     my ($newid,$error,$dellock);
                   6892:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6893:         return ('','ok','invalid call to get suffix');
                   6894:     }
                   6895: 
                   6896: # set defaults for any optional args for which values were not supplied
                   6897:     if ($who eq '') {
                   6898:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6899:     }
                   6900:     if (!$locktries) {
                   6901:         $locktries = 3;
                   6902:     }
                   6903:     if (!$maxtries) {
                   6904:         $maxtries = 10;
                   6905:     }
                   6906:     
                   6907:     if (($cdom eq '') || ($cnum eq '')) {
                   6908:         if ($env{'request.course.id'}) {
                   6909:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6910:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6911:         }
                   6912:         if (($cdom eq '') || ($cnum eq '')) {
                   6913:             return ('','ok','call to get suffix not in course context');
                   6914:         }
                   6915:     }
                   6916: 
                   6917: # construct locking item
                   6918:     my $lockhash = {
                   6919:                       $prefix."\0".'locked_'.$keyid => $who,
                   6920:                    };
                   6921:     my $tries = 0;
                   6922: 
                   6923: # attempt to get lock on nohist_$namespace file
                   6924:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6925:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6926:         $tries ++;
                   6927:         sleep 1;
                   6928:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6929:     }
                   6930: 
                   6931: # attempt to get unique identifier, based on current timestamp
                   6932:     if ($gotlock eq 'ok') {
                   6933:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6934:         my $id = time;
                   6935:         $newid = $id;
1.1268    raeburn  6936:         if ($idtype eq 'addcode') {
                   6937:             $newid .= &sixnum_code();
                   6938:         }
1.1198    raeburn  6939:         my $idtries = 0;
                   6940:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6941:             if ($idtype eq 'concat') {
                   6942:                 $newid = $id.$idtries;
1.1268    raeburn  6943:             } elsif ($idtype eq 'addcode') {
                   6944:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6945:             } else {
                   6946:                 $newid ++;
                   6947:             }
                   6948:             $idtries ++;
                   6949:         }
                   6950:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6951:             my %new_item =  (
                   6952:                               $prefix."\0".$newid => $who,
                   6953:                             );
                   6954:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6955:                                                  $cdom,$cnum);
                   6956:             if ($putresult ne 'ok') {
                   6957:                 undef($newid);
                   6958:                 $error = 'error saving new item: '.$putresult;
                   6959:             }
                   6960:         } else {
1.1268    raeburn  6961:              undef($newid);
1.1198    raeburn  6962:              $error = ('error: no unique suffix available for the new item ');
                   6963:         }
                   6964: #  remove lock
                   6965:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6966:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6967:     } else {
                   6968:         $error = "error: could not obtain lockfile\n";
                   6969:         $dellock = 'ok';
1.1276    raeburn  6970:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6971:             $dellock = 'nolock';
                   6972:         }
1.1198    raeburn  6973:     }
                   6974:     return ($newid,$dellock,$error);
                   6975: }
                   6976: 
1.1268    raeburn  6977: sub sixnum_code {
                   6978:     my $code;
                   6979:     for (0..6) {
                   6980:         $code .= int( rand(9) );
                   6981:     }
                   6982:     return $code;
                   6983: }
                   6984: 
1.765     albertel 6985: # -------------------------------------------------- portfolio access checking
                   6986: 
                   6987: sub portfolio_access {
1.1270    raeburn  6988:     my ($requrl,$clientip) = @_;
1.765     albertel 6989:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6990:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6991:     if ($result) {
                   6992:         my %setters;
                   6993:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6994:             my ($startblock,$endblock) =
                   6995:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6996:             if ($startblock && $endblock) {
                   6997:                 return 'B';
                   6998:             }
                   6999:         } else {
                   7000:             my ($startblock,$endblock) =
                   7001:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7002:             if ($startblock && $endblock) {
                   7003:                 return 'B';
                   7004:             }
                   7005:         }
                   7006:     }
1.765     albertel 7007:     if ($result eq 'ok') {
1.766     albertel 7008:        return 'F';
1.765     albertel 7009:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7010:        return 'A';
1.765     albertel 7011:     }
1.766     albertel 7012:     return '';
1.765     albertel 7013: }
                   7014: 
                   7015: sub get_portfolio_access {
1.1270    raeburn  7016:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7017: 
                   7018:     if (!ref($access_hash)) {
                   7019: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7020: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7021: 						   $file_name);
                   7022: 	$access_hash = $access_controls{$file_name};
                   7023:     }
                   7024: 
1.1270    raeburn  7025:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7026:     my $now = time;
                   7027:     if (ref($access_hash) eq 'HASH') {
                   7028:         foreach my $key (keys(%{$access_hash})) {
                   7029:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7030:             if ($start > $now) {
                   7031:                 next;
                   7032:             }
                   7033:             if ($end && $end<$now) {
                   7034:                 next;
                   7035:             }
                   7036:             if ($scope eq 'public') {
                   7037:                 $public = $key;
                   7038:                 last;
                   7039:             } elsif ($scope eq 'guest') {
                   7040:                 $guest = $key;
                   7041:             } elsif ($scope eq 'domains') {
                   7042:                 push(@domains,$key);
                   7043:             } elsif ($scope eq 'users') {
                   7044:                 push(@users,$key);
                   7045:             } elsif ($scope eq 'course') {
                   7046:                 push(@courses,$key);
                   7047:             } elsif ($scope eq 'group') {
                   7048:                 push(@groups,$key);
1.1270    raeburn  7049:             } elsif ($scope eq 'ip') {
                   7050:                 push(@ips,$key);
1.765     albertel 7051:             }
                   7052:         }
                   7053:         if ($public) {
                   7054:             return 'ok';
1.1270    raeburn  7055:         } elsif (@ips > 0) {
                   7056:             my $allowed;
                   7057:             foreach my $ipkey (@ips) {
                   7058:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7059:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7060:                         $allowed = 1;
                   7061:                         last; 
                   7062:                     }
                   7063:                 }
                   7064:             }
                   7065:             if ($allowed) {
                   7066:                 return 'ok';
                   7067:             }
1.765     albertel 7068:         }
                   7069:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7070:             if ($guest) {
                   7071:                 return $guest;
                   7072:             }
                   7073:         } else {
                   7074:             if (@domains > 0) {
                   7075:                 foreach my $domkey (@domains) {
                   7076:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7077:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7078:                             return 'ok';
                   7079:                         }
                   7080:                     }
                   7081:                 }
                   7082:             }
                   7083:             if (@users > 0) {
                   7084:                 foreach my $userkey (@users) {
1.865     raeburn  7085:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7086:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7087:                             if (ref($item) eq 'HASH') {
                   7088:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7089:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7090:                                     return 'ok';
                   7091:                                 }
                   7092:                             }
                   7093:                         }
                   7094:                     } 
1.765     albertel 7095:                 }
                   7096:             }
                   7097:             my %roleshash;
                   7098:             my @courses_and_groups = @courses;
                   7099:             push(@courses_and_groups,@groups); 
                   7100:             if (@courses_and_groups > 0) {
                   7101:                 my (%allgroups,%allroles); 
                   7102:                 my ($start,$end,$role,$sec,$group);
                   7103:                 foreach my $envkey (%env) {
1.1060    raeburn  7104:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7105:                         my $cid = $2.'_'.$3; 
                   7106:                         if ($1 eq 'gr') {
                   7107:                             $group = $4;
                   7108:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7109:                         } else {
                   7110:                             if ($4 eq '') {
                   7111:                                 $sec = 'none';
                   7112:                             } else {
                   7113:                                 $sec = $4;
                   7114:                             }
                   7115:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7116:                         }
1.811     albertel 7117:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7118:                         my $cid = $2.'_'.$3;
                   7119:                         if ($4 eq '') {
                   7120:                             $sec = 'none';
                   7121:                         } else {
                   7122:                             $sec = $4;
                   7123:                         }
                   7124:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7125:                     }
                   7126:                 }
                   7127:                 if (keys(%allroles) == 0) {
                   7128:                     return;
                   7129:                 }
                   7130:                 foreach my $key (@courses_and_groups) {
                   7131:                     my %content = %{$$access_hash{$key}};
                   7132:                     my $cnum = $content{'number'};
                   7133:                     my $cdom = $content{'domain'};
                   7134:                     my $cid = $cdom.'_'.$cnum;
                   7135:                     if (!exists($allroles{$cid})) {
                   7136:                         next;
                   7137:                     }    
                   7138:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7139:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7140:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7141:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7142:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7143:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7144:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7145:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7146:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7147:                                         if (grep/^all$/,@sections) {
                   7148:                                             return 'ok';
                   7149:                                         } else {
                   7150:                                             if (grep/^$sec$/,@sections) {
                   7151:                                                 return 'ok';
                   7152:                                             }
                   7153:                                         }
                   7154:                                     }
                   7155:                                 }
                   7156:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7157:                                     if (grep/^none$/,@groups) {
                   7158:                                         return 'ok';
                   7159:                                     }
                   7160:                                 } else {
                   7161:                                     if (grep/^all$/,@groups) {
                   7162:                                         return 'ok';
                   7163:                                     } 
                   7164:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7165:                                         if (grep/^$group$/,@groups) {
                   7166:                                             return 'ok';
                   7167:                                         }
                   7168:                                     }
                   7169:                                 } 
                   7170:                             }
                   7171:                         }
                   7172:                     }
                   7173:                 }
                   7174:             }
                   7175:             if ($guest) {
                   7176:                 return $guest;
                   7177:             }
                   7178:         }
                   7179:     }
                   7180:     return;
                   7181: }
                   7182: 
                   7183: sub course_group_datechecker {
                   7184:     my ($dates,$now,$status) = @_;
                   7185:     my ($start,$end) = split(/\./,$dates);
                   7186:     if (!$start && !$end) {
                   7187:         return 'ok';
                   7188:     }
                   7189:     if (grep/^active$/,@{$status}) {
                   7190:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7191:             return 'ok';
                   7192:         }
                   7193:     }
                   7194:     if (grep/^previous$/,@{$status}) {
                   7195:         if ($end > $now ) {
                   7196:             return 'ok';
                   7197:         }
                   7198:     }
                   7199:     if (grep/^future$/,@{$status}) {
                   7200:         if ($start > $now) {
                   7201:             return 'ok';
                   7202:         }
                   7203:     }
                   7204:     return; 
                   7205: }
                   7206: 
                   7207: sub parse_portfolio_url {
                   7208:     my ($url) = @_;
                   7209: 
                   7210:     my ($type,$udom,$unum,$group,$file_name);
                   7211:     
1.823     albertel 7212:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7213: 	$type = 1;
                   7214:         $udom = $1;
                   7215:         $unum = $2;
                   7216:         $file_name = $3;
1.823     albertel 7217:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7218: 	$type = 2;
                   7219:         $udom = $1;
                   7220:         $unum = $2;
                   7221:         $group = $3;
                   7222:         $file_name = $3.'/'.$4;
                   7223:     }
                   7224:     if (wantarray) {
                   7225: 	return ($type,$udom,$unum,$file_name,$group);
                   7226:     }
                   7227:     return $type;
                   7228: }
                   7229: 
                   7230: sub is_portfolio_url {
                   7231:     my ($url) = @_;
                   7232:     return scalar(&parse_portfolio_url($url));
                   7233: }
                   7234: 
1.798     raeburn  7235: sub is_portfolio_file {
                   7236:     my ($file) = @_;
1.820     raeburn  7237:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7238:         return 1;
                   7239:     }
                   7240:     return;
                   7241: }
                   7242: 
1.976     raeburn  7243: sub usertools_access {
1.1084    raeburn  7244:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7245:     my ($access,%tools);
                   7246:     if ($context eq '') {
                   7247:         $context = 'tools';
                   7248:     }
                   7249:     if ($context eq 'requestcourses') {
                   7250:         %tools = (
                   7251:                       official   => 1,
                   7252:                       unofficial => 1,
1.1006    raeburn  7253:                       community  => 1,
1.1246    raeburn  7254:                       textbook   => 1,
1.1305    raeburn  7255:                       placement  => 1,
1.1368    raeburn  7256:                       lti        => 1,
1.985     raeburn  7257:                  );
1.1183    raeburn  7258:     } elsif ($context eq 'requestauthor') {
                   7259:         %tools = (
                   7260:                       requestauthor => 1,
                   7261:                  );
1.985     raeburn  7262:     } else {
                   7263:         %tools = (
                   7264:                       aboutme   => 1,
                   7265:                       blog      => 1,
1.1177    raeburn  7266:                       webdav    => 1,
1.985     raeburn  7267:                       portfolio => 1,
                   7268:                  );
                   7269:     }
1.976     raeburn  7270:     return if (!defined($tools{$tool}));
                   7271: 
1.1242    raeburn  7272:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7273:         $udom = $env{'user.domain'};
                   7274:         $uname = $env{'user.name'};
                   7275:     }
                   7276: 
1.978     raeburn  7277:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7278:         if ($action ne 'reload') {
1.985     raeburn  7279:             if ($context eq 'requestcourses') {
                   7280:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7281:             } elsif ($context eq 'requestauthor') {
                   7282:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7283:             } else {
                   7284:                 return $env{'environment.availabletools.'.$tool};
                   7285:             }
                   7286:         }
1.976     raeburn  7287:     }
                   7288: 
1.1183    raeburn  7289:     my ($toolstatus,$inststatus,$envkey);
                   7290:     if ($context eq 'requestauthor') {
                   7291:         $envkey = $context; 
                   7292:     } else {
                   7293:         $envkey = $context.'.'.$tool;
                   7294:     }
1.976     raeburn  7295: 
1.985     raeburn  7296:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7297:          ($action ne 'reload')) {
1.1183    raeburn  7298:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7299:         $inststatus = $env{'environment.inststatus'};
                   7300:     } else {
1.1084    raeburn  7301:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7302:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7303:             $inststatus = $userenvref->{'inststatus'};
                   7304:         } else {
1.1183    raeburn  7305:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7306:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7307:             $inststatus = $userenv{'inststatus'};
                   7308:         }
1.976     raeburn  7309:     }
                   7310: 
                   7311:     if ($toolstatus ne '') {
                   7312:         if ($toolstatus) {
                   7313:             $access = 1;
                   7314:         } else {
                   7315:             $access = 0;
                   7316:         }
                   7317:         return $access;
                   7318:     }
                   7319: 
1.1084    raeburn  7320:     my ($is_adv,%domdef);
                   7321:     if (ref($is_advref) eq 'HASH') {
                   7322:         $is_adv = $is_advref->{'is_adv'};
                   7323:     } else {
                   7324:         $is_adv = &is_advanced_user($udom,$uname);
                   7325:     }
                   7326:     if (ref($domdefref) eq 'HASH') {
                   7327:         %domdef = %{$domdefref};
                   7328:     } else {
                   7329:         %domdef = &get_domain_defaults($udom);
                   7330:     }
1.976     raeburn  7331:     if (ref($domdef{$tool}) eq 'HASH') {
                   7332:         if ($is_adv) {
                   7333:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7334:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7335:                     $access = 1;
                   7336:                 } else {
                   7337:                     $access = 0;
                   7338:                 }
                   7339:                 return $access;
                   7340:             }
                   7341:         }
                   7342:         if ($inststatus ne '') {
                   7343:             my ($hasaccess,$hasnoaccess);
                   7344:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7345:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7346:                     if ($domdef{$tool}{$affiliation}) {
                   7347:                         $hasaccess = 1;
                   7348:                     } else {
                   7349:                         $hasnoaccess = 1;
                   7350:                     }
                   7351:                 }
                   7352:             }
                   7353:             if ($hasaccess || $hasnoaccess) {
                   7354:                 if ($hasaccess) {
                   7355:                     $access = 1;
                   7356:                 } elsif ($hasnoaccess) {
                   7357:                     $access = 0; 
                   7358:                 }
                   7359:                 return $access;
                   7360:             }
                   7361:         } else {
                   7362:             if ($domdef{$tool}{'default'} ne '') {
                   7363:                 if ($domdef{$tool}{'default'}) {
                   7364:                     $access = 1;
                   7365:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7366:                     $access = 0;
                   7367:                 }
                   7368:                 return $access;
                   7369:             }
                   7370:         }
                   7371:     } else {
1.1177    raeburn  7372:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7373:             $access = 1;
                   7374:         } else {
                   7375:             $access = 0;
                   7376:         }
1.976     raeburn  7377:         return $access;
                   7378:     }
                   7379: }
                   7380: 
1.1050    raeburn  7381: sub is_course_owner {
                   7382:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7383:     if (($udom eq '') || ($uname eq '')) {
                   7384:         $udom = $env{'user.domain'};
                   7385:         $uname = $env{'user.name'};
                   7386:     }
                   7387:     unless (($udom eq '') || ($uname eq '')) {
                   7388:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7389:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7390:                 return 1;
                   7391:             } else {
                   7392:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7393:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7394:                     return 1;
                   7395:                 }
                   7396:             }
                   7397:         }
                   7398:     }
                   7399:     return;
                   7400: }
                   7401: 
1.976     raeburn  7402: sub is_advanced_user {
                   7403:     my ($udom,$uname) = @_;
1.1085    raeburn  7404:     if ($udom ne '' && $uname ne '') {
                   7405:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7406:             if (wantarray) {
                   7407:                 return ($env{'user.adv'},$env{'user.author'});
                   7408:             } else {
                   7409:                 return $env{'user.adv'};
                   7410:             }
1.1085    raeburn  7411:         }
                   7412:     }
1.976     raeburn  7413:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7414:     my %allroles;
1.1128    raeburn  7415:     my ($is_adv,$is_author);
1.976     raeburn  7416:     foreach my $role (keys(%roleshash)) {
                   7417:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7418:         my $area = '/'.$tdomain.'/'.$trest;
                   7419:         if ($sec ne '') {
                   7420:             $area .= '/'.$sec;
                   7421:         }
                   7422:         if (($area ne '') && ($trole ne '')) {
                   7423:             my $spec=$trole.'.'.$area;
                   7424:             if ($trole =~ /^cr\//) {
                   7425:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7426:             } elsif ($trole ne 'gr') {
                   7427:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7428:             }
1.1128    raeburn  7429:             if ($trole eq 'au') {
                   7430:                 $is_author = 1;
                   7431:             }
1.976     raeburn  7432:         }
                   7433:     }
                   7434:     foreach my $role (keys(%allroles)) {
                   7435:         last if ($is_adv);
                   7436:         foreach my $item (split(/:/,$allroles{$role})) {
                   7437:             if ($item ne '') {
                   7438:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7439:                 if ($privilege eq 'adv') {
                   7440:                     $is_adv = 1;
                   7441:                     last;
                   7442:                 }
                   7443:             }
                   7444:         }
                   7445:     }
1.1128    raeburn  7446:     if (wantarray) {
                   7447:         return ($is_adv,$is_author);
                   7448:     }
1.976     raeburn  7449:     return $is_adv;
                   7450: }
1.798     raeburn  7451: 
1.1035    raeburn  7452: sub check_can_request {
1.1368    raeburn  7453:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7454:     my $canreq = 0;
1.1368    raeburn  7455:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7456:         $uname = $env{'user.name'};
                   7457:         $udom = $env{'user.domain'};
                   7458:     }
1.1035    raeburn  7459:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7460:     my @options = ('approval','validate','autolimit');
                   7461:     my $optregex = join('|',@options);
                   7462:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7463:         foreach my $type (@{$types}) {
1.1368    raeburn  7464:             if (&usertools_access($uname,$udom,$type,undef,
                   7465:                                   'requestcourses')) {
1.1035    raeburn  7466:                 $canreq ++;
1.1036    raeburn  7467:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7468:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7469:                 }
1.1368    raeburn  7470:                 if ($dom eq $udom) {
1.1035    raeburn  7471:                     $can_request->{$type} = 1;
                   7472:                 }
                   7473:             }
1.1368    raeburn  7474:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7475:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7476:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7477:                 if (@curr > 0) {
1.1036    raeburn  7478:                     foreach my $item (@curr) {
                   7479:                         if (ref($request_domains) eq 'HASH') {
                   7480:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7481:                             if ($otherdom ne '') {
                   7482:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7483:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7484:                                         push(@{$request_domains->{$type}},$otherdom);
                   7485:                                     }
                   7486:                                 } else {
                   7487:                                     push(@{$request_domains->{$type}},$otherdom);
                   7488:                                 }
                   7489:                             }
                   7490:                         }
                   7491:                     }
1.1368    raeburn  7492:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7493:                         $canreq ++;
1.1035    raeburn  7494:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7495:                             $can_request->{$type} = 1;
                   7496:                         }
                   7497:                     }
                   7498:                 }
                   7499:             }
                   7500:         }
                   7501:     }
                   7502:     return $canreq;
                   7503: }
                   7504: 
1.341     www      7505: # ---------------------------------------------- Custom access rule evaluation
                   7506: 
                   7507: sub customaccess {
                   7508:     my ($priv,$uri)=@_;
1.807     albertel 7509:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7510:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7511:     $udom = &LONCAPA::clean_domain($udom);
                   7512:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7513:     my $access=0;
1.800     albertel 7514:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7515: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7516: 	if ($type eq 'user') {
                   7517: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7518: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7519: 		if ($tdom) {
                   7520: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7521: 		}
1.896     albertel 7522: 		if ($tuname) {
                   7523: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7524: 		}
                   7525: 		$access=($effect eq 'allow');
                   7526: 		last;
                   7527: 	    }
                   7528: 	} else {
                   7529: 	    if ($role) {
                   7530: 		if ($role ne $urole) { next; }
                   7531: 	    }
                   7532: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7533: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7534: 		if ($tdom) {
                   7535: 		    if ($tdom ne $udom) { next; }
                   7536: 		}
                   7537: 		if ($tcrs) {
                   7538: 		    if ($tcrs ne $ucrs) { next; }
                   7539: 		}
                   7540: 		if ($tsec) {
                   7541: 		    if ($tsec ne $usec) { next; }
                   7542: 		}
                   7543: 		$access=($effect eq 'allow');
                   7544: 		last;
                   7545: 	    }
                   7546: 	    if ($realm eq '' && $role eq '') {
                   7547: 		$access=($effect eq 'allow');
                   7548: 	    }
1.402     bowersj2 7549: 	}
1.341     www      7550:     }
                   7551:     return $access;
                   7552: }
                   7553: 
1.103     harris41 7554: # ------------------------------------------------- Check for a user privilege
1.12      www      7555: 
                   7556: sub allowed {
1.1281    raeburn  7557:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7558:     my $ver_orguri=$uri;
1.439     www      7559:     $uri=&deversion($uri);
1.152     www      7560:     my $orguri=$uri;
1.52      www      7561:     $uri=&declutter($uri);
1.809     raeburn  7562: 
1.810     raeburn  7563:     if ($priv eq 'evb') {
                   7564: # Evade communication block restrictions for specified role in a course
                   7565:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7566:             return $1;
                   7567:         } else {
                   7568:             return;
                   7569:         }
                   7570:     }
                   7571: 
1.620     albertel 7572:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7573: # Free bre access to adm and meta resources
1.1343    raeburn  7574:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7575: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7576: 	&& ($priv eq 'bre')) {
1.14      www      7577: 	return 'F';
1.159     www      7578:     }
                   7579: 
1.545     banghart 7580: # Free bre access to user's own portfolio contents
1.714     raeburn  7581:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7582:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7583: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7584:         my %setters;
                   7585:         my ($startblock,$endblock) = 
                   7586:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7587:         if ($startblock && $endblock) {
                   7588:             return 'B';
                   7589:         } else {
                   7590:             return 'F';
                   7591:         }
1.545     banghart 7592:     }
                   7593: 
1.762     raeburn  7594: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7595:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7596:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7597:         if (exists($env{'request.course.id'})) {
                   7598:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7599:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7600:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7601:                 my $courseprivid=$env{'request.course.id'};
                   7602:                 $courseprivid=~s/\_/\//;
                   7603:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7604:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7605:                     return $1; 
1.762     raeburn  7606:                 } else {
                   7607:                     if ($env{'request.course.sec'}) {
                   7608:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7609:                     }
                   7610:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7611:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7612:                         return $2;
                   7613:                     }
1.714     raeburn  7614:                 }
                   7615:             }
                   7616:         }
                   7617:     }
                   7618: 
1.159     www      7619: # Free bre to public access
                   7620: 
                   7621:     if ($priv eq 'bre') {
1.1362    raeburn  7622:         my $copyright;
                   7623:         unless ($uri =~ /ext\.tool/) {
                   7624:             $copyright=&metadata($uri,'copyright');
                   7625:         }
1.620     albertel 7626: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7627:            return 'F'; 
                   7628:         }
1.238     www      7629:         if ($copyright eq 'priv') {
                   7630:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7631: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7632: 		return '';
                   7633:             }
                   7634:         }
                   7635:         if ($copyright eq 'domain') {
                   7636:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7637: 	    unless (($env{'user.domain'} eq $1) ||
                   7638:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7639: 		return '';
                   7640:             }
1.262     matthew  7641:         }
1.620     albertel 7642:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7643:             # Library role, so allow browsing of resources in this domain.
                   7644:             return 'F';
1.238     www      7645:         }
1.341     www      7646:         if ($copyright eq 'custom') {
                   7647: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7648:         }
1.14      www      7649:     }
1.264     matthew  7650:     # Domain coordinator is trying to create a course
1.620     albertel 7651:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7652:         # uri is the requested domain in this case.
                   7653:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7654:         # a role of dc for the domain in question.
1.620     albertel 7655:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7656:     }
1.29      www      7657: 
1.52      www      7658:     my $thisallowed='';
                   7659:     my $statecond=0;
                   7660:     my $courseprivid='';
                   7661: 
1.1039    raeburn  7662:     my $ownaccess;
1.1043    raeburn  7663:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7664:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7665:         if ($uri eq '') {
                   7666:             $ownaccess = 1;
                   7667:         } else {
                   7668:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7669:                 my $udom = $env{'user.domain'};
                   7670:                 my $uname = $env{'user.name'};
                   7671:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7672:                     $ownaccess = 1;
1.1040    raeburn  7673:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7674:                     unless ($uri =~ m{\.\./}) {
                   7675:                         $ownaccess = 1;
                   7676:                     }
                   7677:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7678:                     my $now = time;
                   7679:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7680:                         my $adom = $1;
                   7681:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7682:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7683:                                 my ($start,$end) = split('.',$env{$key});
                   7684:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7685:                                     $ownaccess = 1;
                   7686:                                     last;
                   7687:                                 }
                   7688:                             }
                   7689:                         }
                   7690:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7691:                         my $adom = $1;
                   7692:                         my $aname = $2;
1.1042    raeburn  7693:                         foreach my $role ('ca','aa') { 
                   7694:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7695:                                 my ($start,$end) =
                   7696:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7697:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7698:                                     $ownaccess = 1;
                   7699:                                     last;
                   7700:                                 }
1.1039    raeburn  7701:                             }
                   7702:                         }
                   7703:                     }
                   7704:                 }
                   7705:             }
                   7706:         }
                   7707:     }
                   7708: 
1.52      www      7709: # Course
                   7710: 
1.620     albertel 7711:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7712:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7713:             $thisallowed.=$1;
                   7714:         }
1.52      www      7715:     }
1.29      www      7716: 
1.52      www      7717: # Domain
                   7718: 
1.620     albertel 7719:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7720:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7721:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7722:             $thisallowed.=$1;
                   7723:         }
1.12      www      7724:     }
1.52      www      7725: 
1.1141    raeburn  7726: # User who is not author or co-author might still be able to edit
                   7727: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7728:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7729:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7730:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7731:             $thisallowed.=$1;
                   7732:         }
                   7733:     }
                   7734: 
1.52      www      7735: # Course: uri itself is a course
1.66      www      7736:     my $courseuri=$uri;
                   7737:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7738:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7739: 
1.620     albertel 7740:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7741:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7742:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7743:             $thisallowed.=$1;
                   7744:         }
1.12      www      7745:     }
1.29      www      7746: 
1.665     albertel 7747: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7748: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7749:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7750: 	$thisallowed='';
1.671     raeburn  7751:         my ($match)=&is_on_map($uri);
                   7752:         if ($match) {
                   7753:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7754:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7755:                 my $value = $1;
                   7756:                 if ($noblockcheck) {
                   7757:                     $thisallowed.=$value;
1.1162    raeburn  7758:                 } else {
1.1281    raeburn  7759:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7760:                     if (@blockers > 0) {
                   7761:                         $thisallowed = 'B';
                   7762:                     } else {
                   7763:                         $thisallowed.=$value;
                   7764:                     }
1.1162    raeburn  7765:                 }
1.671     raeburn  7766:             }
                   7767:         } else {
1.705     albertel 7768:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7769:             if ($refuri) {
                   7770:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7771:                     $thisallowed='F';
1.671     raeburn  7772:                 } else {
                   7773:                     $refuri=&declutter($refuri);
                   7774:                     my ($match) = &is_on_map($refuri);
                   7775:                     if ($match) {
1.1281    raeburn  7776:                         if ($noblockcheck) {
                   7777:                             $thisallowed='F';
1.1162    raeburn  7778:                         } else {
1.1281    raeburn  7779:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7780:                             if (@blockers > 0) {
                   7781:                                 $thisallowed = 'B';
                   7782:                             } else {
                   7783:                                 $thisallowed='F';
                   7784:                             }
1.1162    raeburn  7785:                         }
1.671     raeburn  7786:                     }
1.669     raeburn  7787:                 }
1.671     raeburn  7788:             }
                   7789:         }
1.314     www      7790:     }
1.492     albertel 7791: 
1.766     albertel 7792:     if ($priv eq 'bre'
                   7793: 	&& $thisallowed ne 'F' 
                   7794: 	&& $thisallowed ne '2'
                   7795: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7796: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7797:     }
1.1250    raeburn  7798: 
1.52      www      7799: # Full access at system, domain or course-wide level? Exit.
1.29      www      7800:     if ($thisallowed=~/F/) {
                   7801: 	return 'F';
                   7802:     }
                   7803: 
1.52      www      7804: # If this is generating or modifying users, exit with special codes
1.29      www      7805: 
1.643     www      7806:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7807: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7808: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7809: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7810: 	    unless ($auname) { return $thisallowed; }
                   7811: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7812: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7813: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7814: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7815: 	}
1.52      www      7816: 	return $thisallowed;
                   7817:     }
                   7818: #
1.103     harris41 7819: # Gathered so far: system, domain and course wide privileges
1.52      www      7820: #
                   7821: # Course: See if uri or referer is an individual resource that is part of 
                   7822: # the course
                   7823: 
1.620     albertel 7824:     if ($env{'request.course.id'}) {
1.232     www      7825: 
1.620     albertel 7826:        $courseprivid=$env{'request.course.id'};
                   7827:        if ($env{'request.course.sec'}) {
                   7828:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7829:        }
                   7830:        $courseprivid=~s/\_/\//;
                   7831:        my $checkreferer=1;
1.232     www      7832:        my ($match,$cond)=&is_on_map($uri);
                   7833:        if ($match) {
                   7834:            $statecond=$cond;
1.620     albertel 7835:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7836:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7837:                my $value = $1;
                   7838:                if ($priv eq 'bre') {
1.1281    raeburn  7839:                    if ($noblockcheck) {
                   7840:                        $thisallowed.=$value;
1.1162    raeburn  7841:                    } else {
1.1281    raeburn  7842:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7843:                        if (@blockers > 0) {
                   7844:                            $thisallowed = 'B';
                   7845:                        } else {
                   7846:                            $thisallowed.=$value;
                   7847:                        }
1.1162    raeburn  7848:                    }
                   7849:                } else {
                   7850:                    $thisallowed.=$value;
                   7851:                }
1.52      www      7852:                $checkreferer=0;
                   7853:            }
1.29      www      7854:        }
1.83      www      7855:        
1.148     www      7856:        if ($checkreferer) {
1.620     albertel 7857: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7858:             unless ($refuri) {
1.800     albertel 7859:                 foreach my $key (keys(%env)) {
                   7860: 		    if ($key=~/^httpref\..*\*/) {
                   7861: 			my $pattern=$key;
1.156     www      7862:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7863:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7864:                         $pattern=~s/\//\\\//g;
1.152     www      7865:                         if ($orguri=~/$pattern/) {
1.800     albertel 7866: 			    $refuri=$env{$key};
1.148     www      7867:                         }
                   7868:                     }
1.191     harris41 7869:                 }
1.148     www      7870:             }
1.232     www      7871: 
1.148     www      7872:          if ($refuri) { 
1.152     www      7873: 	  $refuri=&declutter($refuri);
1.232     www      7874:           my ($match,$cond)=&is_on_map($refuri);
                   7875:             if ($match) {
                   7876:               my $refstatecond=$cond;
1.620     albertel 7877:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7878:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7879:                   my $value = $1;
                   7880:                   if ($priv eq 'bre') {
1.1281    raeburn  7881:                       if ($noblockcheck) {
                   7882:                           $thisallowed.=$value;
1.1162    raeburn  7883:                       } else {
1.1281    raeburn  7884:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7885:                           if (@blockers > 0) {
                   7886:                               $thisallowed = 'B';
                   7887:                           } else {
                   7888:                               $thisallowed.=$value;
                   7889:                           }
1.1162    raeburn  7890:                       }
                   7891:                   } else {
                   7892:                       $thisallowed.=$value;
                   7893:                   }
1.53      www      7894:                   $uri=$refuri;
                   7895:                   $statecond=$refstatecond;
1.52      www      7896:               }
                   7897:           }
1.148     www      7898:         }
1.29      www      7899:        }
1.52      www      7900:    }
1.29      www      7901: 
1.52      www      7902: #
1.103     harris41 7903: # Gathered now: all privileges that could apply, and condition number
1.52      www      7904: # 
                   7905: #
                   7906: # Full or no access?
                   7907: #
1.29      www      7908: 
1.52      www      7909:     if ($thisallowed=~/F/) {
                   7910: 	return 'F';
                   7911:     }
1.29      www      7912: 
1.52      www      7913:     unless ($thisallowed) {
                   7914:         return '';
                   7915:     }
1.29      www      7916: 
1.52      www      7917: # Restrictions exist, deal with them
                   7918: #
                   7919: #   C:according to course preferences
                   7920: #   R:according to resource settings
                   7921: #   L:unless locked
                   7922: #   X:according to user session state
                   7923: #
                   7924: 
                   7925: # Possibly locked functionality, check all courses
1.54      www      7926: # Locks might take effect only after 10 minutes cache expiration for other
                   7927: # courses, and 2 minutes for current course
1.52      www      7928: 
                   7929:     my $envkey;
                   7930:     if ($thisallowed=~/L/) {
1.1000    raeburn  7931:         foreach $envkey (keys(%env)) {
1.54      www      7932:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7933:                my $courseid=$2;
                   7934:                my $roleid=$1.'.'.$2;
1.92      www      7935:                $courseid=~s/^\///;
1.54      www      7936:                my $expiretime=600;
1.620     albertel 7937:                if ($env{'request.role'} eq $roleid) {
1.54      www      7938: 		  $expiretime=120;
                   7939:                }
                   7940: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7941:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7942:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7943: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7944:                }
1.620     albertel 7945:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7946:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7947: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7948:                        &log($env{'user.domain'},$env{'user.name'},
                   7949:                             $env{'user.home'},
1.57      www      7950:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7951:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7952:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7953: 		       return '';
                   7954:                    }
                   7955:                }
1.620     albertel 7956:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7957:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7958: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7959:                        &log($env{'user.domain'},$env{'user.name'},
                   7960:                             $env{'user.home'},
1.57      www      7961:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7962:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7963:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7964: 		       return '';
                   7965:                    }
                   7966:                }
                   7967: 	   }
1.29      www      7968:        }
1.52      www      7969:     }
                   7970:    
                   7971: #
                   7972: # Rest of the restrictions depend on selected course
                   7973: #
                   7974: 
1.620     albertel 7975:     unless ($env{'request.course.id'}) {
1.766     albertel 7976: 	if ($thisallowed eq 'A') {
                   7977: 	    return 'A';
1.814     raeburn  7978:         } elsif ($thisallowed eq 'B') {
                   7979:             return 'B';
1.766     albertel 7980: 	} else {
                   7981: 	    return '1';
                   7982: 	}
1.52      www      7983:     }
1.29      www      7984: 
1.52      www      7985: #
                   7986: # Now user is definitely in a course
                   7987: #
1.53      www      7988: 
                   7989: 
                   7990: # Course preferences
                   7991: 
                   7992:    if ($thisallowed=~/C/) {
1.620     albertel 7993:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7994:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7995:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7996: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7997: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7998: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7999: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8000: 			$env{'request.course.id'});
                   8001: 	   }
1.237     www      8002:            return '';
                   8003:        }
                   8004: 
1.620     albertel 8005:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8006: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8007: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8008: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8009: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8010: 			$env{'request.course.id'});
                   8011: 	   }
1.54      www      8012:            return '';
                   8013:        }
1.53      www      8014:    }
                   8015: 
                   8016: # Resource preferences
                   8017: 
                   8018:    if ($thisallowed=~/R/) {
1.620     albertel 8019:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8020:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8021: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8022: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8023: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8024: 	   }
                   8025: 	   return '';
1.54      www      8026:        }
1.53      www      8027:    }
1.30      www      8028: 
1.246     www      8029: # Restricted by state or randomout?
1.30      www      8030: 
1.52      www      8031:    if ($thisallowed=~/X/) {
1.620     albertel 8032:       if ($env{'acc.randomout'}) {
1.579     albertel 8033: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8034:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8035:             return ''; 
                   8036:          }
1.247     www      8037:       }
                   8038:       if (&condval($statecond)) {
1.52      www      8039: 	 return '2';
                   8040:       } else {
                   8041:          return '';
                   8042:       }
                   8043:    }
1.30      www      8044: 
1.766     albertel 8045:     if ($thisallowed eq 'A') {
                   8046: 	return 'A';
1.814     raeburn  8047:     } elsif ($thisallowed eq 'B') {
                   8048:         return 'B';
1.766     albertel 8049:     }
1.52      www      8050:    return 'F';
1.232     www      8051: }
1.1162    raeburn  8052: 
1.1192    raeburn  8053: # ------------------------------------------- Check construction space access
                   8054: 
                   8055: sub constructaccess {
                   8056:     my ($url,$setpriv)=@_;
                   8057: 
                   8058: # We do not allow editing of previous versions of files
                   8059:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8060: 
                   8061: # Get username and domain from URL
                   8062:     my ($ownername,$ownerdomain,$ownerhome);
                   8063: 
                   8064:     ($ownerdomain,$ownername) =
1.1325    raeburn  8065:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8066: 
                   8067: # The URL does not really point to any authorspace, forget it
                   8068:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8069: 
                   8070: # Now we need to see if the user has access to the authorspace of
                   8071: # $ownername at $ownerdomain
                   8072: 
                   8073:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8074: # Real author for this?
                   8075:        $ownerhome = $env{'user.home'};
                   8076:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8077:           return ($ownername,$ownerdomain,$ownerhome);
                   8078:        }
                   8079:     } else {
                   8080: # Co-author for this?
                   8081:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8082:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8083:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8084:             return ($ownername,$ownerdomain,$ownerhome);
                   8085:         }
1.1312    raeburn  8086:         if ($env{'request.course.id'}) {
                   8087:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8088:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8089:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8090:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8091:                     return ($ownername,$ownerdomain,$ownerhome);
                   8092:                 }
                   8093:             }
                   8094:         }
1.1192    raeburn  8095:     }
                   8096: 
                   8097: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8098: # we might as well leave
                   8099:    unless ($setpriv) { return ''; }
                   8100: 
                   8101: # Backdoor access?
                   8102:     my $allowed=&allowed('eco',$ownerdomain);
                   8103: # Nope
                   8104:     unless ($allowed) { return ''; }
                   8105: # Looks like we may have access, but could be locked by the owner of the construction space
                   8106:     if ($allowed eq 'U') {
                   8107:         my %blocked=&get('environment',['domcoord.author'],
                   8108:                          $ownerdomain,$ownername);
                   8109: # Is blocked by owner
                   8110:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8111:     }
                   8112:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8113: # Grant temporary access
                   8114:         my $then=$env{'user.login.time'};
1.1209    raeburn  8115:         my $update=$env{'user.update.time'};
1.1192    raeburn  8116:         if (!$update) { $update = $then; }
                   8117:         my $refresh=$env{'user.refresh.time'};
                   8118:         if (!$refresh) { $refresh = $update; }
                   8119:         my $now = time;
                   8120:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8121:                            $now,'ca','constructaccess');
                   8122:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8123:         return($ownername,$ownerdomain,$ownerhome);
                   8124:     }
                   8125: # No business here
                   8126:     return '';
                   8127: }
                   8128: 
1.1282    raeburn  8129: # ----------------------------------------------------------- Content Blocking
                   8130: 
                   8131: {
                   8132: # Caches for faster Course Contents display where content blocking
                   8133: # is in operation (i.e., interval param set) for timed quiz.
                   8134: #
                   8135: # User for whom data are being temporarily cached.
                   8136: my $cacheduser='';
                   8137: # Cached blockers for this user (a hash of blocking items). 
                   8138: my %cachedblockers=();
                   8139: # When the data were last cached.
                   8140: my $cachedlast='';
                   8141: 
                   8142: sub load_all_blockers {
                   8143:     my ($uname,$udom,$blocks)=@_;
                   8144:     if (($uname ne '') && ($udom ne '')) { 
                   8145:         if (($cacheduser eq $uname.':'.$udom) &&
                   8146:             (abs($cachedlast-time)<5)) {
                   8147:             return;
                   8148:         }
                   8149:     }
                   8150:     $cachedlast=time;
                   8151:     $cacheduser=$uname.':'.$udom;
                   8152:     %cachedblockers = &get_commblock_resources($blocks);
                   8153: }
                   8154: 
1.1162    raeburn  8155: sub get_comm_blocks {
                   8156:     my ($cdom,$cnum) = @_;
                   8157:     if ($cdom eq '' || $cnum eq '') {
                   8158:         return unless ($env{'request.course.id'});
                   8159:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8160:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8161:     }
                   8162:     my %commblocks;
                   8163:     my $hashid=$cdom.'_'.$cnum;
                   8164:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8165:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8166:         %commblocks = %{$blocksref};
                   8167:     } else {
                   8168:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8169:         my $cachetime = 600;
                   8170:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8171:     }
                   8172:     return %commblocks;
                   8173: }
                   8174: 
1.1282    raeburn  8175: sub get_commblock_resources {
                   8176:     my ($blocks) = @_;
                   8177:     my %blockers = ();
                   8178:     return %blockers unless ($env{'request.course.id'});
                   8179:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8180:     my %commblocks;
                   8181:     if (ref($blocks) eq 'HASH') {
                   8182:         %commblocks = %{$blocks};
                   8183:     } else {
                   8184:         %commblocks = &get_comm_blocks();
                   8185:     }
1.1282    raeburn  8186:     return %blockers unless (keys(%commblocks) > 0); 
                   8187:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8188:     return %blockers unless (ref($navmap));
1.1162    raeburn  8189:     my $now = time;
                   8190:     foreach my $block (keys(%commblocks)) {
                   8191:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8192:             my ($start,$end) = ($1,$2);
                   8193:             if ($start <= $now && $end >= $now) {
                   8194:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8195:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8196:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8197:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8198:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8199:                             }
                   8200:                         }
                   8201:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8202:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8203:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8204:                             }
                   8205:                         }
                   8206:                     }
                   8207:                 }
                   8208:             }
                   8209:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8210:             my $item = $1;
1.1163    raeburn  8211:             my @to_test;
1.1162    raeburn  8212:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8213:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8214:                     my @interval;
                   8215:                     my $type = 'map';
                   8216:                     if ($item eq 'course') {
                   8217:                         $type = 'course';
                   8218:                         @interval=&EXT("resource.0.interval");
                   8219:                     } else {
                   8220:                         if ($item =~ /___\d+___/) {
                   8221:                             $type = 'resource';
                   8222:                             @interval=&EXT("resource.0.interval",$item);
                   8223:                             if (ref($navmap)) {                        
                   8224:                                 my $res = $navmap->getBySymb($item); 
                   8225:                                 push(@to_test,$res);
                   8226:                             }
1.1162    raeburn  8227:                         } else {
1.1282    raeburn  8228:                             my $mapsymb = &symbread($item,1);
                   8229:                             if ($mapsymb) {
                   8230:                                 if (ref($navmap)) {
                   8231:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8232:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8233:                                     foreach my $res (@to_test) {
                   8234:                                         my $symb = $res->symb();
                   8235:                                         next if ($symb eq $mapsymb);
                   8236:                                         if ($symb ne '') {
                   8237:                                             @interval=&EXT("resource.0.interval",$symb);
                   8238:                                             if ($interval[1] eq 'map') {
                   8239:                                                 last;
1.1162    raeburn  8240:                                             }
                   8241:                                         }
                   8242:                                     }
                   8243:                                 }
                   8244:                             }
                   8245:                         }
1.1282    raeburn  8246:                     }
1.1310    raeburn  8247:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8248:                         my $timelimit = $1; 
1.1282    raeburn  8249:                         my $first_access;
                   8250:                         if ($type eq 'resource') {
                   8251:                             $first_access=&get_first_access($interval[1],$item);
                   8252:                         } elsif ($type eq 'map') {
                   8253:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8254:                         } else {
                   8255:                             $first_access=&get_first_access($interval[1]);
                   8256:                         }
                   8257:                         if ($first_access) {
1.1292    raeburn  8258:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8259:                             if ($timesup > $now) {
                   8260:                                 my $activeblock;
                   8261:                                 foreach my $res (@to_test) {
1.1283    raeburn  8262:                                     if ($res->answerable()) {
1.1282    raeburn  8263:                                         $activeblock = 1;
                   8264:                                         last;
                   8265:                                     }
                   8266:                                 }
                   8267:                                 if ($activeblock) {
                   8268:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8269:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8270:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8271:                                          }
                   8272:                                     }
                   8273:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8274:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8275:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8276:                                         }
1.1162    raeburn  8277:                                     }
                   8278:                                 }
                   8279:                             }
                   8280:                         }
                   8281:                     }
                   8282:                 }
                   8283:             }
                   8284:         }
                   8285:     }
1.1282    raeburn  8286:     return %blockers;
1.1162    raeburn  8287: }
                   8288: 
1.1282    raeburn  8289: sub has_comm_blocking {
                   8290:     my ($priv,$symb,$uri,$blocks) = @_;
                   8291:     my @blockers;
                   8292:     return unless ($env{'request.course.id'});
                   8293:     return unless ($priv eq 'bre');
                   8294:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8295:     return if ($env{'request.state'} eq 'construct');
                   8296:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8297:     return unless (keys(%cachedblockers) > 0);
                   8298:     my (%possibles,@symbs);
                   8299:     if (!$symb) {
                   8300:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8301:     }
1.1282    raeburn  8302:     if ($symb) {
                   8303:         @symbs = ($symb);
                   8304:     } elsif (keys(%possibles)) { 
                   8305:         @symbs = keys(%possibles);
                   8306:     }
                   8307:     my $noblock;
                   8308:     foreach my $symb (@symbs) {
                   8309:         last if ($noblock);
                   8310:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8311:         foreach my $block (keys(%cachedblockers)) {
                   8312:             if ($block =~ /^firstaccess____(.+)$/) {
                   8313:                 my $item = $1;
                   8314:                 if (($item eq $map) || ($item eq $symb)) {
                   8315:                     $noblock = 1;
                   8316:                     last;
                   8317:                 }
                   8318:             }
                   8319:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8320:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8321:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8322:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8323:                             push(@blockers,$block);
                   8324:                         }
                   8325:                     }
                   8326:                 }
1.1162    raeburn  8327:             }
1.1282    raeburn  8328:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8329:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8330:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8331:                         push(@blockers,$block);
                   8332:                     }
                   8333:                 }
1.1162    raeburn  8334:             }
                   8335:         }
                   8336:     }
1.1282    raeburn  8337:     return if ($noblock);
                   8338:     return @blockers;
                   8339: }
1.1162    raeburn  8340: }
                   8341: 
1.1282    raeburn  8342: # -------------------------------- Deversion and split uri into path an filename   
                   8343: 
1.1133    foxr     8344: #
1.1282    raeburn  8345: #   Removes the version from a URI and
1.1133    foxr     8346: #   splits it in to its filename and path to the filename.
                   8347: #   Seems like File::Basename could have done this more clearly.
                   8348: #   Parameters:
                   8349: #      $uri   - input URI
                   8350: #   Returns:
                   8351: #     Two element list consisting of 
                   8352: #     $pathname  - the URI up to and excluding the trailing /
                   8353: #     $filename  - The part of the URI following the last /
                   8354: #  NOTE:
                   8355: #    Another realization of this is simply:
                   8356: #    use File::Basename;
                   8357: #    ...
                   8358: #    $uri = shift;
                   8359: #    $filename = basename($uri);
                   8360: #    $path     = dirname($uri);
                   8361: #    return ($filename, $path);
                   8362: #
                   8363: #     The implementation below is probably faster however.
                   8364: #
1.710     albertel 8365: sub split_uri_for_cond {
                   8366:     my $uri=&deversion(&declutter(shift));
                   8367:     my @uriparts=split(/\//,$uri);
                   8368:     my $filename=pop(@uriparts);
                   8369:     my $pathname=join('/',@uriparts);
                   8370:     return ($pathname,$filename);
                   8371: }
1.232     www      8372: # --------------------------------------------------- Is a resource on the map?
                   8373: 
                   8374: sub is_on_map {
1.710     albertel 8375:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8376:     #Trying to find the conditional for the file
1.620     albertel 8377:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8378: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8379:     if ($match) {
1.289     bowersj2 8380: 	return (1,$1);
                   8381:     } else {
1.434     www      8382: 	return (0,0);
1.289     bowersj2 8383:     }
1.12      www      8384: }
                   8385: 
1.427     www      8386: # --------------------------------------------------------- Get symb from alias
                   8387: 
                   8388: sub get_symb_from_alias {
                   8389:     my $symb=shift;
                   8390:     my ($map,$resid,$url)=&decode_symb($symb);
                   8391: # Already is a symb
                   8392:     if ($url) { return $symb; }
                   8393: # Must be an alias
                   8394:     my $aliassymb='';
                   8395:     my %bighash;
1.620     albertel 8396:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8397:                             &GDBM_READER(),0640)) {
                   8398:         my $rid=$bighash{'mapalias_'.$symb};
                   8399: 	if ($rid) {
                   8400: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8401: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8402: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8403: 	}
                   8404:         untie %bighash;
                   8405:     }
                   8406:     return $aliassymb;
                   8407: }
                   8408: 
1.12      www      8409: # ----------------------------------------------------------------- Define Role
                   8410: 
                   8411: sub definerole {
                   8412:   if (allowed('mcr','/')) {
1.1326    raeburn  8413:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8414:     foreach my $role (split(':',$sysrole)) {
                   8415: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8416:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8417:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8418: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8419:                return "refused:s:$crole&$cqual"; 
                   8420:             }
                   8421:         }
1.191     harris41 8422:     }
1.800     albertel 8423:     foreach my $role (split(':',$domrole)) {
                   8424: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8425:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8426:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8427: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8428:                return "refused:d:$crole&$cqual"; 
                   8429:             }
                   8430:         }
1.191     harris41 8431:     }
1.800     albertel 8432:     foreach my $role (split(':',$courole)) {
                   8433: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8434:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8435:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8436: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8437:                return "refused:c:$crole&$cqual"; 
                   8438:             }
                   8439:         }
1.191     harris41 8440:     }
1.1326    raeburn  8441:     my $uhome;
                   8442:     if (($uname ne '') && ($udom ne '')) {
                   8443:         $uhome = &homeserver($uname,$udom);
                   8444:         return $uhome if ($uhome eq 'no_host');
                   8445:     } else {
                   8446:         $uname = $env{'user.name'};
                   8447:         $udom = $env{'user.domain'};
                   8448:         $uhome = $env{'user.home'};
                   8449:     }
1.620     albertel 8450:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8451:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8452:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8453:     return reply($command,$uhome);
1.12      www      8454:   } else {
                   8455:     return 'refused';
                   8456:   }
1.105     harris41 8457: }
                   8458: 
                   8459: # ---------------- Make a metadata query against the network of library servers
                   8460: 
                   8461: sub metadata_query {
1.1237    raeburn  8462:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8463:     my %rhash;
1.845     albertel 8464:     my %libserv = &all_library();
1.244     matthew  8465:     my @server_list = (defined($server_array) ? @$server_array
                   8466:                                               : keys(%libserv) );
                   8467:     for my $server (@server_list) {
1.1237    raeburn  8468:         my $domains = ''; 
                   8469:         if (ref($domains_hash) eq 'HASH') {
                   8470:             $domains = $domains_hash->{$server}; 
                   8471:         }
1.118     harris41 8472: 	unless ($custom or $customshow) {
1.1237    raeburn  8473: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8474: 	    $rhash{$server}=$reply;
                   8475: 	}
                   8476: 	else {
                   8477: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8478: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8479: 			     $server);
                   8480: 	    $rhash{$server}=$reply;
                   8481: 	}
1.112     harris41 8482:     }
1.118     harris41 8483:     return \%rhash;
1.240     www      8484: }
                   8485: 
                   8486: # ----------------------------------------- Send log queries and wait for reply
                   8487: 
                   8488: sub log_query {
                   8489:     my ($uname,$udom,$query,%filters)=@_;
                   8490:     my $uhome=&homeserver($uname,$udom);
                   8491:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8492:     my $uhost=&hostname($uhome);
1.800     albertel 8493:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8494:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8495:                        $uhome);
1.479     albertel 8496:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8497:     return get_query_reply($queryid);
                   8498: }
                   8499: 
1.818     raeburn  8500: # -------------------------- Update MySQL table for portfolio file
                   8501: 
                   8502: sub update_portfolio_table {
1.821     raeburn  8503:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8504:     if ($group ne '') {
                   8505:         $file_name =~s /^\Q$group\E//;
                   8506:     }
1.818     raeburn  8507:     my $homeserver = &homeserver($uname,$udom);
                   8508:     my $queryid=
1.821     raeburn  8509:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8510:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8511:     my $reply = &get_query_reply($queryid);
                   8512:     return $reply;
                   8513: }
                   8514: 
1.899     raeburn  8515: # -------------------------- Update MySQL allusers table
                   8516: 
                   8517: sub update_allusers_table {
                   8518:     my ($uname,$udom,$names) = @_;
                   8519:     my $homeserver = &homeserver($uname,$udom);
                   8520:     my $queryid=
                   8521:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8522:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8523:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8524:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8525:                'generation='.&escape($names->{'generation'}).'%%'.
                   8526:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8527:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8528:     return;
1.899     raeburn  8529: }
                   8530: 
1.508     raeburn  8531: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8532: 
                   8533: sub fetch_enrollment_query {
1.511     raeburn  8534:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8535:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8536:     my $maxtries = 1;
1.508     raeburn  8537:     if ($context eq 'automated') {
                   8538:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8539:         $sleep = 2;
                   8540:         $loopmax = 100;
1.547     raeburn  8541:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8542:     } else {
                   8543:         $homeserver = &homeserver($cnum,$dom);
                   8544:     }
1.838     albertel 8545:     my $host=&hostname($homeserver);
1.506     raeburn  8546:     my $cmd = '';
1.1000    raeburn  8547:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8548:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8549:     }
                   8550:     $cmd =~ s/%%$//;
                   8551:     $cmd = &escape($cmd);
                   8552:     my $query = 'fetchenrollment';
1.620     albertel 8553:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8554:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8555:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8556:         return 'error: '.$queryid;
                   8557:     }
1.1317    raeburn  8558:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8559:     my $tries = 1;
                   8560:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8561:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8562:         $tries ++;
                   8563:     }
1.526     raeburn  8564:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8565:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8566:     } else {
1.901     albertel 8567:         my @responses = split(/:/,$reply);
1.1322    raeburn  8568:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8569:             foreach my $line (@responses) {
                   8570:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8571:                 $$replyref{$key} = $value;
                   8572:             }
                   8573:         } else {
1.1117    foxr     8574:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8575:             foreach my $line (@responses) {
                   8576:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8577:                 $$replyref{$key} = $value;
                   8578:                 if ($value > 0) {
1.800     albertel 8579:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8580:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8581:                         my $destname = $pathname.'/'.$filename;
                   8582:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8583:                         if ($xml_classlist =~ /^error/) {
                   8584:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8585:                         } else {
1.1359    raeburn  8586:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8587:                                 print FILE &unescape($xml_classlist);
                   8588:                                 close(FILE);
1.526     raeburn  8589:                             } else {
                   8590:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8591:                             }
                   8592:                         }
                   8593:                     }
                   8594:                 }
                   8595:             }
                   8596:         }
                   8597:         return 'ok';
                   8598:     }
                   8599:     return 'error';
                   8600: }
                   8601: 
1.242     www      8602: sub get_query_reply {
1.1317    raeburn  8603:     my ($queryid,$sleep,$loopmax) = @_;;
                   8604:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8605:         $sleep = 0.2;
                   8606:     }
                   8607:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8608:         $loopmax = 100;
                   8609:     }
1.1117    foxr     8610:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8611:     my $reply='';
1.1317    raeburn  8612:     for (1..$loopmax) {
                   8613: 	sleep($sleep);
1.240     www      8614:         if (-e $replyfile.'.end') {
1.1359    raeburn  8615: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8616: 		$reply = join('',<$fh>);
                   8617: 		close($fh);
1.240     www      8618: 	   } else { return 'error: reply_file_error'; }
1.242     www      8619:            return &unescape($reply);
                   8620: 	}
1.240     www      8621:     }
1.242     www      8622:     return 'timeout:'.$queryid;
1.240     www      8623: }
                   8624: 
                   8625: sub courselog_query {
1.241     www      8626: #
                   8627: # possible filters:
                   8628: # url: url or symb
                   8629: # username
                   8630: # domain
                   8631: # action: view, submit, grade
                   8632: # start: timestamp
                   8633: # end: timestamp
                   8634: #
1.240     www      8635:     my (%filters)=@_;
1.620     albertel 8636:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8637:     if ($filters{'url'}) {
                   8638: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8639:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8640:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8641:     }
1.620     albertel 8642:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8643:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8644:     return &log_query($cname,$cdom,'courselog',%filters);
                   8645: }
                   8646: 
                   8647: sub userlog_query {
1.858     raeburn  8648: #
                   8649: # possible filters:
                   8650: # action: log check role
                   8651: # start: timestamp
                   8652: # end: timestamp
                   8653: #
1.240     www      8654:     my ($uname,$udom,%filters)=@_;
                   8655:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8656: }
                   8657: 
1.506     raeburn  8658: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8659: 
                   8660: sub auto_run {
1.508     raeburn  8661:     my ($cnum,$cdom) = @_;
1.876     raeburn  8662:     my $response = 0;
                   8663:     my $settings;
                   8664:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8665:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8666:         $settings = $domconfig{'autoenroll'};
                   8667:         if ($settings->{'run'} eq '1') {
                   8668:             $response = 1;
                   8669:         }
                   8670:     } else {
1.934     raeburn  8671:         my $homeserver;
                   8672:         if (&is_course($cdom,$cnum)) {
                   8673:             $homeserver = &homeserver($cnum,$cdom);
                   8674:         } else {
                   8675:             $homeserver = &domain($cdom,'primary');
                   8676:         }
                   8677:         if ($homeserver ne 'no_host') {
                   8678:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8679:         }
1.876     raeburn  8680:     }
1.506     raeburn  8681:     return $response;
                   8682: }
1.776     albertel 8683: 
1.506     raeburn  8684: sub auto_get_sections {
1.508     raeburn  8685:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8686:     my $homeserver;
                   8687:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8688:         $homeserver = &homeserver($cnum,$cdom);
                   8689:     }
                   8690:     if (!defined($homeserver)) { 
                   8691:         if ($cdom =~ /^$match_domain$/) {
                   8692:             $homeserver = &domain($cdom,'primary');
                   8693:         }
                   8694:     }
                   8695:     my @secs;
                   8696:     if (defined($homeserver)) {
                   8697:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8698:         unless ($response eq 'refused') {
                   8699:             @secs = split(/:/,$response);
                   8700:         }
1.506     raeburn  8701:     }
                   8702:     return @secs;
                   8703: }
1.776     albertel 8704: 
1.506     raeburn  8705: sub auto_new_course {
1.1099    raeburn  8706:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8707:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8708:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8709:     return $response;
                   8710: }
1.776     albertel 8711: 
1.506     raeburn  8712: sub auto_validate_courseID {
1.508     raeburn  8713:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8714:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8715:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8716:     return $response;
                   8717: }
1.776     albertel 8718: 
1.1007    raeburn  8719: sub auto_validate_instcode {
1.1020    raeburn  8720:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8721:     my ($homeserver,$response);
                   8722:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8723:         $homeserver = &homeserver($cnum,$cdom);
                   8724:     }
                   8725:     if (!defined($homeserver)) {
                   8726:         if ($cdom =~ /^$match_domain$/) {
                   8727:             $homeserver = &domain($cdom,'primary');
                   8728:         }
                   8729:     }
1.1065    raeburn  8730:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8731:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8732:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8733:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8734: }
                   8735: 
1.506     raeburn  8736: sub auto_create_password {
1.873     raeburn  8737:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8738:     my ($homeserver,$response);
1.506     raeburn  8739:     my $create_passwd = 0;
                   8740:     my $authchk = '';
1.873     raeburn  8741:     if ($udom =~ /^$match_domain$/) {
                   8742:         $homeserver = &domain($udom,'primary');
                   8743:     }
                   8744:     if ($homeserver eq '') {
                   8745:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8746:             $homeserver = &homeserver($cnum,$cdom);
                   8747:         }
                   8748:     }
                   8749:     if ($homeserver eq '') {
                   8750:         $authchk = 'nodomain';
1.506     raeburn  8751:     } else {
1.873     raeburn  8752:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8753:         if ($response eq 'refused') {
                   8754:             $authchk = 'refused';
                   8755:         } else {
1.901     albertel 8756:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8757:         }
1.506     raeburn  8758:     }
                   8759:     return ($authparam,$create_passwd,$authchk);
                   8760: }
                   8761: 
1.706     raeburn  8762: sub auto_photo_permission {
                   8763:     my ($cnum,$cdom,$students) = @_;
                   8764:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8765:     my ($outcome,$perm_reqd,$conditions) = 
                   8766: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8767:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8768: 	return (undef,undef);
                   8769:     }
1.706     raeburn  8770:     return ($outcome,$perm_reqd,$conditions);
                   8771: }
                   8772: 
                   8773: sub auto_checkphotos {
                   8774:     my ($uname,$udom,$pid) = @_;
                   8775:     my $homeserver = &homeserver($uname,$udom);
                   8776:     my ($result,$resulttype);
                   8777:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8778: 				   &escape($uname).':'.&escape($pid),
                   8779: 				   $homeserver));
1.709     albertel 8780:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8781: 	return (undef,undef);
                   8782:     }
1.706     raeburn  8783:     if ($outcome) {
                   8784:         ($result,$resulttype) = split(/:/,$outcome);
                   8785:     } 
                   8786:     return ($result,$resulttype);
                   8787: }
                   8788: 
                   8789: sub auto_photochoice {
                   8790:     my ($cnum,$cdom) = @_;
                   8791:     my $homeserver = &homeserver($cnum,$cdom);
                   8792:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8793: 						       &escape($cdom),
                   8794: 						       $homeserver)));
1.709     albertel 8795:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8796: 	return (undef,undef);
                   8797:     }
1.706     raeburn  8798:     return ($update,$comment);
                   8799: }
                   8800: 
                   8801: sub auto_photoupdate {
                   8802:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8803:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8804:     my $host=&hostname($homeserver);
1.706     raeburn  8805:     my $cmd = '';
                   8806:     my $maxtries = 1;
1.800     albertel 8807:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8808:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8809:     }
                   8810:     $cmd =~ s/%%$//;
                   8811:     $cmd = &escape($cmd);
                   8812:     my $query = 'institutionalphotos';
                   8813:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8814:     unless ($queryid=~/^\Q$host\E\_/) {
                   8815:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8816:         return 'error: '.$queryid;
                   8817:     }
                   8818:     my $reply = &get_query_reply($queryid);
                   8819:     my $tries = 1;
                   8820:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8821:         $reply = &get_query_reply($queryid);
                   8822:         $tries ++;
                   8823:     }
                   8824:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8825:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8826:     } else {
                   8827:         my @responses = split(/:/,$reply);
                   8828:         my $outcome = shift(@responses); 
                   8829:         foreach my $item (@responses) {
                   8830:             my ($key,$value) = split(/=/,$item);
                   8831:             $$photo{$key} = $value;
                   8832:         }
                   8833:         return $outcome;
                   8834:     }
                   8835:     return 'error';
                   8836: }
                   8837: 
1.521     raeburn  8838: sub auto_instcode_format {
1.793     albertel 8839:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8840: 	$cat_order) = @_;
1.521     raeburn  8841:     my $courses = '';
1.772     raeburn  8842:     my @homeservers;
1.521     raeburn  8843:     if ($caller eq 'global') {
1.841     albertel 8844: 	my %servers = &get_servers($codedom,'library');
                   8845: 	foreach my $tryserver (keys(%servers)) {
                   8846: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8847: 		push(@homeservers,$tryserver);
                   8848: 	    }
1.584     raeburn  8849:         }
1.1022    raeburn  8850:     } elsif ($caller eq 'requests') {
                   8851:         if ($codedom =~ /^$match_domain$/) {
                   8852:             my $chome = &domain($codedom,'primary');
                   8853:             unless ($chome eq 'no_host') {
                   8854:                 push(@homeservers,$chome);
                   8855:             }
                   8856:         }
1.521     raeburn  8857:     } else {
1.772     raeburn  8858:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8859:     }
1.793     albertel 8860:     foreach my $code (keys(%{$instcodes})) {
                   8861:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8862:     }
                   8863:     chop($courses);
1.772     raeburn  8864:     my $ok_response = 0;
                   8865:     my $response;
                   8866:     while (@homeservers > 0 && $ok_response == 0) {
                   8867:         my $server = shift(@homeservers); 
                   8868:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8869:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8870:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8871: 		split(/:/,$response);
1.772     raeburn  8872:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8873:             push(@{$codetitles},&str2array($codetitles_str));
                   8874:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8875:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8876:             $ok_response = 1;
                   8877:         }
                   8878:     }
                   8879:     if ($ok_response) {
1.521     raeburn  8880:         return 'ok';
1.772     raeburn  8881:     } else {
                   8882:         return $response;
1.521     raeburn  8883:     }
                   8884: }
                   8885: 
1.792     raeburn  8886: sub auto_instcode_defaults {
                   8887:     my ($domain,$returnhash,$code_order) = @_;
                   8888:     my @homeservers;
1.841     albertel 8889: 
                   8890:     my %servers = &get_servers($domain,'library');
                   8891:     foreach my $tryserver (keys(%servers)) {
                   8892: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8893: 	    push(@homeservers,$tryserver);
                   8894: 	}
1.792     raeburn  8895:     }
1.841     albertel 8896: 
1.792     raeburn  8897:     my $response;
1.841     albertel 8898:     foreach my $server (@homeservers) {
1.792     raeburn  8899:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8900:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8901: 	
                   8902: 	foreach my $pair (split(/\&/,$response)) {
                   8903: 	    my ($name,$value)=split(/\=/,$pair);
                   8904: 	    if ($name eq 'code_order') {
                   8905: 		@{$code_order} = split(/\&/,&unescape($value));
                   8906: 	    } else {
                   8907: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8908: 	    }
                   8909: 	}
                   8910: 	return 'ok';
1.792     raeburn  8911:     }
1.841     albertel 8912: 
                   8913:     return $response;
1.1003    raeburn  8914: }
                   8915: 
                   8916: sub auto_possible_instcodes {
1.1007    raeburn  8917:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8918:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8919:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8920:         return;
                   8921:     }
1.1003    raeburn  8922:     my (@homeservers,$uhome);
                   8923:     if (defined(&domain($domain,'primary'))) {
                   8924:         $uhome=&domain($domain,'primary');
                   8925:         push(@homeservers,&domain($domain,'primary'));
                   8926:     } else {
                   8927:         my %servers = &get_servers($domain,'library');
                   8928:         foreach my $tryserver (keys(%servers)) {
                   8929:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8930:                 push(@homeservers,$tryserver);
                   8931:             }
                   8932:         }
                   8933:     }
                   8934:     my $response;
                   8935:     foreach my $server (@homeservers) {
                   8936:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8937:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8938:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8939:             split(':',$response);
                   8940:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8941:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8942:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8943:             my ($name,$value)=split('=',$item);
                   8944:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8945:         }
                   8946:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8947:             my ($name,$value)=split('=',$item);
                   8948:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8949:         }
                   8950:         return 'ok';
                   8951:     }
                   8952:     return $response;
                   8953: }
1.792     raeburn  8954: 
1.1010    raeburn  8955: sub auto_courserequest_checks {
                   8956:     my ($dom) = @_;
1.1020    raeburn  8957:     my ($homeserver,%validations);
                   8958:     if ($dom =~ /^$match_domain$/) {
                   8959:         $homeserver = &domain($dom,'primary');
                   8960:     }
                   8961:     unless ($homeserver eq 'no_host') {
                   8962:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8963:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8964:             my @items = split(/&/,$response);
                   8965:             foreach my $item (@items) {
                   8966:                 my ($key,$value) = split('=',$item);
                   8967:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8968:             }
                   8969:         }
                   8970:     }
1.1010    raeburn  8971:     return %validations; 
                   8972: }
                   8973: 
1.1020    raeburn  8974: sub auto_courserequest_validation {
1.1255    raeburn  8975:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8976:     my ($homeserver,$response);
                   8977:     if ($dom =~ /^$match_domain$/) {
                   8978:         $homeserver = &domain($dom,'primary');
                   8979:     }
1.1255    raeburn  8980:     unless ($homeserver eq 'no_host') {
                   8981:         my $customdata;
                   8982:         if (ref($custominfo) eq 'HASH') {
                   8983:             $customdata = &freeze_escape($custominfo);
                   8984:         }
1.1020    raeburn  8985:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8986:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8987:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8988:                                     $customdata,$homeserver));
1.1020    raeburn  8989:     }
                   8990:     return $response;
                   8991: }
                   8992: 
1.777     albertel 8993: sub auto_validate_class_sec {
1.918     raeburn  8994:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8995:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8996:     my $ownerlist;
                   8997:     if (ref($owners) eq 'ARRAY') {
                   8998:         $ownerlist = join(',',@{$owners});
                   8999:     } else {
                   9000:         $ownerlist = $owners;
                   9001:     }
1.773     raeburn  9002:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9003:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9004:     return $response;
                   9005: }
                   9006: 
1.1367    raeburn  9007: sub auto_validate_instclasses {
                   9008:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9009:     my ($homeserver,%validations);
                   9010:     $homeserver = &homeserver($cnum,$cdom);
                   9011:     unless ($homeserver eq 'no_host') {
                   9012:         my $ownerlist;
                   9013:         if (ref($owners) eq 'ARRAY') {
                   9014:             $ownerlist = join(',',@{$owners});
                   9015:         } else {
                   9016:             $ownerlist = $owners;
                   9017:         }
                   9018:         if (ref($classesref) eq 'HASH') {
                   9019:             my $classes = &freeze_escape($classesref);
                   9020:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9021:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9022:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9023:                 my @items = split(/&/,$response);
                   9024:                 foreach my $item (@items) {
                   9025:                     my ($key,$value) = split('=',$item);
                   9026:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9027:                 }
                   9028:             }
                   9029:         }
                   9030:     }
                   9031:     return %validations;
                   9032: }
                   9033: 
1.1248    raeburn  9034: sub auto_crsreq_update {
                   9035:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9036:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9037:     my ($homeserver,%crsreqresponse);
                   9038:     if ($cdom =~ /^$match_domain$/) {
                   9039:         $homeserver = &domain($cdom,'primary');
                   9040:     }
                   9041:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9042:         my $info;
                   9043:         if (ref($inbound) eq 'HASH') {
                   9044:             $info = &freeze_escape($inbound);
                   9045:         }
                   9046:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9047:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9048:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9049:                             &escape($title).':'.&escape($code).':'.
                   9050:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9051:                             $homeserver);
1.1248    raeburn  9052:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9053:             my @items = split(/&/,$response);
                   9054:             foreach my $item (@items) {
                   9055:                 my ($key,$value) = split('=',$item);
                   9056:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9057:             }
                   9058:         }
                   9059:     }
                   9060:     return \%crsreqresponse;
                   9061: }
                   9062: 
1.1305    raeburn  9063: sub auto_export_grades {
1.1309    raeburn  9064:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9065:     my ($homeserver,%exportresponse);
                   9066:     if ($cdom =~ /^$match_domain$/) {
                   9067:         $homeserver = &domain($cdom,'primary');
                   9068:     }
                   9069:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9070:         my $info;
                   9071:         if (ref($inforef) eq 'HASH') {
                   9072:             $info = &freeze_escape($inforef);
                   9073:         }
                   9074:         if (ref($gradesref) eq 'HASH') {
                   9075:             my $grades = &freeze_escape($gradesref);
                   9076:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9077:                                 $info.':'.$grades,$homeserver);
                   9078:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9079:                 my @items = split(/&/,$response);
                   9080:                 foreach my $item (@items) {
                   9081:                     my ($key,$value) = split('=',$item);
                   9082:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9083:                 }
                   9084:             }
                   9085:         }
                   9086:     }
                   9087:     return \%exportresponse;
1.1305    raeburn  9088: }
                   9089: 
1.1287    raeburn  9090: sub check_instcode_cloning {
                   9091:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9092:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9093:         return;
                   9094:     }
                   9095:     my $canclone;
                   9096:     if (@{$code_order} > 0) {
                   9097:         my $instcoderegexp ='^';
                   9098:         my @clonecodes = split(/\&/,$cloner);
                   9099:         foreach my $item (@{$code_order}) {
                   9100:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9101:                 foreach my $pair (@clonecodes) {
                   9102:                     my ($key,$val) = split(/\=/,$pair,2);
                   9103:                     $val = &unescape($val);
                   9104:                     if ($key eq $item) {
                   9105:                         $instcoderegexp .= '('.$val.')';
                   9106:                         last;
                   9107:                     }
                   9108:                 }
                   9109:             } else {
                   9110:                 $instcoderegexp .= $codedefaults->{$item};
                   9111:             }
                   9112:         }
                   9113:         $instcoderegexp .= '$';
                   9114:         my (@from,@to);
                   9115:         eval {
                   9116:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9117:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9118:         };
                   9119:         if ((@from > 0) && (@to > 0)) {
                   9120:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9121:             if (!@diffs) {
                   9122:                 $canclone = 1;
                   9123:             }
                   9124:         }
                   9125:     }
                   9126:     return $canclone;
                   9127: }
                   9128: 
                   9129: sub default_instcode_cloning {
                   9130:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9131:     my (%codedefaults,@code_order,$canclone);
                   9132:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9133:         %codedefaults = %{$codedefaultsref};
                   9134:         @code_order = @{$codeorderref};
                   9135:     } elsif ($clonedom) {
                   9136:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9137:     }
                   9138:     if (($domdefclone) && (@code_order)) {
                   9139:         my @clonecodes = split(/\+/,$domdefclone);
                   9140:         my $instcoderegexp ='^';
                   9141:         foreach my $item (@code_order) {
                   9142:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9143:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9144:             } else {
                   9145:                 $instcoderegexp .= $codedefaults{$item};
                   9146:             }
                   9147:         }
                   9148:         $instcoderegexp .= '$';
                   9149:         my (@from,@to);
                   9150:         eval {
                   9151:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9152:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9153:         };
                   9154:         if ((@from > 0) && (@to > 0)) {
                   9155:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9156:             if (!@diffs) {
                   9157:                 $canclone = 1;
                   9158:             }
                   9159:         }
                   9160:     }
                   9161:     return $canclone;
                   9162: }
                   9163: 
1.679     raeburn  9164: # ------------------------------------------------------- Course Group routines
                   9165: 
                   9166: sub get_coursegroups {
1.809     raeburn  9167:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9168:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9169: }
                   9170: 
1.679     raeburn  9171: sub modify_coursegroup {
                   9172:     my ($cdom,$cnum,$groupsettings) = @_;
                   9173:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9174: }
                   9175: 
1.809     raeburn  9176: sub toggle_coursegroup_status {
                   9177:     my ($cdom,$cnum,$group,$action) = @_;
                   9178:     my ($from_namespace,$to_namespace);
                   9179:     if ($action eq 'delete') {
                   9180:         $from_namespace = 'coursegroups';
                   9181:         $to_namespace = 'deleted_groups';
                   9182:     } else {
                   9183:         $from_namespace = 'deleted_groups';
                   9184:         $to_namespace = 'coursegroups';
                   9185:     }
                   9186:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9187:     if (my $tmp = &error(%curr_group)) {
                   9188:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9189:         return ('read error',$tmp);
                   9190:     } else {
                   9191:         my %savedsettings = %curr_group; 
1.809     raeburn  9192:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9193:         my $deloutcome;
                   9194:         if ($result eq 'ok') {
1.809     raeburn  9195:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9196:         } else {
                   9197:             return ('write error',$result);
                   9198:         }
                   9199:         if ($deloutcome eq 'ok') {
                   9200:             return 'ok';
                   9201:         } else {
                   9202:             return ('delete error',$deloutcome);
                   9203:         }
                   9204:     }
                   9205: }
                   9206: 
1.679     raeburn  9207: sub modify_group_roles {
1.957     raeburn  9208:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9209:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9210:     my $role = 'gr/'.&escape($userprivs);
                   9211:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9212:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9213:     if ($result eq 'ok') {
                   9214:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9215:     }
1.679     raeburn  9216:     return $result;
                   9217: }
                   9218: 
                   9219: sub modify_coursegroup_membership {
                   9220:     my ($cdom,$cnum,$membership) = @_;
                   9221:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9222:     return $result;
                   9223: }
                   9224: 
1.682     raeburn  9225: sub get_active_groups {
                   9226:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9227:     my $now = time;
                   9228:     my %groups = ();
                   9229:     foreach my $key (keys(%env)) {
1.811     albertel 9230:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9231:             my ($start,$end) = split(/\./,$env{$key});
                   9232:             if (($end!=0) && ($end<$now)) { next; }
                   9233:             if (($start!=0) && ($start>$now)) { next; }
                   9234:             if ($1 eq $cdom && $2 eq $cnum) {
                   9235:                 $groups{$3} = $env{$key} ;
                   9236:             }
                   9237:         }
                   9238:     }
                   9239:     return %groups;
                   9240: }
                   9241: 
1.683     raeburn  9242: sub get_group_membership {
                   9243:     my ($cdom,$cnum,$group) = @_;
                   9244:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9245: }
                   9246: 
                   9247: sub get_users_groups {
                   9248:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9249:     my @usersgroups;
1.683     raeburn  9250:     my $cachetime=1800;
                   9251: 
                   9252:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9253:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9254:     if (defined($cached)) {
1.734     albertel 9255:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9256:     } else {  
                   9257:         $grouplist = '';
1.816     raeburn  9258:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9259:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9260:         my $access_end = $env{'course.'.$courseid.
                   9261:                               '.default_enrollment_end_date'};
                   9262:         my $now = time;
                   9263:         foreach my $key (keys(%roleshash)) {
                   9264:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9265:                 my $group = $1;
                   9266:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9267:                     my $start = $2;
                   9268:                     my $end = $1;
                   9269:                     if ($start == -1) { next; } # deleted from group
                   9270:                     if (($start!=0) && ($start>$now)) { next; }
                   9271:                     if (($end!=0) && ($end<$now)) {
                   9272:                         if ($access_end && $access_end < $now) {
                   9273:                             if ($access_end - $end < 86400) {
                   9274:                                 push(@usersgroups,$group);
1.733     raeburn  9275:                             }
                   9276:                         }
1.817     raeburn  9277:                         next;
1.733     raeburn  9278:                     }
1.817     raeburn  9279:                     push(@usersgroups,$group);
1.683     raeburn  9280:                 }
                   9281:             }
                   9282:         }
1.817     raeburn  9283:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9284:         $grouplist = join(':',@usersgroups);
                   9285:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9286:     }
1.733     raeburn  9287:     return @usersgroups;
1.683     raeburn  9288: }
                   9289: 
                   9290: sub devalidate_getgroups_cache {
                   9291:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9292:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9293: 
1.683     raeburn  9294:     my $hashid="$udom:$uname:$courseid";
                   9295:     &devalidate_cache_new('getgroups',$hashid);
                   9296: }
                   9297: 
1.12      www      9298: # ------------------------------------------------------------------ Plain Text
                   9299: 
                   9300: sub plaintext {
1.988     raeburn  9301:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9302:     if ($short =~ m{^cr/}) {
1.758     albertel 9303: 	return (split('/',$short))[-1];
                   9304:     }
1.742     raeburn  9305:     if (!defined($cid)) {
                   9306:         $cid = $env{'request.course.id'};
                   9307:     }
                   9308:     my %rolenames = (
1.1008    raeburn  9309:                       Course    => 'std',
                   9310:                       Community => 'alt1',
1.1305    raeburn  9311:                       Placement => 'std',
1.742     raeburn  9312:                     );
1.1037    raeburn  9313:     if ($cid ne '') {
                   9314:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9315:             unless ($forcedefault) {
                   9316:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9317:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9318:                 return &Apache::lonlocal::mt($roletext);
                   9319:             }
                   9320:         }
                   9321:     }
                   9322:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9323:         (defined($rolenames{$type})) && 
                   9324:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9325:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9326:     } elsif ($cid ne '') {
                   9327:         my $crstype = $env{'course.'.$cid.'.type'};
                   9328:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9329:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9330:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9331:         }
1.742     raeburn  9332:     }
1.1037    raeburn  9333:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9334: }
                   9335: 
                   9336: # ----------------------------------------------------------------- Assign Role
                   9337: 
                   9338: sub assignrole {
1.957     raeburn  9339:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9340:         $context)=@_;
1.21      www      9341:     my $mrole;
                   9342:     if ($role =~ /^cr\//) {
1.393     www      9343:         my $cwosec=$url;
1.811     albertel 9344:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9345: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9346:            my $refused = 1;
                   9347:            if ($context eq 'requestcourses') {
                   9348:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9349:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9350:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9351:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9352:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9353:                            if ($crsenv{'internal.courseowner'} eq
                   9354:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9355:                                $refused = '';
                   9356:                            }
                   9357:                        }
                   9358:                    }
                   9359:                }
                   9360:            }
                   9361:            if ($refused) {
                   9362:                &logthis('Refused custom assignrole: '.
                   9363:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9364:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9365:                return 'refused';
                   9366:            }
1.104     www      9367:         }
1.21      www      9368:         $mrole='cr';
1.678     raeburn  9369:     } elsif ($role =~ /^gr\//) {
                   9370:         my $cwogrp=$url;
1.811     albertel 9371:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9372:         unless (&allowed('mdg',$cwogrp)) {
                   9373:             &logthis('Refused group assignrole: '.
                   9374:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9375:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9376:             return 'refused';
                   9377:         }
                   9378:         $mrole='gr';
1.21      www      9379:     } else {
1.82      www      9380:         my $cwosec=$url;
1.811     albertel 9381:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9382:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9383:             my $refused;
                   9384:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9385:                 if (!(&allowed('c'.$role,$url))) {
                   9386:                     $refused = 1;
                   9387:                 }
                   9388:             } else {
                   9389:                 $refused = 1;
                   9390:             }
1.947     raeburn  9391:             if ($refused) {
1.1045    raeburn  9392:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9393:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9394:                     my %crsenv;
                   9395:                     if ($role eq 'cc' || $role eq 'co') {
                   9396:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9397:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9398:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9399:                                 if ($crsenv{'internal.courseowner'} eq 
                   9400:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9401:                                     $refused = '';
                   9402:                                 }
                   9403:                             }
                   9404:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9405:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9406:                                 if ($crsenv{'internal.courseowner'} eq 
                   9407:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9408:                                     $refused = '';
                   9409:                                 }
                   9410:                             }
                   9411:                         }
                   9412:                     }
1.1368    raeburn  9413:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9414:                     if ($role eq 'st') {
                   9415:                         $refused = '';
1.1377    raeburn  9416:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9417:                         $refused = '';
                   9418:                     }
1.1017    raeburn  9419:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9420:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9421:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9422:                         my $wrongcc;
                   9423:                         if ($cnum =~ /^$match_community$/) {
                   9424:                             $wrongcc = 1 if ($role eq 'cc');
                   9425:                         } else {
                   9426:                             $wrongcc = 1 if ($role eq 'co');
                   9427:                         }
                   9428:                         unless ($wrongcc) {
                   9429:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9430:                             if ($crsenv{'internal.courseowner'} eq 
                   9431:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9432:                                 $refused = '';
                   9433:                             }
1.1017    raeburn  9434:                         }
                   9435:                     }
1.1183    raeburn  9436:                 } elsif ($context eq 'requestauthor') {
                   9437:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9438:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9439:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9440:                             $refused = '';
                   9441:                         } else {
                   9442:                             my %domdefaults = &get_domain_defaults($udom);
                   9443:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9444:                                 my $checkbystatus;
                   9445:                                 if ($env{'user.adv'}) { 
                   9446:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9447:                                     if ($disposition eq 'automatic') {
                   9448:                                         $refused = '';
                   9449:                                     } elsif ($disposition eq '') {
                   9450:                                         $checkbystatus = 1;
                   9451:                                     } 
                   9452:                                 } else {
                   9453:                                     $checkbystatus = 1;
                   9454:                                 }
                   9455:                                 if ($checkbystatus) {
                   9456:                                     if ($env{'environment.inststatus'}) {
                   9457:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9458:                                         foreach my $type (@inststatuses) {
                   9459:                                             if (($type ne '') &&
                   9460:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9461:                                                 $refused = '';
                   9462:                                             }
                   9463:                                         }
                   9464:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9465:                                         $refused = '';
                   9466:                                     }
                   9467:                                 }
                   9468:                             }
                   9469:                         }
                   9470:                     }
1.1017    raeburn  9471:                 }
                   9472:                 if ($refused) {
1.947     raeburn  9473:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9474:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9475: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9476:                     return 'refused';
                   9477:                 }
1.932     raeburn  9478:             }
1.1131    raeburn  9479:         } elsif ($role eq 'au') {
                   9480:             if ($url ne '/'.$udom.'/') {
                   9481:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9482:                          ' to assign author role for '.$uname.':'.$udom.
                   9483:                          ' in domain: '.$url.' refused (wrong domain).');
                   9484:                 return 'refused';
                   9485:             }
1.104     www      9486:         }
1.21      www      9487:         $mrole=$role;
                   9488:     }
1.620     albertel 9489:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9490:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9491:     if ($end) { $command.='_'.$end; }
1.21      www      9492:     if ($start) {
                   9493: 	if ($end) { 
1.81      www      9494:            $command.='_'.$start; 
1.21      www      9495:         } else {
1.81      www      9496:            $command.='_0_'.$start;
1.21      www      9497:         }
                   9498:     }
1.739     raeburn  9499:     my $origstart = $start;
                   9500:     my $origend = $end;
1.957     raeburn  9501:     my $delflag;
1.357     www      9502: # actually delete
                   9503:     if ($deleteflag) {
1.373     www      9504: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9505: # modify command to delete the role
1.620     albertel 9506:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9507:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9508: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9509: # set start and finish to negative values for userrolelog
                   9510:            $start=-1;
                   9511:            $end=-1;
1.957     raeburn  9512:            $delflag = 1;
1.357     www      9513:         }
                   9514:     }
                   9515: # send command
1.349     www      9516:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9517: # log new user role if status is ok
1.349     www      9518:     if ($answer eq 'ok') {
1.663     raeburn  9519: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9520:         if (($role eq 'cc') || ($role eq 'in') ||
                   9521:             ($role eq 'ep') || ($role eq 'ad') ||
                   9522:             ($role eq 'ta') || ($role eq 'st') ||
                   9523:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9524:             ($role eq 'co')) {
1.1200    raeburn  9525: # for course roles, perform group memberships changes triggered by role change.
                   9526:             unless ($role =~ /^gr/) {
                   9527:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9528:                                                  $origstart,$selfenroll,$context);
                   9529:             }
1.1184    raeburn  9530:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9531:                            $selfenroll,$context);
                   9532:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9533:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9534:                  ($role eq 'da')) {
1.1184    raeburn  9535:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9536:                            $context);
                   9537:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9538:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9539:                              $context); 
                   9540:         }
1.1053    raeburn  9541:         if ($role eq 'cc') {
                   9542:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9543:         }
1.349     www      9544:     }
                   9545:     return $answer;
1.169     harris41 9546: }
                   9547: 
1.1053    raeburn  9548: sub autoupdate_coowners {
                   9549:     my ($url,$end,$start,$uname,$udom) = @_;
                   9550:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9551:     if (($cdom ne '') && ($cnum ne '')) {
                   9552:         my $now = time;
                   9553:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9554:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9555:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9556:             my $instcode = $coursehash{'internal.coursecode'};
                   9557:             if ($instcode ne '') {
1.1056    raeburn  9558:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9559:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9560:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9561:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9562:                         if ($result eq 'valid') {
                   9563:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9564:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9565:                                     push(@newcoowners,$coowner);
                   9566:                                 }
                   9567:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9568:                                     push(@newcoowners,$uname.':'.$udom);
                   9569:                                 }
                   9570:                                 @newcoowners = sort(@newcoowners);
                   9571:                             } else {
                   9572:                                 push(@newcoowners,$uname.':'.$udom);
                   9573:                             }
                   9574:                         } else {
                   9575:                             if ($coursehash{'internal.co-owners'}) {
                   9576:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9577:                                     unless ($coowner eq $uname.':'.$udom) {
                   9578:                                         push(@newcoowners,$coowner);
                   9579:                                     }
                   9580:                                 }
                   9581:                                 unless (@newcoowners > 0) {
                   9582:                                     $delcoowners = 1;
                   9583:                                     $coowners = '';
                   9584:                                 }
                   9585:                             }
                   9586:                         }
                   9587:                         if (@newcoowners || $delcoowners) {
                   9588:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9589:                                             $delcoowners,@newcoowners);
                   9590:                         }
                   9591:                     }
                   9592:                 }
                   9593:             }
                   9594:         }
                   9595:     }
                   9596: }
                   9597: 
                   9598: sub store_coowners {
                   9599:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9600:     my $cid = $cdom.'_'.$cnum;
                   9601:     my ($coowners,$delresult,$putresult);
                   9602:     if (@newcoowners) {
                   9603:         $coowners = join(',',@newcoowners);
                   9604:         my %coownershash = (
                   9605:                             'internal.co-owners' => $coowners,
                   9606:                            );
                   9607:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9608:         if ($putresult eq 'ok') {
                   9609:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9610:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9611:             }
                   9612:         }
                   9613:     }
                   9614:     if ($delcoowners) {
                   9615:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9616:         if ($delresult eq 'ok') {
                   9617:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9618:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9619:             }
                   9620:         }
                   9621:     }
                   9622:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9623:         my %crsinfo =
                   9624:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9625:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9626:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9627:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9628:         }
                   9629:     }
                   9630: }
                   9631: 
1.169     harris41 9632: # -------------------------------------------------- Modify user authentication
1.197     www      9633: # Overrides without validation
                   9634: 
1.169     harris41 9635: sub modifyuserauth {
                   9636:     my ($udom,$uname,$umode,$upass)=@_;
                   9637:     my $uhome=&homeserver($uname,$udom);
1.197     www      9638:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9639:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9640:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9641:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9642:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9643: 		     &escape($upass),$uhome);
1.620     albertel 9644:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9645:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9646:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9647:     &log($udom,,$uname,$uhome,
1.620     albertel 9648:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9649:                                      $env{'user.name'}.', '.$umode.
1.197     www      9650:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9651:     unless ($reply eq 'ok') {
1.197     www      9652:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9653: 	return 'error: '.$reply;
                   9654:     }   
1.170     harris41 9655:     return 'ok';
1.80      www      9656: }
                   9657: 
1.81      www      9658: # --------------------------------------------------------------- Modify a user
1.80      www      9659: 
1.81      www      9660: sub modifyuser {
1.206     matthew  9661:     my ($udom,    $uname, $uid,
                   9662:         $umode,   $upass, $first,
                   9663:         $middle,  $last,  $gene,
1.1058    raeburn  9664:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9665:     $udom= &LONCAPA::clean_domain($udom);
                   9666:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9667:     my $showcandelete = 'none';
                   9668:     if (ref($candelete) eq 'ARRAY') {
                   9669:         if (@{$candelete} > 0) {
                   9670:             $showcandelete = join(', ',@{$candelete});
                   9671:         }
                   9672:     }
1.81      www      9673:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9674:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9675: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9676:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9677:                                      ' desiredhome not specified'). 
1.620     albertel 9678:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9679:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9680:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9681:     my $newuser;
                   9682:     if ($uhome eq 'no_host') {
                   9683:         $newuser = 1;
1.1368    raeburn  9684:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9685:                 ($umode eq 'lti')) {
                   9686:             return 'error: more information needed to create new user';
                   9687:         }
1.1075    raeburn  9688:     }
1.80      www      9689: # ----------------------------------------------------------------- Create User
1.406     albertel 9690:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9691: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9692:         my $unhome='';
1.844     albertel 9693:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9694:             $unhome = $desiredhome;
1.620     albertel 9695: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9696: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9697:         } else { # load balancing routine for determining $unhome
1.81      www      9698:             my $loadm=10000000;
1.841     albertel 9699: 	    my %servers = &get_servers($udom,'library');
                   9700: 	    foreach my $tryserver (keys(%servers)) {
                   9701: 		my $answer=reply('load',$tryserver);
                   9702: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9703: 		    $loadm=$answer;
                   9704: 		    $unhome=$tryserver;
                   9705: 		}
1.80      www      9706: 	    }
                   9707:         }
                   9708:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9709: 	    return 'error: unable to find a home server for '.$uname.
                   9710:                    ' in domain '.$udom;
1.80      www      9711:         }
                   9712:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9713:                          &escape($upass),$unhome);
                   9714: 	unless ($reply eq 'ok') {
                   9715:             return 'error: '.$reply;
                   9716:         }   
1.230     stredwic 9717:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9718:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9719: 	    return 'error: unable verify users home machine.';
1.80      www      9720:         }
1.209     matthew  9721:     }   # End of creation of new user
1.80      www      9722: # ---------------------------------------------------------------------- Add ID
                   9723:     if ($uid) {
                   9724:        $uid=~tr/A-Z/a-z/;
                   9725:        my %uidhash=&idrget($udom,$uname);
1.196     www      9726:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9727:          && (!$forceid)) {
1.80      www      9728: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9729: 	      return 'error: user id "'.$uid.'" does not match '.
                   9730:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9731:           }
                   9732:        } else {
1.1300    raeburn  9733: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9734:        }
                   9735:     }
                   9736: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9737:     my @tmp=&get('environment',
1.899     raeburn  9738: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9739:                     'permanentemail','inststatus'],
1.134     albertel 9740: 		   $udom,$uname);
1.1075    raeburn  9741:     my (%names,%oldnames);
1.313     matthew  9742:     if ($tmp[0] =~ m/^error:.*/) { 
                   9743:         %names=(); 
                   9744:     } else {
                   9745:         %names = @tmp;
1.1075    raeburn  9746:         %oldnames = %names;
1.313     matthew  9747:     }
1.388     www      9748: #
1.1058    raeburn  9749: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9750: # of users did not contain them), do not overwrite existing values
                   9751: # unless field is in $candelete array ref.  
                   9752: #
                   9753: 
                   9754:     my @fields = ('firstname','middlename','lastname','generation',
                   9755:                   'permanentemail','id');
                   9756:     my %newvalues;
                   9757:     if (ref($candelete) eq 'ARRAY') {
                   9758:         foreach my $field (@fields) {
                   9759:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9760:                 if ($field eq 'firstname') {
                   9761:                     $names{$field} = $first;
                   9762:                 } elsif ($field eq 'middlename') {
                   9763:                     $names{$field} = $middle;
                   9764:                 } elsif ($field eq 'lastname') {
                   9765:                     $names{$field} = $last;
                   9766:                 } elsif ($field eq 'generation') { 
                   9767:                     $names{$field} = $gene;
                   9768:                 } elsif ($field eq 'permanentemail') {
                   9769:                     $names{$field} = $email;
                   9770:                 } elsif ($field eq 'id') {
                   9771:                     $names{$field}  = $uid;
                   9772:                 }
                   9773:             }
                   9774:         }
                   9775:     }
1.388     www      9776:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9777:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9778:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9779:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9780:     if ($email) {
                   9781:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9782:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9783:     }
1.899     raeburn  9784:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9785:     if (defined($inststatus)) {
                   9786:         $names{'inststatus'} = '';
                   9787:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9788:         if (ref($usertypes) eq 'HASH') {
                   9789:             my @okstatuses; 
                   9790:             foreach my $item (split(/:/,$inststatus)) {
                   9791:                 if (defined($usertypes->{$item})) {
                   9792:                     push(@okstatuses,$item);  
                   9793:                 }
                   9794:             }
                   9795:             if (@okstatuses) {
                   9796:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9797:             }
                   9798:         }
                   9799:     }
1.1075    raeburn  9800:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9801:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9802:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9803:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9804:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9805:     } else {
                   9806:         $logmsg .= ' during self creation';
                   9807:     }
1.1075    raeburn  9808:     my $changed;
                   9809:     if ($newuser) {
                   9810:         $changed = 1;
                   9811:     } else {
                   9812:         foreach my $field (@fields) {
                   9813:             if ($names{$field} ne $oldnames{$field}) {
                   9814:                 $changed = 1;
                   9815:                 last;
                   9816:             }
                   9817:         }
                   9818:     }
                   9819:     unless ($changed) {
                   9820:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9821:         &logthis($logmsg);
                   9822:         return 'ok';
                   9823:     }
                   9824:     my $reply = &put('environment', \%names, $udom,$uname);
                   9825:     if ($reply ne 'ok') { 
                   9826:         return 'error: '.$reply;
                   9827:     }
1.1087    raeburn  9828:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9829:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9830:     }
1.1075    raeburn  9831:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9832:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9833:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9834:     &logthis($logmsg);
1.134     albertel 9835:     return 'ok';
1.80      www      9836: }
                   9837: 
1.81      www      9838: # -------------------------------------------------------------- Modify student
1.80      www      9839: 
1.81      www      9840: sub modifystudent {
                   9841:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9842:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9843:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9844:     if (!$cid) {
1.620     albertel 9845: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9846: 	    return 'not_in_class';
                   9847: 	}
1.80      www      9848:     }
                   9849: # --------------------------------------------------------------- Make the user
1.81      www      9850:     my $reply=&modifyuser
1.209     matthew  9851: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9852:          $desiredhome,$email,$inststatus);
1.80      www      9853:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9854:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9855:     # student's environment
1.297     matthew  9856:     $uid = undef if (!$forceid);
1.455     albertel 9857:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9858:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9859:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9860:     return $reply;
                   9861: }
                   9862: 
                   9863: sub modify_student_enrollment {
1.1216    raeburn  9864:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9865:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9866:     my ($cdom,$cnum,$chome);
                   9867:     if (!$cid) {
1.620     albertel 9868: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9869: 	    return 'not_in_class';
                   9870: 	}
1.620     albertel 9871: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9872: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9873:     } else {
                   9874: 	($cdom,$cnum)=split(/_/,$cid);
                   9875:     }
1.620     albertel 9876:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9877:     if (!$chome) {
1.457     raeburn  9878: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9879:     }
1.455     albertel 9880:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9881:     # Make sure the user exists
1.81      www      9882:     my $uhome=&homeserver($uname,$udom);
                   9883:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9884: 	return 'error: no such user';
                   9885:     }
1.297     matthew  9886:     # Get student data if we were not given enough information
                   9887:     if (!defined($first)  || $first  eq '' || 
                   9888:         !defined($last)   || $last   eq '' || 
                   9889:         !defined($uid)    || $uid    eq '' || 
                   9890:         !defined($middle) || $middle eq '' || 
                   9891:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9892:         # They did not supply us with enough data to enroll the student, so
                   9893:         # we need to pick up more information.
1.297     matthew  9894:         my %tmp = &get('environment',
1.294     matthew  9895:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9896:                        ,$udom,$uname);
                   9897: 
1.800     albertel 9898:         #foreach my $key (keys(%tmp)) {
                   9899:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9900:         #}
1.294     matthew  9901:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9902:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9903:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9904:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9905:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9906:     }
1.556     albertel 9907:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9908:     my $user = "$uname:$udom";
                   9909:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9910:     my $reply=cput('classlist',
1.1148    raeburn  9911: 		   {$user => 
1.1314    raeburn  9912: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9913: 		   $cdom,$cnum);
1.1148    raeburn  9914:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9915:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9916:     } else { 
1.81      www      9917: 	return 'error: '.$reply;
                   9918:     }
1.297     matthew  9919:     # Add student role to user
1.83      www      9920:     my $uurl='/'.$cid;
1.81      www      9921:     $uurl=~s/\_/\//g;
                   9922:     if ($usec) {
                   9923: 	$uurl.='/'.$usec;
                   9924:     }
1.1148    raeburn  9925:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9926:                              $selfenroll,$context);
                   9927:     if ($result ne 'ok') {
                   9928:         if ($old_entry{$user} ne '') {
                   9929:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9930:         } else {
                   9931:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9932:         }
                   9933:     }
                   9934:     return $result; 
1.21      www      9935: }
                   9936: 
1.556     albertel 9937: sub format_name {
                   9938:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9939:     my $name;
                   9940:     if ($first ne 'lastname') {
                   9941: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9942:     } else {
                   9943: 	if ($lastname=~/\S/) {
                   9944: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9945: 	    $name=~s/\s+,/,/;
                   9946: 	} else {
                   9947: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9948: 	}
                   9949:     }
                   9950:     $name=~s/^\s+//;
                   9951:     $name=~s/\s+$//;
                   9952:     $name=~s/\s+/ /g;
                   9953:     return $name;
                   9954: }
                   9955: 
1.84      www      9956: # ------------------------------------------------- Write to course preferences
                   9957: 
                   9958: sub writecoursepref {
                   9959:     my ($courseid,%prefs)=@_;
                   9960:     $courseid=~s/^\///;
                   9961:     $courseid=~s/\_/\//g;
                   9962:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9963:     my $chome=homeserver($cnum,$cdomain);
                   9964:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9965: 	return 'error: no such course';
                   9966:     }
                   9967:     my $cstring='';
1.800     albertel 9968:     foreach my $pref (keys(%prefs)) {
                   9969: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9970:     }
1.84      www      9971:     $cstring=~s/\&$//;
                   9972:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9973: }
                   9974: 
                   9975: # ---------------------------------------------------------- Make/modify course
                   9976: 
                   9977: sub createcourse {
1.741     raeburn  9978:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9979:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9980:     $url=&declutter($url);
                   9981:     my $cid='';
1.1028    raeburn  9982:     if ($context eq 'requestcourses') {
                   9983:         my $can_create = 0;
                   9984:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9985:         if ($udom eq $ownerdom) {
                   9986:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9987:                                   $context)) {
                   9988:                 $can_create = 1;
                   9989:             }
                   9990:         } else {
                   9991:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9992:                                            $category);
                   9993:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9994:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9995:                 if (@curr > 0) {
                   9996:                     my @options = qw(approval validate autolimit);
                   9997:                     my $optregex = join('|',@options);
                   9998:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9999:                         $can_create = 1;
                   10000:                     }
                   10001:                 }
                   10002:             }
                   10003:         }
                   10004:         if ($can_create) {
                   10005:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10006:                 unless (&allowed('ccc',$udom)) {
                   10007:                     return 'refused'; 
                   10008:                 }
1.1017    raeburn  10009:             }
                   10010:         } else {
                   10011:             return 'refused';
                   10012:         }
1.1028    raeburn  10013:     } elsif (!&allowed('ccc',$udom)) {
                   10014:         return 'refused';
1.84      www      10015:     }
1.1011    raeburn  10016: # --------------------------------------------------------------- Get Unique ID
                   10017:     my $uname;
                   10018:     if ($cnum =~ /^$match_courseid$/) {
                   10019:         my $chome=&homeserver($cnum,$udom,'true');
                   10020:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10021:             $uname = $cnum;
                   10022:         } else {
1.1038    raeburn  10023:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10024:         }
                   10025:     } else {
1.1038    raeburn  10026:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10027:     }
                   10028:     return $uname if ($uname =~ /^error/);
                   10029: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10030:     if (!defined($course_server)) {
                   10031:         if (defined(&domain($udom,'primary'))) {
                   10032:             $course_server = &domain($udom,'primary');
                   10033:         } else {
                   10034:             $course_server = $env{'user.home'}; 
                   10035:         }
                   10036:     }
                   10037:     my %host_servers =
                   10038:         &Apache::lonnet::get_servers($udom,'library');
                   10039:     unless ($host_servers{$course_server}) {
                   10040:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10041:     }
1.84      www      10042: # ------------------------------------------------------------- Make the course
                   10043:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10044:                       $course_server);
1.84      www      10045:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10046:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10047:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10048: 	return 'error: no such course';
                   10049:     }
1.271     www      10050: # ----------------------------------------------------------------- Course made
1.516     raeburn  10051: # log existence
1.1029    raeburn  10052:     my $now = time;
1.918     raeburn  10053:     my $newcourse = {
                   10054:                     $udom.'_'.$uname => {
1.921     raeburn  10055:                                      description => $description,
                   10056:                                      inst_code   => $inst_code,
                   10057:                                      owner       => $course_owner,
                   10058:                                      type        => $crstype,
1.1029    raeburn  10059:                                      creator     => $env{'user.name'}.':'.
                   10060:                                                     $env{'user.domain'},
                   10061:                                      created     => $now,
                   10062:                                      context     => $context,
1.918     raeburn  10063:                                                 },
                   10064:                     };
1.921     raeburn  10065:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10066: # set toplevel url
1.271     www      10067:     my $topurl=$url;
                   10068:     unless ($nonstandard) {
                   10069: # ------------------------------------------ For standard courses, make top url
                   10070:         my $mapurl=&clutter($url);
1.278     www      10071:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10072:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10073: <map>
                   10074: <resource id="1" type="start"></resource>
                   10075: <resource id="2" src="$mapurl"></resource>
                   10076: <resource id="3" type="finish"></resource>
                   10077: <link index="1" from="1" to="2"></link>
                   10078: <link index="2" from="2" to="3"></link>
                   10079: </map>
                   10080: ENDINITMAP
                   10081:         $topurl=&declutter(
1.638     albertel 10082:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10083:                           );
                   10084:     }
                   10085: # ----------------------------------------------------------- Write preferences
1.84      www      10086:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10087:                      ('description'              => $description,
                   10088:                       'url'                      => $topurl,
                   10089:                       'internal.creator'         => $env{'user.name'}.':'.
                   10090:                                                     $env{'user.domain'},
                   10091:                       'internal.created'         => $now,
                   10092:                       'internal.creationcontext' => $context)
                   10093:                     );
1.84      www      10094:     return '/'.$udom.'/'.$uname;
                   10095: }
                   10096: 
1.1011    raeburn  10097: # ------------------------------------------------------------------- Create ID
                   10098: sub generate_coursenum {
1.1038    raeburn  10099:     my ($udom,$crstype) = @_;
1.1011    raeburn  10100:     my $domdesc = &domain($udom);
                   10101:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10102:     my $first;
                   10103:     if ($crstype eq 'Community') {
                   10104:         $first = '0';
                   10105:     } else {
                   10106:         $first = int(1+rand(9)); 
                   10107:     } 
                   10108:     my $uname=$first.
1.1011    raeburn  10109:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10110:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10111:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10112: # ----------------------------------------------- Make sure that does not exist
                   10113:     my $uhome=&homeserver($uname,$udom,'true');
                   10114:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10115:         if ($crstype eq 'Community') {
                   10116:             $first = '0';
                   10117:         } else {
                   10118:             $first = int(1+rand(9));
                   10119:         }
                   10120:         $uname=$first.
1.1011    raeburn  10121:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10122:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10123:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10124:         $uhome=&homeserver($uname,$udom,'true');
                   10125:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10126:             return 'error: unable to generate unique course-ID';
                   10127:         }
                   10128:     }
                   10129:     return $uname;
                   10130: }
                   10131: 
1.813     albertel 10132: sub is_course {
1.1167    droeschl 10133:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10134:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10135: 
1.1381    raeburn  10136:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10137:     my $uhome=&homeserver($cnum,$cdom);
                   10138:     my $iscourse;
                   10139:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10140:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10141:     } else {
                   10142:         my $hashid = $cdom.':'.$cnum;
                   10143:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10144:         unless (defined($cached)) {
                   10145:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10146:                                         $cnum,undef,undef,'.');
                   10147:             $iscourse = 0;
                   10148:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10149:                 $iscourse = 1;
                   10150:             }
                   10151:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10152:         }
                   10153:     }
                   10154:     return unless ($iscourse);
1.1167    droeschl 10155:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10156: }
                   10157: 
1.1015    raeburn  10158: sub store_userdata {
                   10159:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10160:     my $result;
1.1016    raeburn  10161:     if ($datakey ne '') {
1.1013    raeburn  10162:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10163:             if ($udom eq '' || $uname eq '') {
                   10164:                 $udom = $env{'user.domain'};
                   10165:                 $uname = $env{'user.name'};
                   10166:             }
                   10167:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10168:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10169:                 $result = 'error: no_host';
                   10170:             } else {
                   10171:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10172:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10173: 
                   10174:                 my $namevalue='';
                   10175:                 foreach my $key (keys(%{$storehash})) {
                   10176:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10177:                 }
                   10178:                 $namevalue=~s/\&$//;
1.1224    raeburn  10179:                 unless ($namespace eq 'courserequests') {
                   10180:                     $datakey = &escape($datakey);
                   10181:                 }
1.1105    raeburn  10182:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10183:                                   $namevalue,$uhome);
1.1013    raeburn  10184:             }
                   10185:         } else {
                   10186:             $result = 'error: data to store was not a hash reference'; 
                   10187:         }
                   10188:     } else {
                   10189:         $result= 'error: invalid requestkey'; 
                   10190:     }
                   10191:     return $result;
                   10192: }
                   10193: 
1.21      www      10194: # ---------------------------------------------------------- Assign Custom Role
                   10195: 
                   10196: sub assigncustomrole {
1.957     raeburn  10197:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10198:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10199:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10200: }
                   10201: 
                   10202: # ----------------------------------------------------------------- Revoke Role
                   10203: 
                   10204: sub revokerole {
1.957     raeburn  10205:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10206:     my $now=time;
1.965     raeburn  10207:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10208: }
                   10209: 
                   10210: # ---------------------------------------------------------- Revoke Custom Role
                   10211: 
                   10212: sub revokecustomrole {
1.957     raeburn  10213:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10214:     my $now=time;
1.357     www      10215:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10216:            $deleteflag,$selfenroll,$context);
1.17      www      10217: }
                   10218: 
1.533     banghart 10219: # ------------------------------------------------------------ Disk usage
1.535     albertel 10220: sub diskusage {
1.955     raeburn  10221:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10222:     $directorypath =~ s/\/$//;
                   10223:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10224:                        .&escape($getpropath).':'.&escape($uname).':'
                   10225:                        .&escape($udom),homeserver($uname,$udom));
                   10226:     if ($listing eq 'unknown_cmd') {
                   10227:         if ($getpropath) {
                   10228:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10229:         }
                   10230:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10231:     }
1.514     albertel 10232:     return $listing;
1.512     banghart 10233: }
                   10234: 
1.566     banghart 10235: sub is_locked {
1.1096    raeburn  10236:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10237:     my @check;
                   10238:     my $is_locked;
1.1093    raeburn  10239:     push (@check,$file_name);
1.613     albertel 10240:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10241: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10242:     my ($tmp)=keys(%locked);
                   10243:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10244:     
1.566     banghart 10245:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10246:         $is_locked = 'false';
                   10247:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10248:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10249:                $is_locked = 'true';
1.1096    raeburn  10250:                if (ref($which) eq 'ARRAY') {
                   10251:                    push(@{$which},$entry);
                   10252:                } else {
                   10253:                    last;
                   10254:                }
1.745     raeburn  10255:            }
                   10256:        }
1.566     banghart 10257:     } else {
                   10258:         $is_locked = 'false';
                   10259:     }
1.1093    raeburn  10260:     return $is_locked;
1.566     banghart 10261: }
                   10262: 
1.759     albertel 10263: sub declutter_portfile {
                   10264:     my ($file) = @_;
1.833     albertel 10265:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10266:     return $file;
                   10267: }
                   10268: 
1.559     banghart 10269: # ------------------------------------------------------------- Mark as Read Only
                   10270: 
                   10271: sub mark_as_readonly {
                   10272:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10273:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10274:     my ($tmp)=keys(%current_permissions);
                   10275:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10276:     foreach my $file (@{$files}) {
1.759     albertel 10277: 	$file = &declutter_portfile($file);
1.561     banghart 10278:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10279:     }
1.613     albertel 10280:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10281:     return;
                   10282: }
                   10283: 
1.572     banghart 10284: # ------------------------------------------------------------Save Selected Files
                   10285: 
                   10286: sub save_selected_files {
                   10287:     my ($user, $path, @files) = @_;
                   10288:     my $filename = $user."savedfiles";
1.573     banghart 10289:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10290:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10291:     foreach my $file (@files) {
1.620     albertel 10292:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10293:     }
                   10294:     foreach my $file (@other_files) {
1.574     banghart 10295:         print (OUT $file."\n");
1.572     banghart 10296:     }
1.574     banghart 10297:     close (OUT);
1.572     banghart 10298:     return 'ok';
                   10299: }
                   10300: 
1.574     banghart 10301: sub clear_selected_files {
                   10302:     my ($user) = @_;
                   10303:     my $filename = $user."savedfiles";
1.1359    raeburn  10304:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10305:     print (OUT undef);
                   10306:     close (OUT);
                   10307:     return ("ok");    
                   10308: }
                   10309: 
1.572     banghart 10310: sub files_in_path {
                   10311:     my ($user, $path) = @_;
                   10312:     my $filename = $user."savedfiles";
                   10313:     my %return_files;
1.1359    raeburn  10314:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10315:     while (my $line_in = <IN>) {
1.574     banghart 10316:         chomp ($line_in);
                   10317:         my @paths_and_file = split (m!/!, $line_in);
                   10318:         my $file_part = pop (@paths_and_file);
                   10319:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10320:         $path_part.='/';
                   10321:         my $path_and_file = $path_part.$file_part;
                   10322:         if ($path_part eq $path) {
                   10323:             $return_files{$file_part}= 'selected';
                   10324:         }
                   10325:     }
1.574     banghart 10326:     close (IN);
                   10327:     return (\%return_files);
1.572     banghart 10328: }
                   10329: 
                   10330: # called in portfolio select mode, to show files selected NOT in current directory
                   10331: sub files_not_in_path {
                   10332:     my ($user, $path) = @_;
                   10333:     my $filename = $user."savedfiles";
                   10334:     my @return_files;
                   10335:     my $path_part;
1.1359    raeburn  10336:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10337:     while (my $line = <IN>) {
1.572     banghart 10338:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10339:         my @paths_and_file = split(m|/|, $line);
                   10340:         my $file_part = pop(@paths_and_file);
                   10341:         chomp($file_part);
                   10342:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10343:         $path_part .= '/';
                   10344:         my $path_and_file = $path_part.$file_part;
                   10345:         if ($path_part ne $path) {
1.800     albertel 10346:             push(@return_files, ($path_and_file));
1.572     banghart 10347:         }
                   10348:     }
1.800     albertel 10349:     close(OUT);
1.574     banghart 10350:     return (@return_files);
1.572     banghart 10351: }
                   10352: 
1.1273    raeburn  10353: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10354:  
                   10355: sub portfiles_versioning {
                   10356:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10357:     my $portfolio_root = '/userfiles/portfolio';
                   10358:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10359:     foreach my $file (@{$portfiles}) {
                   10360:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10361:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10362:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10363:         my $getpropath = 1;
                   10364:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10365:                                              $stu_name,$getpropath);
                   10366:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10367:         my $new_answer = 
                   10368:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10369:         if ($new_answer ne 'problem getting file') {
                   10370:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10371:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10372:                               [$symb,$env{'request.course.id'},'graded']);
                   10373:         }
                   10374:     }
                   10375: }
                   10376: 
                   10377: sub get_next_version {
                   10378:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10379:     my $version;
                   10380:     if (ref($dir_list) eq 'ARRAY') {
                   10381:         foreach my $row (@{$dir_list}) {
                   10382:             my ($file) = split(/\&/,$row,2);
                   10383:             my ($file_name,$file_version,$file_ext) =
                   10384:                 &file_name_version_ext($file);
                   10385:             if (($file_name eq $answer_name) &&
                   10386:                 ($file_ext eq $answer_ext)) {
                   10387:                      # gets here if filename and extension match,
                   10388:                      # regardless of version
                   10389:                 if ($file_version ne '') {
                   10390:                     # a versioned file is found  so save it for later
                   10391:                     if ($file_version > $version) {
                   10392:                         $version = $file_version;
                   10393:                     }
                   10394:                 }
                   10395:             }
                   10396:         }
                   10397:     }
                   10398:     $version ++;
                   10399:     return($version);
                   10400: }
                   10401: 
                   10402: sub version_selected_portfile {
                   10403:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10404:     my ($answer_name,$answer_ver,$answer_ext) =
                   10405:         &file_name_version_ext($file_name);
                   10406:     my $new_answer;
                   10407:     $env{'form.copy'} =
                   10408:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10409:     if($env{'form.copy'} eq '-1') {
                   10410:         $new_answer = 'problem getting file';
                   10411:     } else {
                   10412:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10413:         my $copy_result = 
                   10414:             &finishuserfileupload($stu_name,$domain,'copy',
                   10415:                                   '/portfolio'.$directory.$new_answer);
                   10416:     }
                   10417:     undef($env{'form.copy'});
                   10418:     return ($new_answer);
                   10419: }
                   10420: 
                   10421: sub file_name_version_ext {
                   10422:     my ($file)=@_;
                   10423:     my @file_parts = split(/\./, $file);
                   10424:     my ($name,$version,$ext);
                   10425:     if (@file_parts > 1) {
                   10426:         $ext=pop(@file_parts);
                   10427:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10428:             $version=pop(@file_parts);
                   10429:         }
                   10430:         $name=join('.',@file_parts);
                   10431:     } else {
                   10432:         $name=join('.',@file_parts);
                   10433:     }
                   10434:     return($name,$version,$ext);
                   10435: }
                   10436: 
1.745     raeburn  10437: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10438: 
1.745     raeburn  10439: sub get_portfile_permissions {
                   10440:     my ($domain,$user) = @_;
1.613     albertel 10441:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10442:     my ($tmp)=keys(%current_permissions);
                   10443:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10444:     return \%current_permissions;
                   10445: }
                   10446: 
                   10447: #---------------------------------------------Get portfolio file access controls
                   10448: 
1.749     raeburn  10449: sub get_access_controls {
1.745     raeburn  10450:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10451:     my %access;
                   10452:     my $real_file = $file;
                   10453:     $file =~ s/\.meta$//;
1.745     raeburn  10454:     if (defined($file)) {
1.749     raeburn  10455:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10456:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10457:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10458:             }
                   10459:         }
1.745     raeburn  10460:     } else {
1.749     raeburn  10461:         foreach my $key (keys(%{$current_permissions})) {
                   10462:             if ($key =~ /\0accesscontrol$/) {
                   10463:                 if (defined($group)) {
                   10464:                     if ($key !~ m-^\Q$group\E/-) {
                   10465:                         next;
                   10466:                     }
                   10467:                 }
                   10468:                 my ($fullpath) = split(/\0/,$key);
                   10469:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10470:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10471:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10472:                     }
                   10473:                 }
                   10474:             }
                   10475:         }
                   10476:     }
                   10477:     return %access;
                   10478: }
                   10479: 
                   10480: sub modify_access_controls {
                   10481:     my ($file_name,$changes,$domain,$user)=@_;
                   10482:     my ($outcome,$deloutcome);
                   10483:     my %store_permissions;
                   10484:     my %new_values;
                   10485:     my %new_control;
                   10486:     my %translation;
                   10487:     my @deletions = ();
                   10488:     my $now = time;
                   10489:     if (exists($$changes{'activate'})) {
                   10490:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10491:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10492:             my $numnew = scalar(@newitems);
                   10493:             for (my $i=0; $i<$numnew; $i++) {
                   10494:                 my $newkey = $newitems[$i];
                   10495:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10496:                 if ($newkey =~ /^\d+:/) { 
                   10497:                     $newkey =~ s/^(\d+)/$newid/;
                   10498:                     $translation{$1} = $newid;
                   10499:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10500:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10501:                     $translation{$1} = $newid;
                   10502:                 }
1.749     raeburn  10503:                 $new_values{$file_name."\0".$newkey} = 
                   10504:                                           $$changes{'activate'}{$newitems[$i]};
                   10505:                 $new_control{$newkey} = $now;
                   10506:             }
                   10507:         }
                   10508:     }
                   10509:     my %todelete;
                   10510:     my %changed_items;
                   10511:     foreach my $action ('delete','update') {
                   10512:         if (exists($$changes{$action})) {
                   10513:             if (ref($$changes{$action}) eq 'HASH') {
                   10514:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10515:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10516:                     if ($action eq 'delete') { 
                   10517:                         $todelete{$itemnum} = 1;
                   10518:                     } else {
                   10519:                         $changed_items{$itemnum} = $key;
                   10520:                     }
                   10521:                 }
1.745     raeburn  10522:             }
                   10523:         }
1.749     raeburn  10524:     }
                   10525:     # get lock on access controls for file.
                   10526:     my $lockhash = {
                   10527:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10528:                                                        ':'.$env{'user.domain'},
                   10529:                    }; 
                   10530:     my $tries = 0;
                   10531:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10532:    
1.1288    damieng  10533:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10534:         $tries ++;
1.1289    damieng  10535:         sleep(0.1);
1.749     raeburn  10536:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10537:     }
                   10538:     if ($gotlock eq 'ok') {
                   10539:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10540:         my ($tmp)=keys(%curr_permissions);
                   10541:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10542:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10543:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10544:             if (ref($curr_controls) eq 'HASH') {
                   10545:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10546:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10547:                     if (defined($todelete{$itemnum})) {
                   10548:                         push(@deletions,$file_name."\0".$control_item);
                   10549:                     } else {
                   10550:                         if (defined($changed_items{$itemnum})) {
                   10551:                             $new_control{$changed_items{$itemnum}} = $now;
                   10552:                             push(@deletions,$file_name."\0".$control_item);
                   10553:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10554:                         } else {
                   10555:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10556:                         }
                   10557:                     }
1.745     raeburn  10558:                 }
                   10559:             }
                   10560:         }
1.970     raeburn  10561:         my ($group);
                   10562:         if (&is_course($domain,$user)) {
                   10563:             ($group,my $file) = split(/\//,$file_name,2);
                   10564:         }
1.749     raeburn  10565:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10566:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10567:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10568:         #  remove lock
                   10569:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10570:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10571:         my $sqlresult =
1.970     raeburn  10572:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10573:                                     $group);
1.749     raeburn  10574:     } else {
                   10575:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10576:     }
1.749     raeburn  10577:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10578: }
                   10579: 
1.827     raeburn  10580: sub make_public_indefinitely {
1.1271    raeburn  10581:     my (@requrl) = @_;
                   10582:     return &automated_portfile_access('public',\@requrl);
                   10583: }
                   10584: 
                   10585: sub automated_portfile_access {
                   10586:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10587:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10588:         return 'invalid';
                   10589:     }
1.1271    raeburn  10590:     my %urls;
                   10591:     if (ref($addsref) eq 'ARRAY') {
                   10592:         foreach my $requrl (@{$addsref}) {
                   10593:             if (&is_portfolio_url($requrl)) {
                   10594:                 unless (exists($urls{$requrl})) {
                   10595:                     $urls{$requrl} = 'add';
                   10596:                 }
                   10597:             }
                   10598:         }
                   10599:     }
                   10600:     if (ref($delsref) eq 'ARRAY') {
                   10601:         foreach my $requrl (@{$delsref}) { 
                   10602:             if (&is_portfolio_url($requrl)) {
                   10603:                 unless (exists($urls{$requrl})) {
                   10604:                     $urls{$requrl} = 'delete'; 
                   10605:                 }
                   10606:             }
                   10607:         }
                   10608:     }
                   10609:     unless (keys(%urls)) {
                   10610:         return 'invalid';
                   10611:     }
                   10612:     my $ip;
                   10613:     if ($accesstype eq 'ip') {
                   10614:         if (ref($info) eq 'HASH') {
                   10615:             if ($info->{'ip'} ne '') {
                   10616:                 $ip = $info->{'ip'};
                   10617:             }
                   10618:         }
                   10619:         if ($ip eq '') {
                   10620:             return 'invalid';
                   10621:         }
                   10622:     }
                   10623:     my $errors;
1.827     raeburn  10624:     my $now = time;
1.1271    raeburn  10625:     my %current_perms;
                   10626:     foreach my $requrl (sort(keys(%urls))) {
                   10627:         my $action;
                   10628:         if ($urls{$requrl} eq 'add') {
                   10629:             $action = 'activate';
                   10630:         } else {
                   10631:             $action = 'none';
                   10632:         }
                   10633:         my $aclnum = 0;
1.827     raeburn  10634:         my (undef,$udom,$unum,$file_name,$group) =
                   10635:             &parse_portfolio_url($requrl);
1.1271    raeburn  10636:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10637:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10638:         }
                   10639:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10640:                                                    $group,$file_name);
                   10641:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10642:             my ($num,$scope,$end,$start) = 
                   10643:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10644:             if ($scope eq $accesstype) {
                   10645:                 if (($start <= $now) && ($end == 0)) {
                   10646:                     if ($accesstype eq 'ip') {
                   10647:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10648:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10649:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10650:                                     if ($urls{$requrl} eq 'add') {
                   10651:                                         $action = 'none';
                   10652:                                         last;
                   10653:                                     } else {
                   10654:                                         $action = 'delete';
                   10655:                                         $aclnum = $num;
                   10656:                                         last;
                   10657:                                     }
                   10658:                                 }
                   10659:                             }
                   10660:                         }
                   10661:                     } elsif ($accesstype eq 'public') {
                   10662:                         if ($urls{$requrl} eq 'add') {
                   10663:                             $action = 'none';
                   10664:                             last;
                   10665:                         } else {
                   10666:                             $action = 'delete';
                   10667:                             $aclnum = $num;
                   10668:                             last;
                   10669:                         }
                   10670:                     }
                   10671:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10672:                     $action = 'update';
                   10673:                     $aclnum = $num;
1.1271    raeburn  10674:                     last;
1.827     raeburn  10675:                 }
                   10676:             }
                   10677:         }
                   10678:         if ($action eq 'none') {
1.1271    raeburn  10679:             next;
1.827     raeburn  10680:         } else {
                   10681:             my %changes;
                   10682:             my $newend = 0;
                   10683:             my $newstart = $now;
1.1271    raeburn  10684:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10685:             $changes{$action}{$newkey} = {
1.1271    raeburn  10686:                 type => $accesstype,
1.827     raeburn  10687:                 time => {
                   10688:                     start => $newstart,
                   10689:                     end   => $newend,
                   10690:                 },
                   10691:             };
1.1271    raeburn  10692:             if ($accesstype eq 'ip') {
                   10693:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10694:             }
1.827     raeburn  10695:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10696:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10697:             unless ($outcome eq 'ok') {
                   10698:                 $errors .= $outcome.' ';
                   10699:             }
1.827     raeburn  10700:         }
1.1271    raeburn  10701:     }
                   10702:     if ($errors) {
                   10703:         $errors =~ s/\s$//;
                   10704:         return $errors;
1.827     raeburn  10705:     } else {
1.1271    raeburn  10706:         return 'ok';
1.827     raeburn  10707:     }
                   10708: }
                   10709: 
1.745     raeburn  10710: #------------------------------------------------------Get Marked as Read Only
                   10711: 
                   10712: sub get_marked_as_readonly {
                   10713:     my ($domain,$user,$what,$group) = @_;
                   10714:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10715:     my @readonly_files;
1.629     banghart 10716:     my $cmp1=$what;
                   10717:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10718:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10719:         if (defined($group)) {
                   10720:             if ($file_name !~ m-^\Q$group\E/-) {
                   10721:                 next;
                   10722:             }
                   10723:         }
1.561     banghart 10724:         if (ref($value) eq "ARRAY"){
                   10725:             foreach my $stored_what (@{$value}) {
1.629     banghart 10726:                 my $cmp2=$stored_what;
1.759     albertel 10727:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10728:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10729:                 }
1.629     banghart 10730:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10731:                     push(@readonly_files, $file_name);
1.745     raeburn  10732:                     last;
1.563     banghart 10733:                 } elsif (!defined($what)) {
                   10734:                     push(@readonly_files, $file_name);
1.745     raeburn  10735:                     last;
1.561     banghart 10736:                 }
                   10737:             }
1.745     raeburn  10738:         }
1.561     banghart 10739:     }
                   10740:     return @readonly_files;
                   10741: }
1.577     banghart 10742: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10743: 
1.577     banghart 10744: sub get_marked_as_readonly_hash {
1.745     raeburn  10745:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10746:     my %readonly_files;
1.745     raeburn  10747:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10748:         if (defined($group)) {
                   10749:             if ($file_name !~ m-^\Q$group\E/-) {
                   10750:                 next;
                   10751:             }
                   10752:         }
1.577     banghart 10753:         if (ref($value) eq "ARRAY"){
                   10754:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10755:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10756:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10757:                         if ($lock_descriptor eq 'graded') {
                   10758:                             $readonly_files{$file_name} = 'graded';
                   10759:                         } elsif ($lock_descriptor eq 'handback') {
                   10760:                             $readonly_files{$file_name} = 'handback';
                   10761:                         } else {
                   10762:                             if (!exists($readonly_files{$file_name})) {
                   10763:                                 $readonly_files{$file_name} = 'locked';
                   10764:                             }
                   10765:                         }
1.745     raeburn  10766:                     }
1.750     banghart 10767:                 } 
1.577     banghart 10768:             }
                   10769:         } 
                   10770:     }
                   10771:     return %readonly_files;
                   10772: }
1.559     banghart 10773: # ------------------------------------------------------------ Unmark as Read Only
                   10774: 
                   10775: sub unmark_as_readonly {
1.629     banghart 10776:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10777:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10778:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10779:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10780:     my $symb_crs = $what;
                   10781:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10782:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10783:     my ($tmp)=keys(%current_permissions);
                   10784:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10785:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10786:     foreach my $file (@readonly_files) {
1.759     albertel 10787: 	my $clean_file = &declutter_portfile($file);
                   10788: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10789: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10790:         my @new_locks;
                   10791:         my @del_keys;
                   10792:         if (ref($current_locks) eq "ARRAY"){
                   10793:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10794:                 my $compare=$locker;
1.749     raeburn  10795:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10796:                     $compare=join('',@{$locker});
1.746     raeburn  10797:                     if ($compare ne $symb_crs) {
                   10798:                         push(@new_locks, $locker);
                   10799:                     }
1.563     banghart 10800:                 }
                   10801:             }
1.650     albertel 10802:             if (scalar(@new_locks) > 0) {
1.563     banghart 10803:                 $current_permissions{$file} = \@new_locks;
                   10804:             } else {
                   10805:                 push(@del_keys, $file);
1.613     albertel 10806:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10807:                 delete($current_permissions{$file});
1.563     banghart 10808:             }
                   10809:         }
1.561     banghart 10810:     }
1.613     albertel 10811:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10812:     return;
                   10813: }
1.512     banghart 10814: 
1.17      www      10815: # ------------------------------------------------------------ Directory lister
                   10816: 
                   10817: sub dirlist {
1.955     raeburn  10818:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10819:     $uri=~s/^\///;
                   10820:     $uri=~s/\/$//;
1.253     stredwic 10821:     my ($udom, $uname);
1.955     raeburn  10822:     if ($getuserdir) {
1.253     stredwic 10823:         $udom = $userdomain;
                   10824:         $uname = $username;
1.955     raeburn  10825:     } else {
                   10826:         (undef,$udom,$uname)=split(/\//,$uri);
                   10827:         if(defined($userdomain)) {
                   10828:             $udom = $userdomain;
                   10829:         }
                   10830:         if(defined($username)) {
                   10831:             $uname = $username;
                   10832:         }
1.253     stredwic 10833:     }
1.955     raeburn  10834:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10835: 
1.955     raeburn  10836:     $dirRoot = $perlvar{'lonDocRoot'};
                   10837:     if (defined($getpropath)) {
                   10838:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10839:         $dirRoot =~ s/\/$//;
1.955     raeburn  10840:     } elsif (defined($getuserdir)) {
                   10841:         my $subdir=$uname.'__';
                   10842:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10843:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10844:                    ."/$udom/$subdir/$uname";
                   10845:     } elsif (defined($alternateRoot)) {
                   10846:         $dirRoot = $alternateRoot;
1.751     banghart 10847:     }
1.253     stredwic 10848: 
                   10849:     if($udom) {
                   10850:         if($uname) {
1.1135    raeburn  10851:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10852:             if ($uhome eq 'no_host') {
                   10853:                 return ([],'no_host');
                   10854:             }
1.955     raeburn  10855:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10856:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10857:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10858:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10859:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10860:             } else {
                   10861:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10862:             }
1.605     matthew  10863:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10864:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10865:                 @listing_results = split(/:/,$listing);
                   10866:             } else {
                   10867:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10868:             }
1.1135    raeburn  10869:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10870:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10871:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10872:                 return ([],$listing);
                   10873:             } else {
                   10874:                 return (\@listing_results);
1.1135    raeburn  10875:             }
1.955     raeburn  10876:         } elsif(!$alternateRoot) {
1.1136    raeburn  10877:             my (%allusers,%listerror);
1.841     albertel 10878: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10879:  	    foreach my $tryserver (keys(%servers)) {
                   10880:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10881:                                   &escape($udom),$tryserver);
                   10882:                 if ($listing eq 'unknown_cmd') {
                   10883: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10884: 				      $udom, $tryserver);
                   10885:                 } else {
                   10886:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10887:                 }
1.841     albertel 10888: 		if ($listing eq 'unknown_cmd') {
                   10889: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10890: 				      $udom, $tryserver);
                   10891: 		    @listing_results = split(/:/,$listing);
                   10892: 		} else {
                   10893: 		    @listing_results =
                   10894: 			map { &unescape($_); } split(/:/,$listing);
                   10895: 		}
1.1136    raeburn  10896:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10897:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10898:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10899:                     $listerror{$tryserver} = $listing;
                   10900:                 } else {
1.841     albertel 10901: 		    foreach my $line (@listing_results) {
                   10902: 			my ($entry) = split(/&/,$line,2);
                   10903: 			$allusers{$entry} = 1;
                   10904: 		    }
                   10905: 		}
1.253     stredwic 10906:             }
1.1136    raeburn  10907:             my @alluserslist=();
1.800     albertel 10908:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10909:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10910:             }
1.1318    droeschl 10911: 
                   10912:             if (!%listerror) {
                   10913:                 # no errors
                   10914:                 return (\@alluserslist);
                   10915:             } elsif (scalar(keys(%servers)) == 1) {
                   10916:                 # one library server, one error 
                   10917:                 my ($key) = keys(%listerror);
                   10918:                 return (\@alluserslist, $listerror{$key});
                   10919:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10920:                 # con_lost indicates that we might miss data from at least one
                   10921:                 # library server
                   10922:                 return (\@alluserslist, 'con_lost');
                   10923:             } else {
                   10924:                 # multiple library servers and no con_lost -> data should be
                   10925:                 # complete. 
                   10926:                 return (\@alluserslist);
                   10927:             }
                   10928: 
1.253     stredwic 10929:         } else {
1.1136    raeburn  10930:             return ([],'missing username');
1.253     stredwic 10931:         }
1.955     raeburn  10932:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10933:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10934:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10935:         return (\@all_domains);
1.955     raeburn  10936:     } else {
1.1136    raeburn  10937:         return ([],'missing domain');
1.275     stredwic 10938:     }
                   10939: }
                   10940: 
                   10941: # --------------------------------------------- GetFileTimestamp
                   10942: # This function utilizes dirlist and returns the date stamp for
                   10943: # when it was last modified.  It will also return an error of -1
                   10944: # if an error occurs
                   10945: 
                   10946: sub GetFileTimestamp {
1.955     raeburn  10947:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10948:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10949:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10950:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10951:                                     undef,$getuserdir);
                   10952:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10953:         return -1;
                   10954:     }
                   10955:     if (ref($fileref) eq 'ARRAY') {
                   10956:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10957:         # @stats contains first the filename, then the stat output
                   10958:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10959:     } else {
                   10960:         return -1;
1.253     stredwic 10961:     }
1.26      www      10962: }
                   10963: 
1.712     albertel 10964: sub stat_file {
                   10965:     my ($uri) = @_;
1.787     albertel 10966:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10967: 
1.955     raeburn  10968:     my ($udom,$uname,$file);
1.712     albertel 10969:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10970: 	($udom,$uname,$file) =
1.811     albertel 10971: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10972: 	$file = 'userfiles/'.$file;
                   10973:     }
                   10974:     if ($uri =~ m-^/res/-) {
                   10975: 	($udom,$uname) = 
1.807     albertel 10976: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10977: 	$file = $uri;
                   10978:     }
                   10979: 
                   10980:     if (!$udom || !$uname || !$file) {
                   10981: 	# unable to handle the uri
                   10982: 	return ();
                   10983:     }
1.956     raeburn  10984:     my $getpropath;
                   10985:     if ($file =~ /^userfiles\//) {
                   10986:         $getpropath = 1;
                   10987:     }
1.1136    raeburn  10988:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10989:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10990:         return ();
                   10991:     } else {
                   10992:         if (ref($listref) eq 'ARRAY') {
                   10993:             my @stats = split('&',$listref->[0]);
                   10994: 	    shift(@stats); #filename is first
                   10995: 	    return @stats;
                   10996:         }
1.712     albertel 10997:     }
                   10998:     return ();
                   10999: }
                   11000: 
1.1313    raeburn  11001: # --------------------------------------------------------- recursedirs
                   11002: # Recursive function to traverse either a specific user's Authoring Space
                   11003: # or corresponding Published Resource Space, and populate the hash ref:
                   11004: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11005: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11006: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11007: # files in Authoring Space.
                   11008: #
                   11009: # Inputs:
                   11010: #
                   11011: # $is_home - true if current server is home server for user's space
                   11012: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11013: # $docroot - Document root (i.e., /home/httpd/html
                   11014: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11015: # $relpath - Current path (relative to top level).
                   11016: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11017: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11018: #
                   11019: # Returns: nothing
                   11020: #
                   11021: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11022: #
                   11023: # Currently used by interface/londocs.pm to create linked select boxes for
                   11024: # directory and filename to import a Course "Author" resource into a course, and
                   11025: # also to create linked select boxes for Authoring Space and Directory to choose
                   11026: # save location for creation of a new "standard" problem from the Course Editor.
                   11027: #
                   11028: 
                   11029: sub recursedirs {
                   11030:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11031:     return unless (ref($dirhashref) eq 'HASH');
                   11032:     my $currpath = $docroot.$toppath;
                   11033:     if ($relpath) {
                   11034:         $currpath .= "/$relpath";
                   11035:     }
                   11036:     my $savefile;
                   11037:     if (ref($filehashref)) {
                   11038:         $savefile = 1;
                   11039:     }
                   11040:     if ($is_home) {
                   11041:         if (opendir(my $dirh,$currpath)) {
                   11042:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11043:                 next if ($item eq '');
                   11044:                 if (-d "$currpath/$item") {
                   11045:                     my $newpath;
                   11046:                     if ($relpath) {
                   11047:                         $newpath = "$relpath/$item";
                   11048:                     } else {
                   11049:                         $newpath = $item;
                   11050:                     }
                   11051:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11052:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11053:                 } elsif ($savefile) {
                   11054:                     if ($context eq 'priv') {
                   11055:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11056:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11057:                         }
                   11058:                     } else {
                   11059:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11060:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11061:                         }
                   11062:                     }
                   11063:                 }
                   11064:             }
                   11065:             closedir($dirh);
                   11066:         }
                   11067:     } else {
                   11068:         my ($dirlistref,$listerror) =
                   11069:             &dirlist($toppath.$relpath);
                   11070:         my @dir_lines;
                   11071:         my $dirptr=16384;
                   11072:         if (ref($dirlistref) eq 'ARRAY') {
                   11073:             foreach my $dir_line (sort
                   11074:                               {
                   11075:                                   my ($afile)=split('&',$a,2);
                   11076:                                   my ($bfile)=split('&',$b,2);
                   11077:                                   return (lc($afile) cmp lc($bfile));
                   11078:                               } (@{$dirlistref})) {
                   11079:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11080:                     split(/\&/,$dir_line,16);
                   11081:                 $item =~ s/\s+$//;
                   11082:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11083:                 if ($dirptr&$testdir) {
                   11084:                     my $newpath;
                   11085:                     if ($relpath) {
                   11086:                         $newpath = "$relpath/$item";
                   11087:                     } else {
                   11088:                         $relpath = '/';
                   11089:                         $newpath = $item;
                   11090:                     }
                   11091:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11092:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11093:                 } elsif ($savefile) {
                   11094:                     if ($context eq 'priv') {
                   11095:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11096:                             $filehashref->{$relpath}{$item} = 1;
                   11097:                         }
                   11098:                     } else {
                   11099:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11100:                             $filehashref->{$relpath}{$item} = 1;
                   11101:                         }
                   11102:                     }
                   11103:                 }
                   11104:             }
                   11105:         }
                   11106:     }
                   11107:     return;
                   11108: }
                   11109: 
1.26      www      11110: # -------------------------------------------------------- Value of a Condition
                   11111: 
1.713     albertel 11112: # gets the value of a specific preevaluated condition
                   11113: #    stored in the string  $env{user.state.<cid>}
                   11114: # or looks up a condition reference in the bighash and if if hasn't
                   11115: # already been evaluated recurses into docondval to get the value of
                   11116: # the condition, then memoizing it to 
                   11117: #   $env{user.state.<cid>.<condition>}
1.40      www      11118: sub directcondval {
                   11119:     my $number=shift;
1.620     albertel 11120:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11121: 	&Apache::lonuserstate::evalstate();
                   11122:     }
1.713     albertel 11123:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11124: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11125:     } elsif ($number =~ /^_/) {
                   11126: 	my $sub_condition;
                   11127: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11128: 		&GDBM_READER(),0640)) {
                   11129: 	    $sub_condition=$bighash{'conditions'.$number};
                   11130: 	    untie(%bighash);
                   11131: 	}
                   11132: 	my $value = &docondval($sub_condition);
1.949     raeburn  11133: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11134: 	return $value;
                   11135:     }
1.620     albertel 11136:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11137:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11138:     } else {
                   11139:        return 2;
                   11140:     }
                   11141: }
                   11142: 
1.713     albertel 11143: # get the collection of conditions for this resource
1.26      www      11144: sub condval {
                   11145:     my $condidx=shift;
1.54      www      11146:     my $allpathcond='';
1.713     albertel 11147:     foreach my $cond (split(/\|/,$condidx)) {
                   11148: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11149: 	    $allpathcond.=
                   11150: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11151: 	}
1.191     harris41 11152:     }
1.54      www      11153:     $allpathcond=~s/\|$//;
1.713     albertel 11154:     return &docondval($allpathcond);
                   11155: }
                   11156: 
                   11157: #evaluates an expression of conditions
                   11158: sub docondval {
                   11159:     my ($allpathcond) = @_;
                   11160:     my $result=0;
                   11161:     if ($env{'request.course.id'}
                   11162: 	&& defined($allpathcond)) {
                   11163: 	my $operand='|';
                   11164: 	my @stack;
                   11165: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11166: 	    if ($chunk eq '(') {
                   11167: 		push @stack,($operand,$result);
                   11168: 	    } elsif ($chunk eq ')') {
                   11169: 		my $before=pop @stack;
                   11170: 		if (pop @stack eq '&') {
                   11171: 		    $result=$result>$before?$before:$result;
                   11172: 		} else {
                   11173: 		    $result=$result>$before?$result:$before;
                   11174: 		}
                   11175: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11176: 		$operand=$chunk;
                   11177: 	    } else {
                   11178: 		my $new=directcondval($chunk);
                   11179: 		if ($operand eq '&') {
                   11180: 		    $result=$result>$new?$new:$result;
                   11181: 		} else {
                   11182: 		    $result=$result>$new?$result:$new;
                   11183: 		}
                   11184: 	    }
                   11185: 	}
1.26      www      11186:     }
                   11187:     return $result;
1.421     albertel 11188: }
                   11189: 
                   11190: # ---------------------------------------------------- Devalidate courseresdata
                   11191: 
                   11192: sub devalidatecourseresdata {
                   11193:     my ($coursenum,$coursedomain)=@_;
                   11194:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11195:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11196: }
                   11197: 
1.763     www      11198: 
1.200     www      11199: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11200: #
                   11201: #  Parameters:
                   11202: #      $coursenum    - Number of the course.
                   11203: #      $coursedomain - Domain at which the course was created.
                   11204: #  Returns:
                   11205: #     A hash of the course parameters along (I think) with timestamps
                   11206: #     and version info.
1.877     foxr     11207: 
1.624     albertel 11208: sub get_courseresdata {
                   11209:     my ($coursenum,$coursedomain)=@_;
1.200     www      11210:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11211:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11212:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11213:     my %dumpreply;
1.417     albertel 11214:     unless (defined($cached)) {
1.624     albertel 11215: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11216: 	$result=\%dumpreply;
1.251     albertel 11217: 	my ($tmp) = keys(%dumpreply);
                   11218: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11219: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11220: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11221: 	    return $tmp;
1.416     albertel 11222: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11223: 	    $result=undef;
1.599     albertel 11224: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11225: 	}
                   11226:     }
1.624     albertel 11227:     return $result;
                   11228: }
                   11229: 
1.633     albertel 11230: sub devalidateuserresdata {
                   11231:     my ($uname,$udom)=@_;
                   11232:     my $hashid="$udom:$uname";
                   11233:     &devalidate_cache_new('userres',$hashid);
                   11234: }
                   11235: 
1.624     albertel 11236: sub get_userresdata {
                   11237:     my ($uname,$udom)=@_;
                   11238:     #most student don\'t have any data set, check if there is some data
                   11239:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11240: 
                   11241:     my $hashid="$udom:$uname";
                   11242:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11243:     if (!defined($cached)) {
                   11244: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11245: 	$result=\%resourcedata;
                   11246: 	&do_cache_new('userres',$hashid,$result,600);
                   11247:     }
                   11248:     my ($tmp)=keys(%$result);
                   11249:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11250: 	return $result;
                   11251:     }
                   11252:     #error 2 occurs when the .db doesn't exist
                   11253:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11254:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11255: 	    &logthis("<font color=\"blue\">WARNING:".
                   11256: 		     " Trying to get resource data for ".
                   11257: 		     $uname." at ".$udom.": ".
                   11258: 		     $tmp."</font>");
                   11259:         }
1.624     albertel 11260:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11261: 	#&EXT_cache_set($udom,$uname);
                   11262: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11263: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11264:     }
                   11265:     return $tmp;
                   11266: }
1.879     foxr     11267: #----------------------------------------------- resdata - return resource data
                   11268: #  Purpose:
                   11269: #    Return resource data for either users or for a course.
                   11270: #  Parameters:
                   11271: #     $name      - Course/user name.
                   11272: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11273: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11274: #     $mapp      - decluttered URL of enclosing map  
                   11275: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11276: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11277: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11278: #     $courseid  - CourseID (first part of param identifier).
                   11279: #     $modifier  - Middle part of param identifier.
                   11280: #     $what      - Last part of param identifier.
1.879     foxr     11281: #     @which     - Array of names of resources desired.
                   11282: #  Returns:
                   11283: #     The value of the first reasource in @which that is found in the
                   11284: #     resource hash.
                   11285: #  Exceptional Conditions:
                   11286: #     If the $type passed in is not valid (not the string 'course' or 
                   11287: #     'user', an undefined  reference is returned.
                   11288: #     If none of the resources are found, an undef is returned
1.624     albertel 11289: sub resdata {
1.1301    raeburn  11290:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11291:         $modifier,$what,@which)=@_;
1.624     albertel 11292:     my $result;
                   11293:     if ($type eq 'course') {
                   11294: 	$result=&get_courseresdata($name,$domain);
                   11295:     } elsif ($type eq 'user') {
                   11296: 	$result=&get_userresdata($name,$domain);
                   11297:     }
                   11298:     if (!ref($result)) { return $result; }    
1.251     albertel 11299:     foreach my $item (@which) {
1.1301    raeburn  11300:         if ($item->[1] eq 'course') {
                   11301:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11302:                 unless ($$recursed) {
1.1302    raeburn  11303:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11304:                     $$recursed = 1;
                   11305:                 }
                   11306:                 foreach my $item (@${recurseup}) {
                   11307:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11308:                     last if (defined($result->{$norecursechk}));
                   11309:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11310:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11311:                 }
                   11312:             }
                   11313:         }
                   11314:         if (defined($result->{$item->[0]})) {
1.927     albertel 11315: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11316: 	}
1.250     albertel 11317:     }
1.291     albertel 11318:     return undef;
1.200     www      11319: }
                   11320: 
1.1360    raeburn  11321: sub get_domain_lti {
                   11322:     my ($cdom,$context) = @_;
                   11323:     my ($name,%lti);
                   11324:     if ($context eq 'consumer') {
                   11325:         $name = 'ltitools';
                   11326:     } elsif ($context eq 'provider') {
                   11327:         $name = 'lti';
                   11328:     } else {
                   11329:         return %lti;
                   11330:     }
                   11331:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11332:     if (defined($cached)) {
                   11333:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11334:             %lti = %{$result};
1.1298    raeburn  11335:         }
                   11336:     } else {
1.1360    raeburn  11337:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11338:         if (ref($domconfig{$name}) eq 'HASH') {
                   11339:             %lti = %{$domconfig{$name}};
                   11340:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11341:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11342:                 foreach my $id (keys(%lti)) {
                   11343:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11344:                         foreach my $item ('key','secret') {
1.1360    raeburn  11345:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11346:                         }
                   11347:                     }
                   11348:                 }
                   11349:             }
1.1298    raeburn  11350:         }
                   11351:         my $cachetime = 24*60*60;
1.1360    raeburn  11352:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11353:     }
1.1360    raeburn  11354:     return %lti;
1.1298    raeburn  11355: }
                   11356: 
1.1236    raeburn  11357: sub get_numsuppfiles {
                   11358:     my ($cnum,$cdom,$ignorecache)=@_;
                   11359:     my $hashid=$cnum.':'.$cdom;
                   11360:     my ($suppcount,$cached);
                   11361:     unless ($ignorecache) {
                   11362:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11363:     }
                   11364:     unless (defined($cached)) {
                   11365:         my $chome=&homeserver($cnum,$cdom);
                   11366:         unless ($chome eq 'no_host') {
1.1366    raeburn  11367:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11368:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11369:             ($suppcount,$supptools,$errors) =
                   11370:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11371:                                                          $supptools,$errors);
1.1236    raeburn  11372:         }
                   11373:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11374:     }
                   11375:     return $suppcount;
                   11376: }
                   11377: 
1.379     matthew  11378: #
                   11379: # EXT resource caching routines
                   11380: #
                   11381: 
1.1302    raeburn  11382: {
                   11383: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11384: #
                   11385: # The course for which we cache
                   11386: my $cachedmapkey='';
                   11387: # The cached recursive maps for this course
                   11388: my %cachedmaps=();
                   11389: # When this was last done
                   11390: my $cachedmaptime='';
                   11391: 
1.379     matthew  11392: sub clear_EXT_cache_status {
1.383     albertel 11393:     &delenv('cache.EXT.');
1.379     matthew  11394: }
                   11395: 
                   11396: sub EXT_cache_status {
                   11397:     my ($target_domain,$target_user) = @_;
1.383     albertel 11398:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11399:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11400:         # We know already the user has no data
                   11401:         return 1;
                   11402:     } else {
                   11403:         return 0;
                   11404:     }
                   11405: }
                   11406: 
                   11407: sub EXT_cache_set {
                   11408:     my ($target_domain,$target_user) = @_;
1.383     albertel 11409:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11410:     #&appenv({$cachename => time});
1.379     matthew  11411: }
                   11412: 
1.28      www      11413: # --------------------------------------------------------- Value of a Variable
1.58      www      11414: sub EXT {
1.715     albertel 11415: 
1.1228    raeburn  11416:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11417:     unless ($varname) { return ''; }
1.218     albertel 11418:     #get real user name/domain, courseid and symb
                   11419:     my $courseid;
1.359     albertel 11420:     my $publicuser;
1.427     www      11421:     if ($symbparm) {
                   11422: 	$symbparm=&get_symb_from_alias($symbparm);
                   11423:     }
1.218     albertel 11424:     if (!($uname && $udom)) {
1.790     albertel 11425:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11426:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11427:     } else {
1.620     albertel 11428: 	$courseid=$env{'request.course.id'};
1.218     albertel 11429:     }
1.48      www      11430:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11431:     my $rest;
1.320     albertel 11432:     if (defined($therest[0])) {
1.48      www      11433:        $rest=join('.',@therest);
                   11434:     } else {
                   11435:        $rest='';
                   11436:     }
1.320     albertel 11437: 
1.57      www      11438:     my $qualifierrest=$qualifier;
                   11439:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11440:     my $spacequalifierrest=$space;
                   11441:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11442:     if ($realm eq 'user') {
1.48      www      11443: # --------------------------------------------------------------- user.resource
                   11444: 	if ($space eq 'resource') {
1.651     albertel 11445: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11446: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11447: 		 &&
1.744     albertel 11448: 		 ($symbparm eq &symbread()) ) {	
                   11449: 		# if we are in the middle of processing the resource the
                   11450: 		# get the value we are planning on committing
                   11451:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11452:                     return $Apache::lonhomework::results{$qualifierrest};
                   11453:                 } else {
                   11454:                     return $Apache::lonhomework::history{$qualifierrest};
                   11455:                 }
1.335     albertel 11456: 	    } else {
1.359     albertel 11457: 		my %restored;
1.620     albertel 11458: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11459: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11460: 		} else {
                   11461: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11462: 		}
1.335     albertel 11463: 		return $restored{$qualifierrest};
                   11464: 	    }
1.48      www      11465: # ----------------------------------------------------------------- user.access
                   11466:         } elsif ($space eq 'access') {
1.218     albertel 11467: 	    # FIXME - not supporting calls for a specific user
1.48      www      11468:             return &allowed($qualifier,$rest);
                   11469: # ------------------------------------------ user.preferences, user.environment
                   11470:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11471: 	    if (($uname eq $env{'user.name'}) &&
                   11472: 		($udom eq $env{'user.domain'})) {
                   11473: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11474: 	    } else {
1.359     albertel 11475: 		my %returnhash;
                   11476: 		if (!$publicuser) {
                   11477: 		    %returnhash=&userenvironment($udom,$uname,
                   11478: 						 $qualifierrest);
                   11479: 		}
1.218     albertel 11480: 		return $returnhash{$qualifierrest};
                   11481: 	    }
1.48      www      11482: # ----------------------------------------------------------------- user.course
                   11483:         } elsif ($space eq 'course') {
1.218     albertel 11484: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11485:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11486: # ------------------------------------------------------------------- user.role
                   11487:         } elsif ($space eq 'role') {
1.218     albertel 11488: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11489:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11490:             if ($qualifier eq 'value') {
                   11491: 		return $role;
                   11492:             } elsif ($qualifier eq 'extent') {
                   11493:                 return $where;
                   11494:             }
                   11495: # ----------------------------------------------------------------- user.domain
                   11496:         } elsif ($space eq 'domain') {
1.218     albertel 11497:             return $udom;
1.48      www      11498: # ------------------------------------------------------------------- user.name
                   11499:         } elsif ($space eq 'name') {
1.218     albertel 11500:             return $uname;
1.48      www      11501: # ---------------------------------------------------- Any other user namespace
1.29      www      11502:         } else {
1.359     albertel 11503: 	    my %reply;
                   11504: 	    if (!$publicuser) {
                   11505: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11506: 	    }
                   11507: 	    return $reply{$qualifierrest};
1.48      www      11508:         }
1.236     www      11509:     } elsif ($realm eq 'query') {
                   11510: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11511:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11512: 						[$spacequalifierrest]);
1.620     albertel 11513: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11514:    } elsif ($realm eq 'request') {
1.48      www      11515: # ------------------------------------------------------------- request.browser
                   11516:         if ($space eq 'browser') {
1.1145    bisitz   11517:             return $env{'browser.'.$qualifier};
1.57      www      11518: # ------------------------------------------------------------ request.filename
                   11519:         } else {
1.620     albertel 11520:             return $env{'request.'.$spacequalifierrest};
1.29      www      11521:         }
1.28      www      11522:     } elsif ($realm eq 'course') {
1.48      www      11523: # ---------------------------------------------------------- course.description
1.620     albertel 11524:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11525:     } elsif ($realm eq 'resource') {
1.165     www      11526: 
1.620     albertel 11527: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11528: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11529: 	}
1.693     albertel 11530: 
1.1232    raeburn  11531:         if ($qualifier eq '') {
                   11532: 	    if ($space eq 'title') {
                   11533: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11534: 	        return &gettitle($symbparm);
                   11535: 	    }
1.693     albertel 11536: 	
1.1232    raeburn  11537: 	    if ($space eq 'map') {
                   11538: 	        my ($map) = &decode_symb($symbparm);
                   11539: 	        return &symbread($map);
                   11540: 	    }
                   11541:             if ($space eq 'maptitle') {
                   11542:                 my ($map) = &decode_symb($symbparm);
                   11543:                 return &gettitle($map);
                   11544:             }
                   11545: 	    if ($space eq 'filename') {
                   11546: 	        if ($symbparm) {
                   11547: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11548: 	        }
                   11549: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11550: 	    }
1.1232    raeburn  11551: 
1.1233    raeburn  11552:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11553:                 if ($space eq 'visibleparts') {
                   11554:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11555:                     my $item;
                   11556:                     if (ref($navmap)) {
                   11557:                         my $res = $navmap->getBySymb($symbparm);
                   11558:                         my $parts = $res->parts();
                   11559:                         if (ref($parts) eq 'ARRAY') {
                   11560:                             $item = join(',',@{$parts});
                   11561:                         }
                   11562:                         undef($navmap);
1.1232    raeburn  11563:                     }
1.1233    raeburn  11564:                     return $item;
1.1232    raeburn  11565:                 }
                   11566:             }
                   11567:         }
1.693     albertel 11568: 
1.1301    raeburn  11569: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11570: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11571:         if (($courseid eq '') && ($cid)) {
                   11572:             $courseid = $cid;
                   11573:         }
                   11574: 	if (($symbparm && $courseid) && 
                   11575: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11576: 
1.218     albertel 11577: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11578: 
1.60      www      11579: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11580: 	    my $symbp=$symbparm;
1.1301    raeburn  11581: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11582: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11583:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11584: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11585: 	    if (($env{'user.name'} eq $uname) &&
                   11586: 		($env{'user.domain'} eq $udom)) {
                   11587: 		$section=$env{'request.course.sec'};
1.733     raeburn  11588:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11589:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11590: 	    } else {
1.539     albertel 11591: 		if (! defined($usection)) {
1.551     albertel 11592: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11593: 		} else {
                   11594: 		    $section = $usection;
                   11595: 		}
1.733     raeburn  11596:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11597: 	    }
                   11598: 
                   11599: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11600: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11601:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11602: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11603: 
1.593     albertel 11604: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11605: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11606:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11607: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11608: 
1.60      www      11609: # ----------------------------------------------------------- first, check user
1.624     albertel 11610: 
1.1301    raeburn  11611: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11612:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11613: 				       ([$courselevelr,'resource'],
                   11614: 					[$courselevelm,'map'     ],
1.1301    raeburn  11615:                                         [$courseleveli,'map'     ],
1.927     albertel 11616: 					[$courselevel, 'course'  ]));
1.931     albertel 11617: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11618: 
1.594     albertel 11619: # ------------------------------------------------ second, check some of course
1.684     raeburn  11620:             my $coursereply;
1.691     raeburn  11621:             if (@groups > 0) {
                   11622:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11623:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11624:                                        $mapp,\$recursed,\@recurseup);
                   11625:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11626:             }
1.96      www      11627: 
1.684     raeburn  11628: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11629: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11630: 				  'course',$mapp,\$recursed,\@recurseup,
                   11631:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11632: 				  ([$seclevelr,   'resource'],
                   11633: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11634:                                    [$secleveli,   'map'     ],
1.927     albertel 11635: 				   [$seclevel,    'course'  ],
                   11636: 				   [$courselevelr,'resource']));
                   11637: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11638: 
1.60      www      11639: # ------------------------------------------------------ third, check map parms
1.218     albertel 11640: 	    my %parmhash=();
                   11641: 	    my $thisparm='';
                   11642: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11643: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11644: 		    &GDBM_READER(),0640)) {
1.218     albertel 11645: 		$thisparm=$parmhash{$symbparm};
                   11646: 		untie(%parmhash);
                   11647: 	    }
1.927     albertel 11648: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11649: 	}
1.594     albertel 11650: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11651:  
                   11652:         my $what = $spacequalifierrest;
                   11653: 	$what=~s/\./\_/;
1.282     albertel 11654: 	my $filename;
                   11655: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11656: 	if ($symbparm) {
1.409     www      11657: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11658: 	} else {
1.620     albertel 11659: 	    $filename=$env{'request.filename'};
1.282     albertel 11660: 	}
1.1362    raeburn  11661:         my $toolsymb;
                   11662:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11663:             $toolsymb = $symbparm;
                   11664:         }
                   11665: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11666: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11667: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11668: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11669: 
1.1301    raeburn  11670: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11671: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11672: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11673: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11674: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11675: 				     'course',$mapp,\$recursed,\@recurseup,
                   11676:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11677: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11678:                                       [$courseleveli,'map'   ],
1.927     albertel 11679: 				      [$courselevel, 'course']));
                   11680: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11681: 	}
1.145     www      11682: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11683: 	unless ($space eq '0') {
1.336     albertel 11684: 	    my @parts=split(/_/,$space);
                   11685: 	    my $id=pop(@parts);
                   11686: 	    my $part=join('_',@parts);
                   11687: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11688: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11689: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11690: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11691: 	}
1.395     albertel 11692: 	if ($recurse) { return undef; }
1.1362    raeburn  11693: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11694: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11695: # ---------------------------------------------------- Any other user namespace
                   11696:     } elsif ($realm eq 'environment') {
                   11697: # ----------------------------------------------------------------- environment
1.620     albertel 11698: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11699: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11700: 	} else {
1.770     albertel 11701: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11702: 		return '';
                   11703: 	    }
1.219     albertel 11704: 	    my %returnhash=&userenvironment($udom,$uname,
                   11705: 					    $spacequalifierrest);
                   11706: 	    return $returnhash{$spacequalifierrest};
                   11707: 	}
1.28      www      11708:     } elsif ($realm eq 'system') {
1.48      www      11709: # ----------------------------------------------------------------- system.time
                   11710: 	if ($space eq 'time') {
                   11711: 	    return time;
                   11712:         }
1.696     albertel 11713:     } elsif ($realm eq 'server') {
                   11714: # ----------------------------------------------------------------- system.time
                   11715: 	if ($space eq 'name') {
                   11716: 	    return $ENV{'SERVER_NAME'};
                   11717:         }
1.28      www      11718:     }
1.48      www      11719:     return '';
1.61      www      11720: }
                   11721: 
1.927     albertel 11722: sub get_reply {
                   11723:     my ($reply_value) = @_;
1.940     raeburn  11724:     if (ref($reply_value) eq 'ARRAY') {
                   11725:         if (wantarray) {
                   11726: 	    return @$reply_value;
                   11727:         }
                   11728:         return $reply_value->[0];
                   11729:     } else {
                   11730:         return $reply_value;
1.927     albertel 11731:     }
                   11732: }
                   11733: 
1.691     raeburn  11734: sub check_group_parms {
1.1301    raeburn  11735:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11736:         $recursed,$recurseupref) = @_;
                   11737:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11738:                   [$what,'course']);
                   11739:     my $coursereply;
1.691     raeburn  11740:     foreach my $group (@{$groups}) {
1.1301    raeburn  11741:         my @groupitems = ();
1.691     raeburn  11742:         foreach my $level (@levels) {
1.927     albertel 11743:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11744:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11745:         }
1.1301    raeburn  11746:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11747:                                    $env{'course.'.$courseid.'.domain'},
                   11748:                                    'course',$mapp,$recursed,$recurseupref,
                   11749:                                    $courseid,'.['.$group.'].',$what,
                   11750:                                    @groupitems);
                   11751:         last if (defined($coursereply));
1.691     raeburn  11752:     }
                   11753:     return $coursereply;
                   11754: }
                   11755: 
1.1301    raeburn  11756: sub get_map_hierarchy {
1.1302    raeburn  11757:     my ($mapname,$courseid) = @_;
                   11758:     my @recurseup = ();
1.1301    raeburn  11759:     if ($mapname) {
1.1302    raeburn  11760:         if (($cachedmapkey eq $courseid) &&
                   11761:             (abs($cachedmaptime-time)<5)) {
                   11762:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11763:                 return @{$cachedmaps{$mapname}};
                   11764:             }
                   11765:         }
1.1301    raeburn  11766:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11767:         if (ref($navmap)) {
                   11768:             @recurseup = $navmap->recurseup_maps($mapname);
                   11769:             undef($navmap);
1.1302    raeburn  11770:             $cachedmaps{$mapname} = \@recurseup;
                   11771:             $cachedmaptime=time;
                   11772:             $cachedmapkey=$courseid;
1.1301    raeburn  11773:         }
                   11774:     }
                   11775:     return @recurseup;
                   11776: }
                   11777: 
1.1302    raeburn  11778: }
                   11779: 
1.691     raeburn  11780: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11781:     my ($courseid,@groups) = @_;
                   11782:     @groups = sort(@groups);
1.691     raeburn  11783:     return @groups;
                   11784: }
                   11785: 
1.395     albertel 11786: sub packages_tab_default {
1.1362    raeburn  11787:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11788:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11789: 
                   11790:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11791:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11792: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11793: 	if ($pack_type eq 'default') {
                   11794: 	    $do_default=1;
                   11795: 	} elsif ($pack_type eq 'extension') {
                   11796: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11797: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11798: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11799: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11800: 	}
                   11801:     }
                   11802:     # first look for a package that matches the requested part id
                   11803:     foreach my $package (@specifics) {
                   11804: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11805: 	next if ($pack_part ne $part);
                   11806: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11807: 	    return $packagetab{"$pack_type&$name&default"};
                   11808: 	}
                   11809:     }
                   11810:     # look for any possible matching non extension_ package
                   11811:     foreach my $package (@specifics) {
                   11812: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11813: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11814: 	    return $packagetab{"$pack_type&$name&default"};
                   11815: 	}
1.585     albertel 11816: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11817: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11818: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11819: 	}
                   11820:     }
1.738     albertel 11821:     # look for any posible extension_ match
                   11822:     foreach my $package (@extension) {
                   11823: 	my ($package,$pack_type)=@{$package};
                   11824: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11825: 	    return $packagetab{"$pack_type&$name&default"};
                   11826: 	}
                   11827: 	if (defined($packagetab{$package."&$name&default"})) {
                   11828: 	    return $packagetab{$package."&$name&default"};
                   11829: 	}
                   11830:     }
                   11831:     # look for a global default setting
                   11832:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11833: 	return $packagetab{"default&$name&default"};
                   11834:     }
1.395     albertel 11835:     return undef;
                   11836: }
                   11837: 
1.334     albertel 11838: sub add_prefix_and_part {
                   11839:     my ($prefix,$part)=@_;
                   11840:     my $keyroot;
                   11841:     if (defined($prefix) && $prefix !~ /^__/) {
                   11842: 	# prefix that has a part already
                   11843: 	$keyroot=$prefix;
                   11844:     } elsif (defined($prefix)) {
                   11845: 	# prefix that is missing a part
                   11846: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11847:     } else {
                   11848: 	# no prefix at all
                   11849: 	if (defined($part)) { $keyroot='_'.$part; }
                   11850:     }
                   11851:     return $keyroot;
                   11852: }
                   11853: 
1.71      www      11854: # ---------------------------------------------------------------- Get metadata
                   11855: 
1.599     albertel 11856: my %metaentry;
1.1070    www      11857: my %importedpartids;
1.1369    raeburn  11858: my %importedrespids;
1.71      www      11859: sub metadata {
1.1362    raeburn  11860:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11861:     $uri=&declutter($uri);
1.288     albertel 11862:     # if it is a non metadata possible uri return quickly
1.529     albertel 11863:     if (($uri eq '') || 
                   11864: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11865: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11866:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11867: 	return undef;
                   11868:     }
1.1261    raeburn  11869:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11870: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11871: 	return undef;
1.288     albertel 11872:     }
1.73      www      11873:     my $filename=$uri;
                   11874:     $uri=~s/\.meta$//;
1.172     www      11875: #
                   11876: # Is the metadata already cached?
1.177     www      11877: # Look at timestamp of caching
1.172     www      11878: # Everything is cached by the main uri, libraries are never directly cached
                   11879: #
1.428     albertel 11880:     if (!defined($liburi)) {
1.599     albertel 11881: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11882: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11883:     }
1.1362    raeburn  11884: 
                   11885: #
                   11886: # If the uri is for an external tool the file from
                   11887: # which metadata should be retrieved depends on whether
                   11888: # the tool had been configured to be gradable (set in the Course
                   11889: # Editor or Resource Editor).
                   11890: #
                   11891: # If a valid symb has been included as the third arg in the call
                   11892: # to &metadata() that can be used to retrieve the value of
                   11893: # parameter_0_gradable set for the resource, and included in the
                   11894: # uploaded map containing the tool. The value is retrieved via
                   11895: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11896: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11897: # is retrieved via &get().
                   11898: #
                   11899: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11900: # hiddenresource and encrypturl (during course initialization)
                   11901: # the map-level parameter for resource.0.gradable included in the 
                   11902: # uploaded map containing the tool will not yet have been stored
                   11903: # in the user_course_parms.db file for the user's session, so in 
                   11904: # this case fall back to retrieving gradable status from the
                   11905: # exttool_$marker.db file.
1.1362    raeburn  11906: #
                   11907: # In order to avoid an infinite loop, &metadata() will return
                   11908: # before a call to &EXT(), if the uri is for an external tool
                   11909: # and the $what for which metadata is being requested is
                   11910: # parameter_0_gradable or 0_gradable.
                   11911: #
                   11912: 
                   11913:     if ($uri =~ /ext\.tool$/) {
                   11914:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11915:             return;
                   11916:         } else {
                   11917:             my ($checked,$use_passback);
                   11918:             if ($toolsymb ne '') {
                   11919:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11920:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11921:                     $checked = 1;
                   11922:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11923:                         $use_passback = 1;
                   11924:                     }
                   11925:                 }
                   11926:             }
                   11927:             unless ($checked) {
                   11928:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11929:                 $marker=~s/\D//g;
1.1363    raeburn  11930:                 if ($marker) {
1.1362    raeburn  11931:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11932:                     $use_passback = $toolsettings{'gradable'};
                   11933:                 }
                   11934:             }
                   11935:             if ($use_passback) {
                   11936:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11937:             } else {
                   11938:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11939:             }
                   11940:         }
                   11941:     }
                   11942: 
1.428     albertel 11943:     {
1.1069    www      11944: # Imported parts would go here
1.1369    raeburn  11945:         my @origfiletagids=();
1.1069    www      11946:         my $importedparts=0;
1.1369    raeburn  11947: 
                   11948: # Imported responseids would go here
                   11949:         my $importedresponses=0;
1.172     www      11950: #
                   11951: # Is this a recursive call for a library?
                   11952: #
1.599     albertel 11953: #	if (! exists($metacache{$uri})) {
                   11954: #	    $metacache{$uri}={};
                   11955: #	}
1.924     albertel 11956: 	my $cachetime = 60*60;
1.171     www      11957:         if ($liburi) {
                   11958: 	    $liburi=&declutter($liburi);
                   11959:             $filename=$liburi;
1.401     bowersj2 11960:         } else {
1.599     albertel 11961: 	    &devalidate_cache_new('meta',$uri);
                   11962: 	    undef(%metaentry);
1.401     bowersj2 11963: 	}
1.140     www      11964:         my %metathesekeys=();
1.73      www      11965:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11966: 	my $metastring;
1.1140    www      11967: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11968: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11969: 	    $metastring = 
1.929     albertel 11970: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11971: 					  ('grade_target' => 'meta'));
                   11972: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11973: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11974:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11975: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11976: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11977: 	    $metastring=&getfile($file);
1.489     albertel 11978: 	}
1.208     albertel 11979:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11980:         my $token;
1.140     www      11981:         undef %metathesekeys;
1.71      www      11982:         while ($token=$parser->get_token) {
1.339     albertel 11983: 	    if ($token->[0] eq 'S') {
                   11984: 		if (defined($token->[2]->{'package'})) {
1.172     www      11985: #
                   11986: # This is a package - get package info
                   11987: #
1.339     albertel 11988: 		    my $package=$token->[2]->{'package'};
                   11989: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11990: 		    if (defined($token->[2]->{'id'})) { 
                   11991: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11992: 		    }
1.599     albertel 11993: 		    if ($metaentry{':packages'}) {
                   11994: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11995: 		    } else {
1.599     albertel 11996: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11997: 		    }
1.736     albertel 11998: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11999: 			my $part=$keyroot;
                   12000: 			$part=~s/^\_//;
1.736     albertel 12001: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12002: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12003: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12004: 			    # ignore package.tab specified default values
                   12005:                             # here &package_tab_default() will fetch those
                   12006: 			    if ($subp eq 'default') { next; }
1.736     albertel 12007: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12008: 			    my $unikey;
                   12009: 			    if ($pack =~ /_0$/) {
                   12010: 				$unikey='parameter_0_'.$name;
                   12011: 				$part=0;
                   12012: 			    } else {
                   12013: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12014: 			    }
1.339     albertel 12015: 			    if ($subp eq 'display') {
                   12016: 				$value.=' [Part: '.$part.']';
                   12017: 			    }
1.599     albertel 12018: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12019: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12020: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12021: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12022: 			    }
1.599     albertel 12023: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12024: 				$metaentry{':'.$unikey}=
                   12025: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12026: 			    }
1.339     albertel 12027: 			}
                   12028: 		    }
                   12029: 		} else {
1.172     www      12030: #
                   12031: # This is not a package - some other kind of start tag
1.339     albertel 12032: #
                   12033: 		    my $entry=$token->[1];
1.1068    www      12034: 		    my $unikey='';
1.175     www      12035: 
1.339     albertel 12036: 		    if ($entry eq 'import') {
1.175     www      12037: #
                   12038: # Importing a library here
1.339     albertel 12039: #
1.1067    www      12040:                         my $location=$parser->get_text('/import');
                   12041:                         my $dir=$filename;
                   12042:                         $dir=~s|[^/]*$||;
                   12043:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12044: 
                   12045:                         my $importid=$token->[2]->{'id'};
1.1068    www      12046:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12047: #
                   12048: # Check metadata for imported file to
                   12049: # see if it contained response items
                   12050: #
1.1372    raeburn  12051:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12052:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12053:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12054:                                                            $depthcount+1));
                   12055:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12056:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12057:                                                              undef,$depthcount+1);
                   12058:                             if ($libresponseorder ne '') {
                   12059:                                 if ($#origfiletagids<0) {
                   12060:                                     undef(%importedrespids);
                   12061:                                     undef(%importedpartids);
                   12062:                                 }
1.1373    raeburn  12063:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12064:                                 if (@respids) {
                   12065:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12066:                                 }
                   12067:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12068:                                     $importedresponses = 1;
1.1369    raeburn  12069: # We need to get the original file and the imported file to get the response order correct
                   12070: # Load and inspect original file
1.1372    raeburn  12071:                                     if ($#origfiletagids<0) {
                   12072:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12073:                                         $origfile=&getfile($origfilelocation);
                   12074:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12075:                                     }
1.1369    raeburn  12076:                                 }
                   12077:                             }
                   12078:                         }
1.1370    raeburn  12079: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12080: # hash populated for imported library file
                   12081:                         %metaentry = %currmetaentry;
                   12082:                         undef(%currmetaentry);
1.1374    raeburn  12083:                         if ($importmode eq 'part') {
1.1068    www      12084: # Import as part(s)
1.1069    www      12085:                            $importedparts=1;
                   12086: # We need to get the original file and the imported file to get the part order correct
                   12087: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12088: # Load and inspect original file if we didn't do that already
                   12089:                            if ($#origfiletagids<0) {
                   12090:                                undef(%importedrespids);
                   12091:                                undef(%importedpartids);
                   12092:                                if ($origfile eq '') {
                   12093:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12094:                                    $origfile=&getfile($origfilelocation);
                   12095:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12096:                                }
1.1070    www      12097:                            }
1.1372    raeburn  12098:                            my @impfilepartids;
                   12099: # If <partorder> tag is included in metadata for the imported file
                   12100: # get the parts in the imported file from that.
                   12101:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12102:                                %currmetaentry = %metaentry;
                   12103:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12104:                                                             $depthcount+1);
                   12105:                                %metaentry = %currmetaentry;
                   12106:                                undef(%currmetaentry);
                   12107:                                if ($libpartorder ne '') {
                   12108:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12109:                                }
                   12110:                            } else {
                   12111: # If no <partorder> tag available, load and inspect imported file
                   12112:                                my $impfile=&getfile($location);
                   12113:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12114:                            }
1.1069    www      12115:                            if ($#impfilepartids>=0) {
                   12116: # This problem had parts
1.1070    www      12117:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12118:                            } else {
                   12119: # Importing by turning a single problem into a problem part
                   12120: # It gets the import-tags ID as part-ID
                   12121:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12122:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12123:                            }
1.1068    www      12124:                         } else {
1.1374    raeburn  12125: # Import as problem or as normal import
                   12126:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12127:                             unless ($importmode eq 'problem') {
1.1068    www      12128: # Normal import
1.1374    raeburn  12129:                                 if (defined($token->[2]->{'id'})) {
                   12130:                                     $unikey.='_'.$token->[2]->{'id'};
                   12131:                                 }
                   12132:                             }
                   12133: # Check metadata for imported file to
                   12134: # see if it contained parts
                   12135:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12136:                                 %currmetaentry = %metaentry;
                   12137:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12138:                                                              $depthcount+1);
                   12139:                                 %metaentry = %currmetaentry;
                   12140:                                 undef(%currmetaentry);
                   12141:                                 if ($libpartorder ne '') {
                   12142:                                     $importedparts = 1;
                   12143:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12144:                                 }
                   12145:                             }
1.1067    www      12146:                         }
1.339     albertel 12147: 			if ($depthcount<20) {
1.736     albertel 12148: 			    my $metadata = 
1.1362    raeburn  12149: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12150: 					  $depthcount+1);
                   12151: 			    foreach my $meta (split(',',$metadata)) {
                   12152: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12153: 				$metathesekeys{$meta}=1;
1.339     albertel 12154: 			    }
1.1068    www      12155:                         }
1.1067    www      12156: 		    } else {
                   12157: #
                   12158: # Not importing, some other kind of non-package, non-library start tag
                   12159: # 
                   12160:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12161:                         if (defined($token->[2]->{'id'})) {
                   12162:                             $unikey.='_'.$token->[2]->{'id'};
                   12163:                         }
1.339     albertel 12164: 			if (defined($token->[2]->{'name'})) { 
                   12165: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12166: 			}
                   12167: 			$metathesekeys{$unikey}=1;
1.736     albertel 12168: 			foreach my $param (@{$token->[3]}) {
                   12169: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12170: 				$token->[2]->{$param};
1.339     albertel 12171: 			}
                   12172: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12173: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12174: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12175: 		 # only ws inside the tag, and not in default, so use default
                   12176: 		 # as value
1.599     albertel 12177: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12178: 			} elsif ( $internaltext =~ /\S/ ) {
                   12179: 		  # something interesting inside the tag
                   12180: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12181: 			} else {
1.908     albertel 12182: 		  # no interesting values, don't set a default
1.339     albertel 12183: 			}
1.172     www      12184: # end of not-a-package not-a-library import
1.339     albertel 12185: 		    }
1.172     www      12186: # end of not-a-package start tag
1.339     albertel 12187: 		}
1.172     www      12188: # the next is the end of "start tag"
1.339     albertel 12189: 	    }
                   12190: 	}
1.483     albertel 12191: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12192: 	$extension = lc($extension);
                   12193: 	if ($extension eq 'htm') { $extension='html'; }
                   12194: 
1.737     albertel 12195: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12196: 	    #no specific packages #how's our extension
                   12197: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12198: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12199: 					 \%metathesekeys);
                   12200: 	}
1.883     albertel 12201: 
                   12202: 	if (!exists($metaentry{':packages'})
                   12203: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12204: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12205: 		#no specific packages well let's get default then
                   12206: 		if ($key!~/^default&/) { next; }
1.488     albertel 12207: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12208: 					     \%metathesekeys);
                   12209: 	    }
                   12210: 	}
1.338     www      12211: # are there custom rights to evaluate
1.599     albertel 12212: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12213: 
1.338     www      12214:     #
                   12215:     # Importing a rights file here
1.339     albertel 12216:     #
                   12217: 	    unless ($depthcount) {
1.599     albertel 12218: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12219: 		my $dir=$filename;
                   12220: 		$dir=~s|[^/]*$||;
                   12221: 		$location=&filelocation($dir,$location);
1.736     albertel 12222: 		my $rights_metadata =
1.1362    raeburn  12223: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12224: 			      $depthcount+1);
                   12225: 		foreach my $rights (split(',',$rights_metadata)) {
                   12226: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12227: 		    $metathesekeys{$rights}=1;
1.339     albertel 12228: 		}
                   12229: 	    }
                   12230: 	}
1.737     albertel 12231: 	# uniqifiy package listing
                   12232: 	my %seen;
                   12233: 	my @uniq_packages =
                   12234: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12235: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12236: 
1.1369    raeburn  12237:         if (($importedresponses) || ($importedparts)) {
                   12238:             if ($importedparts) {
1.1070    www      12239: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12240:                 $metaentry{':partorder'}='';
                   12241:                 $metathesekeys{'partorder'}=1;
                   12242:             }
                   12243:             if ($importedresponses) {
                   12244: # We had imported responses and need to rebuil responseorder
                   12245:                 $metaentry{':responseorder'}='';
                   12246:                 $metathesekeys{'responseorder'}=1;
                   12247:             }
                   12248:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12249:                 my $origid = $origfiletagids[$index+1];
                   12250:                 if ($origfiletagids[$index] eq 'part') {
                   12251: # Original part, part of the problem
                   12252:                     if ($importedparts) {
                   12253:                         $metaentry{':partorder'}.=','.$origid;
                   12254:                     }
                   12255:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12256:                     if ($importedparts) {
                   12257: # We have imported parts at this position
1.1373    raeburn  12258:                         if ($importedpartids{$origid} ne '') {
                   12259:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12260:                         }
1.1369    raeburn  12261:                     }
                   12262:                     if ($importedresponses) {
                   12263: # We have imported responses at this position
1.1373    raeburn  12264:                         if ($importedrespids{$origid} ne '') {
                   12265:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12266:                         }
                   12267:                     }
                   12268:                 } else {
                   12269: # Original response item, part of the problem
                   12270:                     if ($importedresponses) {
                   12271:                         $metaentry{':responseorder'}.=','.$origid;
                   12272:                     }
                   12273:                 }
                   12274:             }
                   12275:             if ($importedparts) {
                   12276:                 $metaentry{':partorder'}=~s/^\,//;
                   12277:             }
                   12278:             if ($importedresponses) {
                   12279:                 $metaentry{':responseorder'}=~s/^\,//;
                   12280:             }
1.1070    www      12281:         }
1.737     albertel 12282: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12283: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12284: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12285:         unless ($liburi) {
                   12286: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12287:         }
1.177     www      12288: # this is the end of "was not already recently cached
1.71      www      12289:     }
1.599     albertel 12290:     return $metaentry{':'.$what};
1.261     albertel 12291: }
                   12292: 
1.488     albertel 12293: sub metadata_create_package_def {
1.483     albertel 12294:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12295:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12296:     if ($subp eq 'default') { next; }
                   12297:     
1.599     albertel 12298:     if (defined($metaentry{':packages'})) {
                   12299: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12300:     } else {
1.599     albertel 12301: 	$metaentry{':packages'}=$package;
1.483     albertel 12302:     }
                   12303:     my $value=$packagetab{$key};
                   12304:     my $unikey;
                   12305:     $unikey='parameter_0_'.$name;
1.599     albertel 12306:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12307:     $$metathesekeys{$unikey}=1;
1.599     albertel 12308:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12309: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12310:     }
1.599     albertel 12311:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12312: 	$metaentry{':'.$unikey}=
                   12313: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12314:     }
                   12315: }
                   12316: 
1.261     albertel 12317: sub metadata_generate_part0 {
                   12318:     my ($metadata,$metacache,$uri) = @_;
                   12319:     my %allnames;
1.737     albertel 12320:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12321: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12322: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12323: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12324: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12325: 	    $allnames{$name}=$part;
                   12326: 	  }
                   12327: 	}
                   12328:     }
                   12329:     foreach my $name (keys(%allnames)) {
                   12330:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12331:       my $key=":parameter_0_$name";
1.261     albertel 12332:       $$metacache{"$key.part"}='0';
                   12333:       $$metacache{"$key.name"}=$name;
1.428     albertel 12334:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12335: 					   $allnames{$name}.'_'.$name.
                   12336: 					   '.type'};
1.428     albertel 12337:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12338: 			     '.display'};
1.644     www      12339:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12340:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12341:       $$metacache{"$key.display"}=$olddis;
                   12342:     }
1.71      www      12343: }
                   12344: 
1.764     albertel 12345: # ------------------------------------------------------ Devalidate title cache
                   12346: 
                   12347: sub devalidate_title_cache {
                   12348:     my ($url)=@_;
                   12349:     if (!$env{'request.course.id'}) { return; }
                   12350:     my $symb=&symbread($url);
                   12351:     if (!$symb) { return; }
                   12352:     my $key=$env{'request.course.id'}."\0".$symb;
                   12353:     &devalidate_cache_new('title',$key);
                   12354: }
                   12355: 
1.1014    droeschl 12356: # ------------------------------------------------- Get the title of a course
                   12357: 
                   12358: sub current_course_title {
                   12359:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12360: }
1.301     www      12361: # ------------------------------------------------- Get the title of a resource
                   12362: 
                   12363: sub gettitle {
                   12364:     my $urlsymb=shift;
                   12365:     my $symb=&symbread($urlsymb);
1.534     albertel 12366:     if ($symb) {
1.620     albertel 12367: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12368: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12369: 	if (defined($cached)) { 
                   12370: 	    return $result;
                   12371: 	}
1.534     albertel 12372: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12373: 	my $title='';
1.907     albertel 12374: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12375: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12376: 	} else {
                   12377: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12378: 		    &GDBM_READER(),0640)) {
                   12379: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12380: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12381: 		untie(%bighash);
                   12382: 	    }
1.534     albertel 12383: 	}
                   12384: 	$title=~s/\&colon\;/\:/gs;
                   12385: 	if ($title) {
1.1159    www      12386: # Remember both $symb and $title for dynamic metadata
                   12387:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12388:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12389: # Cache this title and then return it
1.599     albertel 12390: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12391: 	}
                   12392: 	$urlsymb=$url;
                   12393:     }
                   12394:     my $title=&metadata($urlsymb,'title');
                   12395:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12396:     return $title;
1.301     www      12397: }
1.613     albertel 12398: 
1.614     albertel 12399: sub get_slot {
                   12400:     my ($which,$cnum,$cdom)=@_;
                   12401:     if (!$cnum || !$cdom) {
1.790     albertel 12402: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12403: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12404: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12405:     }
1.703     albertel 12406:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12407:     my %slotinfo;
                   12408:     if (exists($remembered{$key})) {
                   12409: 	$slotinfo{$which} = $remembered{$key};
                   12410:     } else {
                   12411: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12412: 	&Apache::lonhomework::showhash(%slotinfo);
                   12413: 	my ($tmp)=keys(%slotinfo);
                   12414: 	if ($tmp=~/^error:/) { return (); }
                   12415: 	$remembered{$key} = $slotinfo{$which};
                   12416:     }
1.616     albertel 12417:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12418: 	return %{$slotinfo{$which}};
                   12419:     }
                   12420:     return $slotinfo{$which};
1.614     albertel 12421: }
1.1150    raeburn  12422: 
                   12423: sub get_reservable_slots {
                   12424:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12425:     my $now = time;
                   12426:     my $reservable_info;
                   12427:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12428:     if (exists($remembered{$key})) {
                   12429:         $reservable_info = $remembered{$key};
                   12430:     } else {
                   12431:         my %resv;
                   12432:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12433:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12434:         $reservable_info = \%resv;
                   12435:         $remembered{$key} = $reservable_info;
                   12436:     }
                   12437:     return $reservable_info;
                   12438: }
                   12439: 
                   12440: sub get_course_slots {
                   12441:     my ($cnum,$cdom) = @_;
                   12442:     my $hashid=$cnum.':'.$cdom;
                   12443:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12444:     if (defined($cached)) {
                   12445:         if (ref($result) eq 'HASH') {
                   12446:             return %{$result};
                   12447:         }
                   12448:     } else {
                   12449:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12450:         my ($tmp) = keys(%slots);
                   12451:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12452:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12453:             return %slots;
                   12454:         }
                   12455:     }
                   12456:     return;
                   12457: }
                   12458: 
                   12459: sub devalidate_slots_cache {
                   12460:     my ($cnum,$cdom)=@_;
                   12461:     my $hashid=$cnum.':'.$cdom;
                   12462:     &devalidate_cache_new('allslots',$hashid);
                   12463: }
                   12464: 
1.1181    raeburn  12465: sub get_coursechange {
                   12466:     my ($cdom,$cnum) = @_;
                   12467:     if ($cdom eq '' || $cnum eq '') {
                   12468:         return unless ($env{'request.course.id'});
                   12469:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12470:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12471:     }
                   12472:     my $hashid=$cdom.'_'.$cnum;
                   12473:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12474:     if ((defined($cached)) && ($change ne '')) {
                   12475:         return $change;
                   12476:     } else {
                   12477:         my %crshash;
                   12478:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12479:         if ($crshash{'internal.contentchange'} eq '') {
                   12480:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12481:             if ($change eq '') {
                   12482:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12483:                 $change = $crshash{'internal.created'};
                   12484:             }
                   12485:         } else {
                   12486:             $change = $crshash{'internal.contentchange'};
                   12487:         }
                   12488:         my $cachetime = 600;
                   12489:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12490:     }
                   12491:     return $change;
                   12492: }
                   12493: 
                   12494: sub devalidate_coursechange_cache {
                   12495:     my ($cnum,$cdom)=@_;
                   12496:     my $hashid=$cnum.':'.$cdom;
                   12497:     &devalidate_cache_new('crschange',$hashid);
                   12498: }
                   12499: 
1.31      www      12500: # ------------------------------------------------- Update symbolic store links
                   12501: 
                   12502: sub symblist {
                   12503:     my ($mapname,%newhash)=@_;
1.438     www      12504:     $mapname=&deversion(&declutter($mapname));
1.31      www      12505:     my %hash;
1.620     albertel 12506:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12507:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12508:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12509: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12510: 		next if ($url eq 'last_known'
                   12511: 			 && $env{'form.no_update_last_known'});
                   12512: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12513: 						    $newhash{$url}->[1],
                   12514: 						    $newhash{$url}->[0]);
1.191     harris41 12515:             }
1.31      www      12516:             if (untie(%hash)) {
                   12517: 		return 'ok';
                   12518:             }
                   12519:         }
                   12520:     }
                   12521:     return 'error';
1.212     www      12522: }
                   12523: 
                   12524: # --------------------------------------------------------------- Verify a symb
                   12525: 
                   12526: sub symbverify {
1.1190    raeburn  12527:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12528:     my $thisfn=$thisurl;
1.439     www      12529:     $thisfn=&declutter($thisfn);
1.215     www      12530: # direct jump to resource in page or to a sequence - will construct own symbs
                   12531:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12532: # check URL part
1.409     www      12533:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12534: 
1.431     www      12535:     unless ($url eq $thisfn) { return 0; }
1.213     www      12536: 
1.216     www      12537:     $symb=&symbclean($symb);
1.510     www      12538:     $thisurl=&deversion($thisurl);
1.439     www      12539:     $thisfn=&deversion($thisfn);
1.213     www      12540: 
                   12541:     my %bighash;
                   12542:     my $okay=0;
1.431     www      12543: 
1.620     albertel 12544:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12545:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12546:         my $noclutter;
1.1032    raeburn  12547:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12548:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12549:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12550:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12551:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12552:                 $noclutter = 1;
                   12553:             }
                   12554:         }
                   12555:         my $ids;
                   12556:         if ($noclutter) {
                   12557:             $ids=$bighash{'ids_'.$thisurl};
                   12558:         } else {
                   12559:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12560:         }
1.1102    raeburn  12561:         unless ($ids) {
                   12562:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12563:             $ids=$bighash{$idkey};
1.216     www      12564:         }
                   12565:         if ($ids) {
                   12566: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12567:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12568:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12569:             }
1.800     albertel 12570: 	    foreach my $id (split(/\,/,$ids)) {
                   12571: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12572:                if (
                   12573:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12574:    eq $symb) {
                   12575:                    if (ref($encstate)) {
                   12576:                        $$encstate = $bighash{'encrypted_'.$id};
                   12577:                    }
1.620     albertel 12578: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12579: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12580:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12581: 		       $okay=1;
1.1202    raeburn  12582:                        last;
1.582     albertel 12583: 		   }
                   12584: 	       }
1.216     www      12585: 	   }
                   12586:         }
1.213     www      12587: 	untie(%bighash);
                   12588:     }
                   12589:     return $okay;
1.31      www      12590: }
                   12591: 
1.210     www      12592: # --------------------------------------------------------------- Clean-up symb
                   12593: 
                   12594: sub symbclean {
                   12595:     my $symb=shift;
1.568     albertel 12596:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12597: # remove version from map
                   12598:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12599: 
1.210     www      12600: # remove version from URL
                   12601:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12602: 
1.507     www      12603: # remove wrapper
                   12604: 
1.510     www      12605:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12606:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12607:     return $symb;
1.409     www      12608: }
                   12609: 
                   12610: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12611: 
                   12612: sub encode_symb {
                   12613:     my ($map,$resid,$url)=@_;
                   12614:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12615: }
1.409     www      12616: 
                   12617: sub decode_symb {
1.568     albertel 12618:     my $symb=shift;
                   12619:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12620:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12621:     return (&fixversion($map),$resid,&fixversion($url));
                   12622: }
                   12623: 
                   12624: sub fixversion {
                   12625:     my $fn=shift;
1.609     banghart 12626:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12627:     my %bighash;
                   12628:     my $uri=&clutter($fn);
1.620     albertel 12629:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12630: # is this cached?
1.599     albertel 12631:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12632:     if (defined($cached)) { return $result; }
                   12633: # unfortunately not cached, or expired
1.620     albertel 12634:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12635: 	    &GDBM_READER(),0640)) {
                   12636:  	if ($bighash{'version_'.$uri}) {
                   12637:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12638:  	    unless (($version eq 'mostrecent') || 
                   12639: 		    ($version==&getversion($uri))) {
1.440     www      12640:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12641:  	    }
                   12642:  	}
                   12643:  	untie %bighash;
1.413     www      12644:     }
1.599     albertel 12645:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12646: }
                   12647: 
                   12648: sub deversion {
                   12649:     my $url=shift;
                   12650:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12651:     return $url;
1.210     www      12652: }
                   12653: 
1.31      www      12654: # ------------------------------------------------------ Return symb list entry
                   12655: 
                   12656: sub symbread {
1.1282    raeburn  12657:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12658:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12659:     if (defined($env{$cache_str})) {
                   12660:         if ($ignorecachednull) {
                   12661:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12662:         } else {
                   12663:             return $env{$cache_str};
                   12664:         }
                   12665:     }
1.242     www      12666: # no filename provided? try from environment
1.1265    raeburn  12667:     unless ($thisfn) {
1.620     albertel 12668:         if ($env{'request.symb'}) {
                   12669: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12670: 	}
1.620     albertel 12671: 	$thisfn=$env{'request.filename'};
1.44      www      12672:     }
1.569     albertel 12673:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12674: # is that filename actually a symb? Verify, clean, and return
                   12675:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12676: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12677: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12678: 	}
1.242     www      12679:     }
1.44      www      12680:     $thisfn=declutter($thisfn);
1.31      www      12681:     my %hash;
1.37      www      12682:     my %bighash;
                   12683:     my $syval='';
1.620     albertel 12684:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12685:         my $targetfn = $thisfn;
1.609     banghart 12686:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12687:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12688:         }
1.687     albertel 12689: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12690: 	    $targetfn=$1;
                   12691: 	}
1.620     albertel 12692:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12693:                       &GDBM_READER(),0640)) {
1.481     raeburn  12694: 	    $syval=$hash{$targetfn};
1.37      www      12695:             untie(%hash);
                   12696:         }
                   12697: # ---------------------------------------------------------- There was an entry
                   12698:         if ($syval) {
1.601     albertel 12699: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12700: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12701: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12702: 		    #return $env{$cache_str}='';
1.601     albertel 12703: 		#}    
                   12704: 		#$syval.=$1;
                   12705: 	    #}
1.37      www      12706:         } else {
                   12707: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12708:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12709:                             &GDBM_READER(),0640)) {
1.37      www      12710: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12711:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12712:               unless ($ids) { 
                   12713:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12714:               }
                   12715:               unless ($ids) {
                   12716: # alias?
                   12717: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12718:               }
1.37      www      12719:               if ($ids) {
                   12720: # ------------------------------------------------------------------- Has ID(s)
                   12721:                  my @possibilities=split(/\,/,$ids);
1.39      www      12722:                  if ($#possibilities==0) {
                   12723: # ----------------------------------------------- There is only one possibility
1.37      www      12724: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12725: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12726: 						    $resid,$thisfn);
1.1282    raeburn  12727:                      if (ref($possibles) eq 'HASH') {
                   12728:                          $possibles->{$syval} = 1;    
                   12729:                      }
                   12730:                      if ($checkforblock) {
                   12731:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12732:                          if (@blockers) {
                   12733:                              $syval = '';
                   12734:                              return;
                   12735:                          }
                   12736:                      }
                   12737:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12738: # ------------------------------------------ There is more than one possibility
                   12739:                      my $realpossible=0;
1.800     albertel 12740:                      foreach my $id (@possibilities) {
                   12741: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12742:                          my $canaccess;
                   12743:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12744:                              $canaccess = 1;
                   12745:                          } else { 
                   12746:                              $canaccess = &allowed('bre',$file);
                   12747:                          }
                   12748:                          if ($canaccess) {
                   12749:          		     my ($mapid,$resid)=split(/\./,$id);
                   12750:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12751:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12752: 						             $resid,$thisfn);
                   12753:                                  if (ref($possibles) eq 'HASH') {
                   12754:                                      $possibles->{$syval} = 1;
                   12755:                                  }
                   12756:                                  if ($checkforblock) {
                   12757:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12758:                                      unless (@blockers > 0) {
                   12759:                                          $syval = $poss_syval;
                   12760:                                          $realpossible++;
                   12761:                                      }
                   12762:                                  } else {
                   12763:                                      $syval = $poss_syval;
                   12764:                                      $realpossible++;
                   12765:                                  }
                   12766:                              }
1.39      www      12767: 			 }
1.191     harris41 12768:                      }
1.39      www      12769: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12770:                  } else {
                   12771:                      $syval='';
1.37      www      12772:                  }
                   12773: 	      }
1.1282    raeburn  12774:               untie(%bighash);
1.481     raeburn  12775:            }
1.31      www      12776:         }
1.62      www      12777:         if ($syval) {
1.620     albertel 12778: 	    return $env{$cache_str}=$syval;
1.62      www      12779:         }
1.31      www      12780:     }
1.949     raeburn  12781:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12782:     return $env{$cache_str}='';
1.31      www      12783: }
                   12784: 
                   12785: # ---------------------------------------------------------- Return random seed
                   12786: 
1.32      www      12787: sub numval {
                   12788:     my $txt=shift;
                   12789:     $txt=~tr/A-J/0-9/;
                   12790:     $txt=~tr/a-j/0-9/;
                   12791:     $txt=~tr/K-T/0-9/;
                   12792:     $txt=~tr/k-t/0-9/;
                   12793:     $txt=~tr/U-Z/0-5/;
                   12794:     $txt=~tr/u-z/0-5/;
                   12795:     $txt=~s/\D//g;
1.564     albertel 12796:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12797:     return int($txt);
1.368     albertel 12798: }
                   12799: 
1.484     albertel 12800: sub numval2 {
                   12801:     my $txt=shift;
                   12802:     $txt=~tr/A-J/0-9/;
                   12803:     $txt=~tr/a-j/0-9/;
                   12804:     $txt=~tr/K-T/0-9/;
                   12805:     $txt=~tr/k-t/0-9/;
                   12806:     $txt=~tr/U-Z/0-5/;
                   12807:     $txt=~tr/u-z/0-5/;
                   12808:     $txt=~s/\D//g;
                   12809:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12810:     my $total;
                   12811:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12812:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12813:     return int($total);
                   12814: }
                   12815: 
1.575     albertel 12816: sub numval3 {
                   12817:     use integer;
                   12818:     my $txt=shift;
                   12819:     $txt=~tr/A-J/0-9/;
                   12820:     $txt=~tr/a-j/0-9/;
                   12821:     $txt=~tr/K-T/0-9/;
                   12822:     $txt=~tr/k-t/0-9/;
                   12823:     $txt=~tr/U-Z/0-5/;
                   12824:     $txt=~tr/u-z/0-5/;
                   12825:     $txt=~s/\D//g;
                   12826:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12827:     my $total;
                   12828:     foreach my $val (@txts) { $total+=$val; }
                   12829:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12830:     return $total;
                   12831: }
                   12832: 
1.675     albertel 12833: sub digest {
                   12834:     my ($data)=@_;
                   12835:     my $digest=&Digest::MD5::md5($data);
                   12836:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12837:     my ($e,$f);
                   12838:     {
                   12839:         use integer;
                   12840:         $e=($a+$b);
                   12841:         $f=($c+$d);
                   12842:         if ($_64bit) {
                   12843:             $e=(($e<<32)>>32);
                   12844:             $f=(($f<<32)>>32);
                   12845:         }
                   12846:     }
                   12847:     if (wantarray) {
                   12848: 	return ($e,$f);
                   12849:     } else {
                   12850: 	my $g;
                   12851: 	{
                   12852: 	    use integer;
                   12853: 	    $g=($e+$f);
                   12854: 	    if ($_64bit) {
                   12855: 		$g=(($g<<32)>>32);
                   12856: 	    }
                   12857: 	}
                   12858: 	return $g;
                   12859:     }
                   12860: }
                   12861: 
1.368     albertel 12862: sub latest_rnd_algorithm_id {
1.675     albertel 12863:     return '64bit5';
1.366     albertel 12864: }
1.32      www      12865: 
1.503     albertel 12866: sub get_rand_alg {
                   12867:     my ($courseid)=@_;
1.790     albertel 12868:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12869:     if ($courseid) {
1.620     albertel 12870: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12871:     }
                   12872:     return &latest_rnd_algorithm_id();
                   12873: }
                   12874: 
1.562     albertel 12875: sub validCODE {
                   12876:     my ($CODE)=@_;
                   12877:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12878:     return 0;
                   12879: }
                   12880: 
1.491     albertel 12881: sub getCODE {
1.620     albertel 12882:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12883:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12884: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12885: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12886: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12887:     }
                   12888:     return undef;
                   12889: }
1.1133    foxr     12890: #
                   12891: #  Determines the random seed for a specific context:
                   12892: #
                   12893: # parameters:
                   12894: #   symb      - in course context the symb for the seed.
                   12895: #   course_id - The course id of the form domain_coursenum.
                   12896: #   domain    - Domain for the user.
                   12897: #   course    - Course for the user.
                   12898: #   cenv      - environment of the course.
                   12899: #
                   12900: # NOTE:
                   12901: #   All parameters are picked out of the environment if missing
                   12902: #   or not defined.
                   12903: #   If a symb cannot be determined the current time is used instead.
                   12904: #
                   12905: #  For a given well defined symb, courside, domain, username,
                   12906: #  and course environment, the seed is reproducible.
                   12907: #
1.31      www      12908: sub rndseed {
1.1133    foxr     12909:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12910:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12911:     if (!defined($symb)) {
1.366     albertel 12912: 	unless ($symb=$wsymb) { return time; }
                   12913:     }
1.1146    foxr     12914:     if (!defined $courseid) { 
                   12915: 	$courseid=$wcourseid; 
                   12916:     }
                   12917:     if (!defined $domain) { $domain=$wdomain; }
                   12918:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12919: 
                   12920:     my $which;
                   12921:     if (defined($cenv->{'rndseed'})) {
                   12922: 	$which = $cenv->{'rndseed'};
                   12923:     } else {
                   12924: 	$which =&get_rand_alg($courseid);
                   12925:     }
1.491     albertel 12926:     if (defined(&getCODE())) {
1.1133    foxr     12927: 
1.675     albertel 12928: 	if ($which eq '64bit5') {
                   12929: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12930: 	} elsif ($which eq '64bit4') {
1.575     albertel 12931: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12932: 	} else {
                   12933: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12934: 	}
1.675     albertel 12935:     } elsif ($which eq '64bit5') {
                   12936: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12937:     } elsif ($which eq '64bit4') {
                   12938: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12939:     } elsif ($which eq '64bit3') {
                   12940: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12941:     } elsif ($which eq '64bit2') {
                   12942: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12943:     } elsif ($which eq '64bit') {
                   12944: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12945:     }
                   12946:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12947: }
                   12948: 
                   12949: sub rndseed_32bit {
                   12950:     my ($symb,$courseid,$domain,$username)=@_;
                   12951:     {
                   12952: 	use integer;
                   12953: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12954: 	my $symbseed=numval($symb) << 22;
                   12955: 	my $namechck=unpack("%32C*",$username) << 17;
                   12956: 	my $nameseed=numval($username) << 12;
                   12957: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12958: 	my $courseseed=unpack("%32C*",$courseid);
                   12959: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12960: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12961: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12962: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12963: 	return $num;
                   12964:     }
                   12965: }
                   12966: 
                   12967: sub rndseed_64bit {
                   12968:     my ($symb,$courseid,$domain,$username)=@_;
                   12969:     {
                   12970: 	use integer;
                   12971: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12972: 	my $symbseed=numval($symb) << 10;
                   12973: 	my $namechck=unpack("%32S*",$username);
                   12974: 	
                   12975: 	my $nameseed=numval($username) << 21;
                   12976: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12977: 	my $courseseed=unpack("%32S*",$courseid);
                   12978: 	
                   12979: 	my $num1=$symbchck+$symbseed+$namechck;
                   12980: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12981: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12982: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12983: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12984: 	return "$num1,$num2";
1.155     albertel 12985:     }
1.366     albertel 12986: }
                   12987: 
1.443     albertel 12988: sub rndseed_64bit2 {
                   12989:     my ($symb,$courseid,$domain,$username)=@_;
                   12990:     {
                   12991: 	use integer;
                   12992: 	# strings need to be an even # of cahracters long, it it is odd the
                   12993:         # last characters gets thrown away
                   12994: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12995: 	my $symbseed=numval($symb) << 10;
                   12996: 	my $namechck=unpack("%32S*",$username.' ');
                   12997: 	
                   12998: 	my $nameseed=numval($username) << 21;
1.501     albertel 12999: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13000: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13001: 	
                   13002: 	my $num1=$symbchck+$symbseed+$namechck;
                   13003: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13004: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13005: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13006: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13007: 	return "$num1,$num2";
                   13008:     }
                   13009: }
                   13010: 
                   13011: sub rndseed_64bit3 {
                   13012:     my ($symb,$courseid,$domain,$username)=@_;
                   13013:     {
                   13014: 	use integer;
                   13015: 	# strings need to be an even # of cahracters long, it it is odd the
                   13016:         # last characters gets thrown away
                   13017: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13018: 	my $symbseed=numval2($symb) << 10;
                   13019: 	my $namechck=unpack("%32S*",$username.' ');
                   13020: 	
                   13021: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13022: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13023: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13024: 	
                   13025: 	my $num1=$symbchck+$symbseed+$namechck;
                   13026: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13027: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13028: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13029: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13030: 	
1.503     albertel 13031: 	return "$num1:$num2";
1.443     albertel 13032:     }
                   13033: }
                   13034: 
1.575     albertel 13035: sub rndseed_64bit4 {
                   13036:     my ($symb,$courseid,$domain,$username)=@_;
                   13037:     {
                   13038: 	use integer;
                   13039: 	# strings need to be an even # of cahracters long, it it is odd the
                   13040:         # last characters gets thrown away
                   13041: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13042: 	my $symbseed=numval3($symb) << 10;
                   13043: 	my $namechck=unpack("%32S*",$username.' ');
                   13044: 	
                   13045: 	my $nameseed=numval3($username) << 21;
                   13046: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13047: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13048: 	
                   13049: 	my $num1=$symbchck+$symbseed+$namechck;
                   13050: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13051: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13052: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13053: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13054: 	
1.575     albertel 13055: 	return "$num1:$num2";
                   13056:     }
                   13057: }
                   13058: 
1.675     albertel 13059: sub rndseed_64bit5 {
                   13060:     my ($symb,$courseid,$domain,$username)=@_;
                   13061:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13062:     return "$num1:$num2";
                   13063: }
                   13064: 
1.366     albertel 13065: sub rndseed_CODE_64bit {
                   13066:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13067:     {
1.366     albertel 13068: 	use integer;
1.443     albertel 13069: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13070: 	my $symbseed=numval2($symb);
1.491     albertel 13071: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13072: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13073: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13074: 	my $num1=$symbseed+$CODEchck;
                   13075: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13076: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13077: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13078: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13079: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13080: 	return "$num1:$num2";
1.366     albertel 13081:     }
                   13082: }
                   13083: 
1.575     albertel 13084: sub rndseed_CODE_64bit4 {
                   13085:     my ($symb,$courseid,$domain,$username)=@_;
                   13086:     {
                   13087: 	use integer;
                   13088: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13089: 	my $symbseed=numval3($symb);
                   13090: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13091: 	my $CODEseed=numval3(&getCODE());
                   13092: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13093: 	my $num1=$symbseed+$CODEchck;
                   13094: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13095: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13096: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13097: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13098: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13099: 	return "$num1:$num2";
                   13100:     }
                   13101: }
                   13102: 
1.675     albertel 13103: sub rndseed_CODE_64bit5 {
                   13104:     my ($symb,$courseid,$domain,$username)=@_;
                   13105:     my $code = &getCODE();
                   13106:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13107:     return "$num1:$num2";
                   13108: }
                   13109: 
1.366     albertel 13110: sub setup_random_from_rndseed {
                   13111:     my ($rndseed)=@_;
1.503     albertel 13112:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13113:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13114:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13115:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13116:         } else {
                   13117:             &Math::Random::random_set_seed($num1,$num2);
                   13118:         }
1.366     albertel 13119:     } else {
                   13120: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13121:     }
1.36      albertel 13122: }
                   13123: 
1.474     albertel 13124: sub latest_receipt_algorithm_id {
1.835     albertel 13125:     return 'receipt3';
1.474     albertel 13126: }
                   13127: 
1.480     www      13128: sub recunique {
                   13129:     my $fucourseid=shift;
                   13130:     my $unique;
1.835     albertel 13131:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13132: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13133: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13134:     } else {
                   13135: 	$unique=$perlvar{'lonReceipt'};
                   13136:     }
                   13137:     return unpack("%32C*",$unique);
                   13138: }
                   13139: 
                   13140: sub recprefix {
                   13141:     my $fucourseid=shift;
                   13142:     my $prefix;
1.835     albertel 13143:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13144: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13145: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13146:     } else {
                   13147: 	$prefix=$perlvar{'lonHostID'};
                   13148:     }
                   13149:     return unpack("%32C*",$prefix);
                   13150: }
                   13151: 
1.76      www      13152: sub ireceipt {
1.474     albertel 13153:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13154: 
                   13155:     my $return =&recprefix($fucourseid).'-';
                   13156: 
                   13157:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13158: 	$env{'request.state'} eq 'construct') {
                   13159: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13160: 	return $return;
                   13161:     }
                   13162: 
1.76      www      13163:     my $cuname=unpack("%32C*",$funame);
                   13164:     my $cudom=unpack("%32C*",$fudom);
                   13165:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13166:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13167:     my $cunique=&recunique($fucourseid);
1.474     albertel 13168:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13169:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13170: 
1.790     albertel 13171: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13172: 			       
                   13173: 	$return.= ($cunique%$cuname+
                   13174: 		   $cunique%$cudom+
                   13175: 		   $cusymb%$cuname+
                   13176: 		   $cusymb%$cudom+
                   13177: 		   $cucourseid%$cuname+
                   13178: 		   $cucourseid%$cudom+
                   13179: 		   $cpart%$cuname+
                   13180: 		   $cpart%$cudom);
                   13181:     } else {
                   13182: 	$return.= ($cunique%$cuname+
                   13183: 		   $cunique%$cudom+
                   13184: 		   $cusymb%$cuname+
                   13185: 		   $cusymb%$cudom+
                   13186: 		   $cucourseid%$cuname+
                   13187: 		   $cucourseid%$cudom);
                   13188:     }
                   13189:     return $return;
1.76      www      13190: }
                   13191: 
                   13192: sub receipt {
1.474     albertel 13193:     my ($part)=@_;
1.790     albertel 13194:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13195:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13196: }
1.260     ng       13197: 
1.790     albertel 13198: sub whichuser {
                   13199:     my ($passedsymb)=@_;
                   13200:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13201:     if (defined($env{'form.grade_symb'})) {
                   13202: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13203: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13204: 	if (!$allowed &&
                   13205: 	    exists($env{'request.course.sec'}) &&
                   13206: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13207: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13208: 			      '/'.$env{'request.course.sec'});
                   13209: 	}
                   13210: 	if ($allowed) {
                   13211: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13212: 	    $courseid=$tmp_courseid;
                   13213: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13214: 	    ($name)=&get_env_multiple('form.grade_username');
                   13215: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13216: 	}
                   13217:     }
                   13218:     if (!$passedsymb) {
                   13219: 	$symb=&symbread();
                   13220:     } else {
                   13221: 	$symb=$passedsymb;
                   13222:     }
                   13223:     $courseid=$env{'request.course.id'};
                   13224:     $domain=$env{'user.domain'};
                   13225:     $name=$env{'user.name'};
                   13226:     if ($name eq 'public' && $domain eq 'public') {
                   13227: 	if (!defined($env{'form.username'})) {
                   13228: 	    $env{'form.username'}.=time.rand(10000000);
                   13229: 	}
                   13230: 	$name.=$env{'form.username'};
                   13231:     }
                   13232:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13233: 
                   13234: }
                   13235: 
1.36      albertel 13236: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13237: # returns either the contents of the file or 
                   13238: # -1 if the file doesn't exist
1.481     raeburn  13239: #
                   13240: # if the target is a file that was uploaded via DOCS, 
                   13241: # a check will be made to see if a current copy exists on the local server,
                   13242: # if it does this will be served, otherwise a copy will be retrieved from
                   13243: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13244: # the local server.   
1.472     albertel 13245: 
1.36      albertel 13246: sub getfile {
1.538     albertel 13247:     my ($file) = @_;
1.609     banghart 13248:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13249:     &repcopy($file);
                   13250:     return &readfile($file);
                   13251: }
                   13252: 
                   13253: sub repcopy_userfile {
                   13254:     my ($file)=@_;
1.1142    raeburn  13255:     my $londocroot = $perlvar{'lonDocRoot'};
                   13256:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13257:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13258:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13259: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13260:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13261:     if (-e "$file") {
1.828     www      13262: # we already have a local copy, check it out
1.538     albertel 13263: 	my @fileinfo = stat($file);
1.828     www      13264: 	my $rtncode;
                   13265: 	my $info;
1.538     albertel 13266: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13267: 	if ($lwpresp ne 'ok') {
1.828     www      13268: # there is no such file anymore, even though we had a local copy
1.482     albertel 13269: 	    if ($rtncode eq '404') {
1.538     albertel 13270: 		unlink($file);
1.482     albertel 13271: 	    }
                   13272: 	    return -1;
                   13273: 	}
                   13274: 	if ($info < $fileinfo[9]) {
1.828     www      13275: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13276: 	    return 'ok';
1.828     www      13277: 	} else {
                   13278: # the file is outdated, get rid of it
                   13279: 	    unlink($file);
1.482     albertel 13280: 	}
1.828     www      13281:     }
                   13282: # one way or the other, at this point, we don't have the file
                   13283: # construct the correct path for the file
                   13284:     my @parts = ($cdom,$cnum); 
                   13285:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13286: 	push @parts, split(/\//,$1);
                   13287:     }
                   13288:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13289:     foreach my $part (@parts) {
                   13290: 	$path .= '/'.$part;
                   13291: 	if (!-e $path) {
                   13292: 	    mkdir($path,0770);
1.482     albertel 13293: 	}
                   13294:     }
1.828     www      13295: # now the path exists for sure
                   13296: # get a user agent
                   13297:     my $transferfile=$file.'.in.transfer';
                   13298: # FIXME: this should flock
                   13299:     if (-e $transferfile) { return 'ok'; }
                   13300:     my $request;
                   13301:     $uri=~s/^\///;
1.980     raeburn  13302:     my $homeserver = &homeserver($cnum,$cdom);
                   13303:     my $protocol = $protocol{$homeserver};
                   13304:     $protocol = 'http' if ($protocol ne 'https');
                   13305:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13306:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13307: # did it work?
                   13308:     if ($response->is_error()) {
                   13309: 	unlink($transferfile);
                   13310: 	&logthis("Userfile repcopy failed for $uri");
                   13311: 	return -1;
                   13312:     }
                   13313: # worked, rename the transfer file
                   13314:     rename($transferfile,$file);
1.607     raeburn  13315:     return 'ok';
1.481     raeburn  13316: }
                   13317: 
1.517     albertel 13318: sub tokenwrapper {
                   13319:     my $uri=shift;
1.980     raeburn  13320:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13321:     $uri=~s|^/||;
1.620     albertel 13322:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13323:     my $token=$1;
1.552     albertel 13324:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13325:     if ($udom && $uname && $file) {
                   13326: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13327:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13328:         my $homeserver = &homeserver($uname,$udom);
                   13329:         my $protocol = $protocol{$homeserver};
                   13330:         $protocol = 'http' if ($protocol ne 'https');
                   13331:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13332:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13333:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13334:     } else {
                   13335:         return '/adm/notfound.html';
                   13336:     }
                   13337: }
                   13338: 
1.828     www      13339: # call with reqtype HEAD: get last modification time
                   13340: # call with reqtype GET: get the file contents
                   13341: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13342: #
1.481     raeburn  13343: sub getuploaded {
                   13344:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13345:     $uri=~s/^\///;
1.980     raeburn  13346:     my $homeserver = &homeserver($cnum,$cdom);
                   13347:     my $protocol = $protocol{$homeserver};
                   13348:     $protocol = 'http' if ($protocol ne 'https');
                   13349:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13350:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13351:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13352:     $$rtncode = $response->code;
1.482     albertel 13353:     if (! $response->is_success()) {
                   13354: 	return 'failed';
                   13355:     }      
                   13356:     if ($reqtype eq 'HEAD') {
1.486     www      13357: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13358:     } elsif ($reqtype eq 'GET') {
                   13359: 	$$info = $response->content;
1.472     albertel 13360:     }
1.482     albertel 13361:     return 'ok';
1.36      albertel 13362: }
                   13363: 
1.481     raeburn  13364: sub readfile {
                   13365:     my $file = shift;
                   13366:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13367:     my $fh;
1.1359    raeburn  13368:     open($fh,"<",$file);
1.481     raeburn  13369:     my $a='';
1.800     albertel 13370:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13371:     return $a;
                   13372: }
                   13373: 
1.36      albertel 13374: sub filelocation {
1.590     banghart 13375:     my ($dir,$file) = @_;
                   13376:     my $location;
                   13377:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13378: 
                   13379:     if ($file =~ m-^/adm/-) {
                   13380: 	$file=~s-^/adm/wrapper/-/-;
                   13381: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13382:     }
1.882     albertel 13383: 
1.1139    www      13384:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13385:         $location = $file;
1.609     banghart 13386:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13387:         my ($udom,$uname,$filename)=
1.811     albertel 13388:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13389:         my $home=&homeserver($uname,$udom);
                   13390:         my $is_me=0;
                   13391:         my @ids=&current_machine_ids();
                   13392:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13393:         if ($is_me) {
1.1117    foxr     13394:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13395:         } else {
                   13396:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13397:   	      $udom.'/'.$uname.'/'.$filename;
                   13398:         }
1.882     albertel 13399:     } elsif ($file =~ m-^/adm/-) {
                   13400: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13401:     } else {
                   13402:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13403:         $file=~s:^/(res|priv)/:/:;
                   13404:         my $space=$1;
1.590     banghart 13405:         if ( !( $file =~ m:^/:) ) {
                   13406:             $location = $dir. '/'.$file;
                   13407:         } else {
1.1142    raeburn  13408:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13409:         }
1.59      albertel 13410:     }
1.590     banghart 13411:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13412:     while ($location=~m{/\.\./}) {
                   13413: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13414: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13415: 	} else {
                   13416: 	    $location=~ s{/\.\./}{/}g;
                   13417: 	}
                   13418:     } #remove dir/..
1.590     banghart 13419:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13420:     return $location;
1.46      www      13421: }
1.36      albertel 13422: 
1.46      www      13423: sub hreflocation {
                   13424:     my ($dir,$file)=@_;
1.980     raeburn  13425:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13426: 	$file=filelocation($dir,$file);
1.700     albertel 13427:     } elsif ($file=~m-^/adm/-) {
                   13428: 	$file=~s-^/adm/wrapper/-/-;
                   13429: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13430:     }
                   13431:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13432: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13433:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13434: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13435: 	        {/uploaded/$1/$2/}x;
1.46      www      13436:     }
1.913     albertel 13437:     if ($file=~ m{^/userfiles/}) {
                   13438: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13439:     }
1.462     albertel 13440:     return $file;
1.465     albertel 13441: }
                   13442: 
1.1139    www      13443: 
                   13444: 
                   13445: 
                   13446: 
1.465     albertel 13447: sub current_machine_domains {
1.853     albertel 13448:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13449: }
                   13450: 
                   13451: sub machine_domains {
                   13452:     my ($hostname) = @_;
1.465     albertel 13453:     my @domains;
1.838     albertel 13454:     my %hostname = &all_hostnames();
1.465     albertel 13455:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13456: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13457: 	if ($hostname eq $name) {
1.844     albertel 13458: 	    push(@domains,&host_domain($id));
1.465     albertel 13459: 	}
                   13460:     }
                   13461:     return @domains;
                   13462: }
                   13463: 
                   13464: sub current_machine_ids {
1.853     albertel 13465:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13466: }
                   13467: 
                   13468: sub machine_ids {
                   13469:     my ($hostname) = @_;
                   13470:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13471:     my @ids;
1.888     albertel 13472:     my %name_to_host = &all_names();
1.889     albertel 13473:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13474: 	return @{ $name_to_host{$hostname} };
                   13475:     }
                   13476:     return;
1.31      www      13477: }
                   13478: 
1.824     raeburn  13479: sub additional_machine_domains {
                   13480:     my @domains;
1.1359    raeburn  13481:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13482:     while( my $line = <$fh>) {
                   13483:         $line =~ s/\s//g;
                   13484:         push(@domains,$line);
                   13485:     }
                   13486:     return @domains;
                   13487: }
                   13488: 
                   13489: sub default_login_domain {
                   13490:     my $domain = $perlvar{'lonDefDomain'};
                   13491:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13492:     foreach my $posdom (&current_machine_domains(),
                   13493:                         &additional_machine_domains()) {
                   13494:         if (lc($posdom) eq lc($testdomain)) {
                   13495:             $domain=$posdom;
                   13496:             last;
                   13497:         }
                   13498:     }
                   13499:     return $domain;
                   13500: }
                   13501: 
1.31      www      13502: # ------------------------------------------------------------- Declutters URLs
                   13503: 
                   13504: sub declutter {
                   13505:     my $thisfn=shift;
1.569     albertel 13506:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13507:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13508:         $thisfn=~s{^/home/httpd/html}{};
                   13509:     }
1.31      www      13510:     $thisfn=~s/^\///;
1.697     albertel 13511:     $thisfn=~s|^adm/wrapper/||;
                   13512:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13513:     $thisfn=~s/^res\///;
1.1172    bisitz   13514:     $thisfn=~s/^priv\///;
1.1032    raeburn  13515:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13516:         $thisfn=~s/\?.+$//;
                   13517:     }
1.268     www      13518:     return $thisfn;
                   13519: }
                   13520: 
                   13521: # ------------------------------------------------------------- Clutter up URLs
                   13522: 
                   13523: sub clutter {
                   13524:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13525:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13526: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13527:        $thisfn='/res'.$thisfn; 
                   13528:     }
1.1031    raeburn  13529:     if ($thisfn !~m|^/adm|) {
                   13530: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13531: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13532: 	} else {
                   13533: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13534: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13535: 	    if ($embstyle eq 'ssi'
                   13536: 		|| ($embstyle eq 'hdn')
                   13537: 		|| ($embstyle eq 'rat')
                   13538: 		|| ($embstyle eq 'prv')
                   13539: 		|| ($embstyle eq 'ign')) {
                   13540: 		#do nothing with these
                   13541: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13542: 		|| ($embstyle eq 'emb')
                   13543: 		|| ($embstyle eq 'wrp')) {
                   13544: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13545: 	    } elsif ($embstyle eq 'unk'
                   13546: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13547: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13548: 	    } else {
1.718     www      13549: #		&logthis("Got a blank emb style");
1.695     albertel 13550: 	    }
1.694     albertel 13551: 	}
1.1343    raeburn  13552:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13553:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13554:     }
1.31      www      13555:     return $thisfn;
1.12      www      13556: }
                   13557: 
1.787     albertel 13558: sub clutter_with_no_wrapper {
                   13559:     my $uri = &clutter(shift);
                   13560:     if ($uri =~ m-^/adm/-) {
                   13561: 	$uri =~ s-^/adm/wrapper/-/-;
                   13562: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13563:     }
                   13564:     return $uri;
                   13565: }
                   13566: 
1.557     albertel 13567: sub freeze_escape {
                   13568:     my ($value)=@_;
                   13569:     if (ref($value)) {
                   13570: 	$value=&nfreeze($value);
                   13571: 	return '__FROZEN__'.&escape($value);
                   13572:     }
                   13573:     return &escape($value);
                   13574: }
                   13575: 
1.11      www      13576: 
1.557     albertel 13577: sub thaw_unescape {
                   13578:     my ($value)=@_;
                   13579:     if ($value =~ /^__FROZEN__/) {
                   13580: 	substr($value,0,10,undef);
                   13581: 	$value=&unescape($value);
                   13582: 	return &thaw($value);
                   13583:     }
                   13584:     return &unescape($value);
                   13585: }
                   13586: 
1.436     albertel 13587: sub correct_line_ends {
                   13588:     my ($result)=@_;
                   13589:     $$result =~s/\r\n/\n/mg;
                   13590:     $$result =~s/\r/\n/mg;
1.415     albertel 13591: }
1.1       albertel 13592: # ================================================================ Main Program
                   13593: 
1.184     www      13594: sub goodbye {
1.204     albertel 13595:    &logthis("Starting Shut down");
1.443     albertel 13596: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13597:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13598: #converted
1.599     albertel 13599: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13600:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13601: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13602: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13603: #1.1 only
1.870     albertel 13604: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13605: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13606: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13607: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13608:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13609:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13610:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13611:    &flushcourselogs();
                   13612:    &logthis("Shutting down");
                   13613: }
                   13614: 
1.852     albertel 13615: sub get_dns {
1.1210    raeburn  13616:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13617:     if (!$ignore_cache) {
                   13618: 	my ($content,$cached)=
                   13619: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13620: 	if ($cached) {
1.1210    raeburn  13621: 	    &$func($content,$hashref);
1.869     albertel 13622: 	    return;
                   13623: 	}
                   13624:     }
                   13625: 
                   13626:     my %alldns;
1.1379    raeburn  13627:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13628:         foreach my $dns (<$config>) {
                   13629: 	    next if ($dns !~ /^\^(\S*)/x);
                   13630:             my $line = $1;
                   13631:             my ($host,$protocol) = split(/:/,$line);
                   13632:             if ($protocol ne 'https') {
                   13633:                 $protocol = 'http';
                   13634:             }
                   13635: 	    $alldns{$host} = $protocol;
1.979     raeburn  13636:         }
1.1379    raeburn  13637:         close($config);
1.869     albertel 13638:     }
                   13639:     while (%alldns) {
1.1263    raeburn  13640: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13641: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13642:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13643:         delete($alldns{$dns});
1.852     albertel 13644: 	next if ($response->is_error());
1.1379    raeburn  13645:         if ($url eq '/adm/dns/loncapaCRL') {
                   13646:             return &$func($response);
                   13647:         } else {
                   13648: 	    my @content = split("\n",$response->content);
                   13649: 	    unless ($nocache) {
                   13650: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   13651: 	    }
                   13652: 	    &$func(\@content,$hashref);
                   13653:             return;
                   13654:         }
                   13655:     }
                   13656:     my $which = (split('/',$url,4))[3];
                   13657:     if ($which eq 'loncapaCRL') {
                   13658:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   13659:         if (-e $diskfile) {
                   13660:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   13661:         } else {
                   13662:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   13663:         }
                   13664:     } else {
                   13665:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13666:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13667:             my @content = <$config>;
                   13668:             close($config);
                   13669:             &$func(\@content,$hashref);
                   13670:         }
1.852     albertel 13671:     }
1.1210    raeburn  13672:     return;
                   13673: }
                   13674: 
                   13675: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13676: sub parse_dns_checksums_tab {
1.1210    raeburn  13677:     my ($lines,$hashref) = @_;
1.1264    raeburn  13678:     my $lonhost = $perlvar{'lonHostID'};
                   13679:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13680:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13681:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13682:     my $webconfdir = '/etc/httpd/conf';
                   13683:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13684:         $webconfdir = '/etc/apache2';
                   13685:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13686:         if ($1 >= 10) {
                   13687:             $webconfdir = '/etc/apache2';
                   13688:         }
                   13689:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13690:         if ($1 >= 10.0) {
                   13691:             $webconfdir = '/etc/apache2';
                   13692:         }
                   13693:     }
1.1210    raeburn  13694:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13695:     my (%chksum,%revnum);
                   13696:     if (ref($lines) eq 'ARRAY') {
                   13697:         chomp(@{$lines});
1.1238    raeburn  13698:         my $version = shift(@{$lines});
                   13699:         if ($version eq $release) {  
1.1210    raeburn  13700:             foreach my $line (@{$lines}) {
1.1238    raeburn  13701:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13702:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13703:                     if ($webconfdir eq '/etc/apache2') {
                   13704:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13705:                     }
                   13706:                 }
1.1238    raeburn  13707:                 $chksum{$file} = $shasum;
                   13708:                 $revnum{$file} = $version;
1.1210    raeburn  13709:             }
                   13710:             if (ref($hashref) eq 'HASH') {
                   13711:                 %{$hashref} = (
                   13712:                                 sums     => \%chksum,
                   13713:                                 versions => \%revnum,
                   13714:                               );
                   13715:             }
                   13716:         }
                   13717:     }
1.869     albertel 13718:     return;
1.852     albertel 13719: }
1.1210    raeburn  13720: 
                   13721: sub fetch_dns_checksums {
1.1238    raeburn  13722:     my %checksums;
                   13723:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13724:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13725:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13726:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13727:              \%checksums);
1.1210    raeburn  13728:     return \%checksums;
                   13729: }
                   13730: 
1.1379    raeburn  13731: sub fetch_crl_pemfile {
                   13732:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   13733: }
                   13734: 
                   13735: sub save_crl_pem {
                   13736:     my ($response) = @_;
1.1380    raeburn  13737:     my ($msg,$hadchanges);
1.1379    raeburn  13738:     if (ref($response)) {
                   13739:         my $now = time;
                   13740:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   13741:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   13742:         if (open(my $fh,'>',"$tmpcrl")) {
                   13743:             print $fh $response->content;
                   13744:             close($fh);
                   13745:             if (-e $lonca) {
                   13746:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   13747:                     my $check = <PIPE>;
                   13748:                     close(PIPE);
                   13749:                     chomp($check);
                   13750:                     if ($check eq 'verify OK') {
                   13751:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  13752:                         my $backup;
1.1379    raeburn  13753:                         if (-e $dest) {
1.1380    raeburn  13754:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   13755:                                 $backup = 'ok';
                   13756:                             }
1.1379    raeburn  13757:                         }
                   13758:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   13759:                             $msg = 'ok';
1.1380    raeburn  13760:                             if ($backup) {
                   13761:                                 my (%oldnums,%newnums);
                   13762:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   13763:                                     while (<PIPE>) {
                   13764:                                         $oldnums{(split(/:/))[1]} = 1;
                   13765:                                     }
                   13766:                                     close(PIPE);
                   13767:                                 }
                   13768:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   13769:                                     while(<PIPE>) {
                   13770:                                         $newnums{(split(/:/))[1]} = 1;
                   13771:                                     }
                   13772:                                     close(PIPE);
                   13773:                                 }
                   13774:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   13775:                                     unless (exists($oldnums{$key})) {
                   13776:                                         $hadchanges = 1;
                   13777:                                         last;
                   13778:                                     }
                   13779:                                 }
                   13780:                                 unless ($hadchanges) {
                   13781:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   13782:                                         unless (exists($newnums{$key})) {
                   13783:                                             $hadchanges = 1;
                   13784:                                             last;
                   13785:                                         }
                   13786:                                     }
                   13787:                                 }
                   13788:                             }
1.1379    raeburn  13789:                         }
                   13790:                     } else {
                   13791:                         unlink($tmpcrl);
                   13792:                     }
                   13793:                 } else {
                   13794:                     unlink($tmpcrl);
                   13795:                 }
                   13796:             } else {
                   13797:                 unlink($tmpcrl);
                   13798:             }
                   13799:         }
                   13800:     }
1.1380    raeburn  13801:     return ($msg,$hadchanges);
1.1379    raeburn  13802: }
                   13803: 
1.327     albertel 13804: # ------------------------------------------------------------ Read domain file
                   13805: {
1.852     albertel 13806:     my $loaded;
1.846     albertel 13807:     my %domain;
                   13808: 
1.852     albertel 13809:     sub parse_domain_tab {
                   13810: 	my ($lines) = @_;
                   13811: 	foreach my $line (@$lines) {
                   13812: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13813: 
1.846     albertel 13814: 	    chomp($line);
1.852     albertel 13815: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13816: 	    my %this_domain;
                   13817: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13818: 			       'lang_def', 'city', 'longi', 'lati',
                   13819: 			       'primary') {
                   13820: 		$this_domain{$field} = shift(@elements);
                   13821: 	    }
                   13822: 	    $domain{$name} = \%this_domain;
1.852     albertel 13823: 	}
                   13824:     }
1.864     albertel 13825: 
                   13826:     sub reset_domain_info {
                   13827: 	undef($loaded);
                   13828: 	undef(%domain);
                   13829:     }
                   13830: 
1.852     albertel 13831:     sub load_domain_tab {
1.1293    raeburn  13832: 	my ($ignore_cache,$nocache) = @_;
                   13833: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13834: 	my $fh;
1.1359    raeburn  13835: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13836: 	    my @lines = <$fh>;
                   13837: 	    &parse_domain_tab(\@lines);
1.448     albertel 13838: 	}
1.852     albertel 13839: 	close($fh);
                   13840: 	$loaded = 1;
1.327     albertel 13841:     }
1.846     albertel 13842: 
                   13843:     sub domain {
1.852     albertel 13844: 	&load_domain_tab() if (!$loaded);
                   13845: 
1.846     albertel 13846: 	my ($name,$what) = @_;
                   13847: 	return if ( !exists($domain{$name}) );
                   13848: 
                   13849: 	if (!$what) {
                   13850: 	    return $domain{$name}{'description'};
                   13851: 	}
                   13852: 	return $domain{$name}{$what};
                   13853:     }
1.974     raeburn  13854: 
                   13855:     sub domain_info {
                   13856:         &load_domain_tab() if (!$loaded);
                   13857:         return %domain;
                   13858:     }
                   13859: 
1.327     albertel 13860: }
                   13861: 
                   13862: 
1.1       albertel 13863: # ------------------------------------------------------------- Read hosts file
                   13864: {
1.838     albertel 13865:     my %hostname;
1.844     albertel 13866:     my %hostdom;
1.845     albertel 13867:     my %libserv;
1.852     albertel 13868:     my $loaded;
1.888     albertel 13869:     my %name_to_host;
1.1074    raeburn  13870:     my %internetdom;
1.1107    raeburn  13871:     my %LC_dns_serv;
1.852     albertel 13872: 
                   13873:     sub parse_hosts_tab {
                   13874: 	my ($file) = @_;
                   13875: 	foreach my $configline (@$file) {
                   13876: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13877:             chomp($configline);
                   13878: 	    if ($configline =~ /^\^/) {
                   13879:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13880:                     $LC_dns_serv{$1} = 1;
                   13881:                 }
                   13882:                 next;
                   13883:             }
1.1074    raeburn  13884: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13885: 	    $name=~s/\s//g;
                   13886: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13887:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13888:                     my $curr = $hostname{$id};
                   13889:                     my $skip;
                   13890:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13891:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13892:                             $skip = 1;
                   13893:                         } else {
                   13894:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13895:                         }
                   13896:                     }
                   13897:                     unless ($skip) {
                   13898:                         push(@{$name_to_host{$name}},$id);
                   13899:                     }
                   13900:                 } else {
                   13901:                     push(@{$name_to_host{$name}},$id);
                   13902:                 }
1.852     albertel 13903: 		$hostname{$id}=$name;
                   13904: 		$hostdom{$id}=$domain;
                   13905: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13906:                 if (defined($protocol)) {
                   13907:                     if ($protocol eq 'https') {
                   13908:                         $protocol{$id} = $protocol;
                   13909:                     } else {
                   13910:                         $protocol{$id} = 'http'; 
                   13911:                     }
1.968     raeburn  13912:                 } else {
1.969     raeburn  13913:                     $protocol{$id} = 'http';
1.968     raeburn  13914:                 }
1.1074    raeburn  13915:                 if (defined($intdom)) {
                   13916:                     $internetdom{$id} = $intdom;
                   13917:                 }
1.852     albertel 13918: 	    }
                   13919: 	}
                   13920:     }
1.864     albertel 13921:     
                   13922:     sub reset_hosts_info {
1.897     albertel 13923: 	&purge_remembered();
1.864     albertel 13924: 	&reset_domain_info();
                   13925: 	&reset_hosts_ip_info();
1.1339    raeburn  13926:         undef(%internetdom);
1.892     albertel 13927: 	undef(%name_to_host);
1.864     albertel 13928: 	undef(%hostname);
                   13929: 	undef(%hostdom);
                   13930: 	undef(%libserv);
                   13931: 	undef($loaded);
                   13932:     }
1.1       albertel 13933: 
1.852     albertel 13934:     sub load_hosts_tab {
1.1293    raeburn  13935: 	my ($ignore_cache,$nocache) = @_;
                   13936: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13937: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13938: 	my @config = <$config>;
                   13939: 	&parse_hosts_tab(\@config);
                   13940: 	close($config);
                   13941: 	$loaded=1;
1.1       albertel 13942:     }
1.852     albertel 13943: 
1.838     albertel 13944:     sub hostname {
1.852     albertel 13945: 	&load_hosts_tab() if (!$loaded);
                   13946: 
1.838     albertel 13947: 	my ($lonid) = @_;
                   13948: 	return $hostname{$lonid};
                   13949:     }
1.845     albertel 13950: 
1.838     albertel 13951:     sub all_hostnames {
1.852     albertel 13952: 	&load_hosts_tab() if (!$loaded);
                   13953: 
1.838     albertel 13954: 	return %hostname;
                   13955:     }
1.845     albertel 13956: 
1.888     albertel 13957:     sub all_names {
1.1293    raeburn  13958:         my ($ignore_cache,$nocache) = @_;
                   13959: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13960: 
                   13961: 	return %name_to_host;
                   13962:     }
                   13963: 
1.974     raeburn  13964:     sub all_host_domain {
                   13965:         &load_hosts_tab() if (!$loaded);
                   13966:         return %hostdom;
                   13967:     }
                   13968: 
1.1339    raeburn  13969:     sub all_host_intdom {
                   13970:         &load_hosts_tab() if (!$loaded);
                   13971:         return %internetdom;
                   13972:     }
                   13973: 
1.845     albertel 13974:     sub is_library {
1.852     albertel 13975: 	&load_hosts_tab() if (!$loaded);
                   13976: 
1.845     albertel 13977: 	return exists($libserv{$_[0]});
                   13978:     }
                   13979: 
                   13980:     sub all_library {
1.852     albertel 13981: 	&load_hosts_tab() if (!$loaded);
                   13982: 
1.845     albertel 13983: 	return %libserv;
                   13984:     }
                   13985: 
1.1062    droeschl 13986:     sub unique_library {
                   13987: 	#2x reverse removes all hostnames that appear more than once
                   13988:         my %unique = reverse &all_library();
                   13989:         return reverse %unique;
                   13990:     }
                   13991: 
1.841     albertel 13992:     sub get_servers {
1.852     albertel 13993: 	&load_hosts_tab() if (!$loaded);
                   13994: 
1.841     albertel 13995: 	my ($domain,$type) = @_;
                   13996: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13997: 	                                          : %hostname;
                   13998: 	my %result;
1.842     albertel 13999: 	if (ref($domain) eq 'ARRAY') {
                   14000: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14001: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14002: 		    $result{$host} = $hostname;
                   14003: 		}
                   14004: 	    }
                   14005: 	} else {
                   14006: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14007: 		if ($hostdom{$host} eq $domain) {
                   14008: 		    $result{$host} = $hostname;
                   14009: 		}
1.841     albertel 14010: 	    }
                   14011: 	}
                   14012: 	return %result;
                   14013:     }
1.845     albertel 14014: 
1.1062    droeschl 14015:     sub get_unique_servers {
                   14016:         my %unique = reverse &get_servers(@_);
                   14017: 	return reverse %unique;
                   14018:     }
                   14019: 
1.844     albertel 14020:     sub host_domain {
1.852     albertel 14021: 	&load_hosts_tab() if (!$loaded);
                   14022: 
1.844     albertel 14023: 	my ($lonid) = @_;
                   14024: 	return $hostdom{$lonid};
                   14025:     }
                   14026: 
1.841     albertel 14027:     sub all_domains {
1.852     albertel 14028: 	&load_hosts_tab() if (!$loaded);
                   14029: 
1.841     albertel 14030: 	my %seen;
                   14031: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14032: 	return @uniq;
                   14033:     }
1.1074    raeburn  14034: 
                   14035:     sub internet_dom {
                   14036:         &load_hosts_tab() if (!$loaded);
                   14037: 
                   14038:         my ($lonid) = @_;
                   14039:         return $internetdom{$lonid};
                   14040:     }
1.1107    raeburn  14041: 
                   14042:     sub is_LC_dns {
                   14043:         &load_hosts_tab() if (!$loaded);
                   14044: 
                   14045:         my ($hostname) = @_;
                   14046:         return exists($LC_dns_serv{$hostname});
                   14047:     }
                   14048: 
1.1       albertel 14049: }
                   14050: 
1.847     albertel 14051: { 
                   14052:     my %iphost;
1.856     albertel 14053:     my %name_to_ip;
                   14054:     my %lonid_to_ip;
1.869     albertel 14055: 
1.847     albertel 14056:     sub get_hosts_from_ip {
                   14057: 	my ($ip) = @_;
                   14058: 	my %iphosts = &get_iphost();
                   14059: 	if (ref($iphosts{$ip})) {
                   14060: 	    return @{$iphosts{$ip}};
                   14061: 	}
                   14062: 	return;
1.839     albertel 14063:     }
1.864     albertel 14064:     
                   14065:     sub reset_hosts_ip_info {
                   14066: 	undef(%iphost);
                   14067: 	undef(%name_to_ip);
                   14068: 	undef(%lonid_to_ip);
                   14069:     }
1.856     albertel 14070: 
                   14071:     sub get_host_ip {
                   14072: 	my ($lonid) = @_;
                   14073: 	if (exists($lonid_to_ip{$lonid})) {
                   14074: 	    return $lonid_to_ip{$lonid};
                   14075: 	}
                   14076: 	my $name=&hostname($lonid);
                   14077:    	my $ip = gethostbyname($name);
                   14078: 	return if (!$ip || length($ip) ne 4);
                   14079: 	$ip=inet_ntoa($ip);
                   14080: 	$name_to_ip{$name}   = $ip;
                   14081: 	$lonid_to_ip{$lonid} = $ip;
                   14082: 	return $ip;
                   14083:     }
1.847     albertel 14084:     
                   14085:     sub get_iphost {
1.1293    raeburn  14086: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14087: 
1.869     albertel 14088: 	if (!$ignore_cache) {
                   14089: 	    if (%iphost) {
                   14090: 		return %iphost;
                   14091: 	    }
                   14092: 	    my ($ip_info,$cached)=
                   14093: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14094: 	    if ($cached) {
                   14095: 		%iphost      = %{$ip_info->[0]};
                   14096: 		%name_to_ip  = %{$ip_info->[1]};
                   14097: 		%lonid_to_ip = %{$ip_info->[2]};
                   14098: 		return %iphost;
                   14099: 	    }
                   14100: 	}
1.894     albertel 14101: 
                   14102: 	# get yesterday's info for fallback
                   14103: 	my %old_name_to_ip;
                   14104: 	my ($ip_info,$cached)=
                   14105: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14106: 	if ($cached) {
                   14107: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14108: 	}
                   14109: 
1.1293    raeburn  14110: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14111: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14112: 	    my $ip;
                   14113: 	    if (!exists($name_to_ip{$name})) {
                   14114: 		$ip = gethostbyname($name);
                   14115: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14116: 		    if (defined($old_name_to_ip{$name})) {
                   14117: 			$ip = $old_name_to_ip{$name};
                   14118: 			&logthis("Can't find $name defaulting to old $ip");
                   14119: 		    } else {
                   14120: 			&logthis("Name $name no IP found");
                   14121: 			next;
                   14122: 		    }
                   14123: 		} else {
                   14124: 		    $ip=inet_ntoa($ip);
1.847     albertel 14125: 		}
                   14126: 		$name_to_ip{$name} = $ip;
                   14127: 	    } else {
                   14128: 		$ip = $name_to_ip{$name};
1.653     albertel 14129: 	    }
1.888     albertel 14130: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14131: 		$lonid_to_ip{$id} = $ip;
                   14132: 	    }
                   14133: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14134: 	}
1.1293    raeburn  14135:         unless ($nocache) {
                   14136: 	    &do_cache_new('iphost','iphost',
                   14137: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14138: 		          48*60*60);
                   14139:         }
1.869     albertel 14140: 
1.847     albertel 14141: 	return %iphost;
1.598     albertel 14142:     }
                   14143: 
1.992     raeburn  14144:     #
                   14145:     #  Given a DNS returns the loncapa host name for that DNS 
                   14146:     # 
                   14147:     sub host_from_dns {
                   14148:         my ($dns) = @_;
                   14149:         my @hosts;
                   14150:         my $ip;
                   14151: 
1.993     raeburn  14152:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14153:             $ip = $name_to_ip{$dns};
                   14154:         }
                   14155:         if (!$ip) {
                   14156:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14157:             if (length($ip) == 4) { 
                   14158: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14159:             }
                   14160:         }
                   14161:         if ($ip) {
                   14162: 	    @hosts = get_hosts_from_ip($ip);
                   14163: 	    return $hosts[0];
                   14164:         }
                   14165:         return undef;
1.986     foxr     14166:     }
1.992     raeburn  14167: 
1.1074    raeburn  14168:     sub get_internet_names {
                   14169:         my ($lonid) = @_;
                   14170:         return if ($lonid eq '');
                   14171:         my ($idnref,$cached)=
                   14172:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14173:         if ($cached) {
                   14174:             return $idnref;
                   14175:         }
                   14176:         my $ip = &get_host_ip($lonid);
                   14177:         my @hosts = &get_hosts_from_ip($ip);
                   14178:         my %iphost = &get_iphost();
                   14179:         my (@idns,%seen);
                   14180:         foreach my $id (@hosts) {
                   14181:             my $dom = &host_domain($id);
                   14182:             my $prim_id = &domain($dom,'primary');
                   14183:             my $prim_ip = &get_host_ip($prim_id);
                   14184:             next if ($seen{$prim_ip});
                   14185:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14186:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14187:                     my $intdom = &internet_dom($id);
                   14188:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14189:                         push(@idns,$intdom);
                   14190:                     }
                   14191:                 }
                   14192:             }
                   14193:             $seen{$prim_ip} = 1;
                   14194:         }
1.1219    raeburn  14195:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14196:     }
                   14197: 
1.986     foxr     14198: }
                   14199: 
1.1079    raeburn  14200: sub all_loncaparevs {
1.1249    raeburn  14201:     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  14202: }
                   14203: 
1.1227    raeburn  14204: # ---------------------------------------------------------- Read loncaparev table
                   14205: {
                   14206:     sub load_loncaparevs { 
                   14207:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14208:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14209:                 while (my $configline=<$config>) {
                   14210:                     chomp($configline);
                   14211:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14212:                     $loncaparevs{$hostid}=$loncaparev;
                   14213:                 }
                   14214:                 close($config);
                   14215:             }
                   14216:         }
                   14217:     }
                   14218: }
                   14219: 
                   14220: # ---------------------------------------------------------- Read serverhostID table
                   14221: {
                   14222:     sub load_serverhomeIDs {
                   14223:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14224:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14225:                 while (my $configline=<$config>) {
                   14226:                     chomp($configline);
                   14227:                     my ($name,$id)=split(/:/,$configline);
                   14228:                     $serverhomeIDs{$name}=$id;
                   14229:                 }
                   14230:                 close($config);
                   14231:             }
                   14232:         }
                   14233:     }
                   14234: }
                   14235: 
                   14236: 
1.862     albertel 14237: BEGIN {
                   14238: 
                   14239: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14240:     unless ($readit) {
                   14241: {
                   14242:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14243:     %perlvar = (%perlvar,%{$configvars});
                   14244: }
                   14245: 
                   14246: 
1.1       albertel 14247: # ------------------------------------------------------ Read spare server file
                   14248: {
1.1359    raeburn  14249:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14250: 
                   14251:     while (my $configline=<$config>) {
                   14252:        chomp($configline);
1.284     matthew  14253:        if ($configline) {
1.784     albertel 14254: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14255: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14256: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14257:        }
                   14258:     }
1.448     albertel 14259:     close($config);
1.1       albertel 14260: }
1.11      www      14261: # ------------------------------------------------------------ Read permissions
                   14262: {
1.1359    raeburn  14263:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14264: 
                   14265:     while (my $configline=<$config>) {
1.448     albertel 14266: 	chomp($configline);
                   14267: 	if ($configline) {
                   14268: 	    my ($role,$perm)=split(/ /,$configline);
                   14269: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14270: 	}
1.11      www      14271:     }
1.448     albertel 14272:     close($config);
1.11      www      14273: }
                   14274: 
                   14275: # -------------------------------------------- Read plain texts for permissions
                   14276: {
1.1359    raeburn  14277:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14278: 
                   14279:     while (my $configline=<$config>) {
1.448     albertel 14280: 	chomp($configline);
                   14281: 	if ($configline) {
1.742     raeburn  14282: 	    my ($short,@plain)=split(/:/,$configline);
                   14283:             %{$prp{$short}} = ();
                   14284: 	    if (@plain > 0) {
                   14285:                 $prp{$short}{'std'} = $plain[0];
                   14286:                 for (my $i=1; $i<@plain; $i++) {
                   14287:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14288:                 }
                   14289:             }
1.448     albertel 14290: 	}
1.135     www      14291:     }
1.448     albertel 14292:     close($config);
1.135     www      14293: }
                   14294: 
                   14295: # ---------------------------------------------------------- Read package table
                   14296: {
1.1359    raeburn  14297:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14298: 
                   14299:     while (my $configline=<$config>) {
1.483     albertel 14300: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14301: 	chomp($configline);
                   14302: 	my ($short,$plain)=split(/:/,$configline);
                   14303: 	my ($pack,$name)=split(/\&/,$short);
                   14304: 	if ($plain ne '') {
                   14305: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14306: 	    $packagetab{$short}=$plain; 
                   14307: 	}
1.11      www      14308:     }
1.448     albertel 14309:     close($config);
1.329     matthew  14310: }
                   14311: 
1.1073    raeburn  14312: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14313: 
                   14314: &load_loncaparevs();
1.1073    raeburn  14315: 
1.1074    raeburn  14316: # ---------------------------------------------------------- Read serverhostID table
                   14317: 
1.1227    raeburn  14318: &load_serverhomeIDs();
                   14319: 
                   14320: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14321: {
                   14322:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14323:     if (-e $file) {
                   14324:         my $parser = HTML::LCParser->new($file);
                   14325:         while (my $token = $parser->get_token()) {
                   14326:             if ($token->[0] eq 'S') {
                   14327:                 my $item = $token->[1];
                   14328:                 my $name = $token->[2]{'name'};
                   14329:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14330:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14331:                 my $namematch = $token->[2]{'namematch'};
                   14332:                 if ($item eq 'parameter') {
                   14333:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14334:                         my $release = $parser->get_text();
                   14335:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14336:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14337:                     }
                   14338:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14339:                     my $release = $parser->get_text();
                   14340:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14341:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14342:                 }
                   14343:             }
                   14344:         }
                   14345:     }
1.1073    raeburn  14346: }
                   14347: 
1.1138    raeburn  14348: # ---------------------------------------------------------- Read managers table
                   14349: {
                   14350:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14351:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14352:             while (my $configline=<$config>) {
                   14353:                 chomp($configline);
                   14354:                 next if ($configline =~ /^\#/);
                   14355:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14356:                     $managerstab{$configline} = 1;
                   14357:                 }
                   14358:             }
                   14359:             close($config);
                   14360:         }
                   14361:     }
                   14362: }
                   14363: 
1.329     matthew  14364: # ------------- set up temporary directory
                   14365: {
1.1117    foxr     14366:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14367: 
1.11      www      14368: }
                   14369: 
1.794     albertel 14370: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14371: 				'compress_threshold'=> 20_000,
                   14372:  			        });
1.185     www      14373: 
1.281     www      14374: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14375: $dumpcount=0;
1.958     www      14376: $locknum=0;
1.22      www      14377: 
1.163     harris41 14378: &logtouch();
1.672     albertel 14379: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14380: $readit=1;
1.564     albertel 14381:     {
                   14382: 	use integer;
                   14383: 	my $test=(2**32)+1;
1.568     albertel 14384: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14385: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14386:     }
1.195     www      14387: }
1.1       albertel 14388: }
1.179     www      14389: 
1.1       albertel 14390: 1;
1.191     harris41 14391: __END__
                   14392: 
1.243     albertel 14393: =pod
                   14394: 
1.191     harris41 14395: =head1 NAME
                   14396: 
1.243     albertel 14397: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14398: 
                   14399: =head1 SYNOPSIS
                   14400: 
1.243     albertel 14401: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14402: 
                   14403:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14404: 
1.243     albertel 14405: Common parameters:
                   14406: 
                   14407: =over 4
                   14408: 
                   14409: =item *
                   14410: 
                   14411: $uname : an internal username (if $cname expecting a course Id specifically)
                   14412: 
                   14413: =item *
                   14414: 
                   14415: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14416: 
                   14417: =item *
                   14418: 
                   14419: $symb : a resource instance identifier
                   14420: 
                   14421: =item *
                   14422: 
                   14423: $namespace : the name of a .db file that contains the data needed or
                   14424: being set.
                   14425: 
                   14426: =back
                   14427: 
1.394     bowersj2 14428: =head1 OVERVIEW
1.191     harris41 14429: 
1.394     bowersj2 14430: lonnet provides subroutines which interact with the
                   14431: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14432: about classes, users, and resources.
1.243     albertel 14433: 
                   14434: For many of these objects you can also use this to store data about
                   14435: them or modify them in various ways.
1.191     harris41 14436: 
1.394     bowersj2 14437: =head2 Symbs
1.191     harris41 14438: 
1.394     bowersj2 14439: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14440: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14441: map, the resource number of the resource in the map, and the URL of
                   14442: the resource itself. The latter is somewhat redundant, but might help
                   14443: if maps change.
                   14444: 
                   14445: An example is
                   14446: 
                   14447:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14448: 
                   14449: The respective map entry is
                   14450: 
                   14451:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14452:   title="Problem 2">
                   14453:  </resource>
                   14454: 
                   14455: Symbs are used by the random number generator, as well as to store and
                   14456: restore data specific to a certain instance of for example a problem.
                   14457: 
                   14458: =head2 Storing And Retrieving Data
                   14459: 
                   14460: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14461: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14462: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14463: is is the non-critical message twin of cstore. These functions are for
                   14464: handlers to store a perl hash to a user's permanent data space in an
                   14465: easy manner, and to retrieve it again on another call. It is expected
                   14466: that a handler would use this once at the beginning to retrieve data,
                   14467: and then again once at the end to send only the new data back.
                   14468: 
                   14469: The data is stored in the user's data directory on the user's
                   14470: homeserver under the ID of the course.
                   14471: 
                   14472: The hash that is returned by restore will have all of the previous
                   14473: value for all of the elements of the hash.
                   14474: 
                   14475: Example:
                   14476: 
                   14477:  #creating a hash
                   14478:  my %hash;
                   14479:  $hash{'foo'}='bar';
                   14480: 
                   14481:  #storing it
                   14482:  &Apache::lonnet::cstore(\%hash);
                   14483: 
                   14484:  #changing a value
                   14485:  $hash{'foo'}='notbar';
                   14486: 
                   14487:  #adding a new value
                   14488:  $hash{'bar'}='foo';
                   14489:  &Apache::lonnet::cstore(\%hash);
                   14490: 
                   14491:  #retrieving the hash
                   14492:  my %history=&Apache::lonnet::restore();
                   14493: 
                   14494:  #print the hash
                   14495:  foreach my $key (sort(keys(%history))) {
                   14496:    print("\%history{$key} = $history{$key}");
                   14497:  }
                   14498: 
                   14499: Will print out:
1.191     harris41 14500: 
1.394     bowersj2 14501:  %history{1:foo} = bar
                   14502:  %history{1:keys} = foo:timestamp
                   14503:  %history{1:timestamp} = 990455579
                   14504:  %history{2:bar} = foo
                   14505:  %history{2:foo} = notbar
                   14506:  %history{2:keys} = foo:bar:timestamp
                   14507:  %history{2:timestamp} = 990455580
                   14508:  %history{bar} = foo
                   14509:  %history{foo} = notbar
                   14510:  %history{timestamp} = 990455580
                   14511:  %history{version} = 2
                   14512: 
                   14513: Note that the special hash entries C<keys>, C<version> and
                   14514: C<timestamp> were added to the hash. C<version> will be equal to the
                   14515: total number of versions of the data that have been stored. The
                   14516: C<timestamp> attribute will be the UNIX time the hash was
                   14517: stored. C<keys> is available in every historical section to list which
                   14518: keys were added or changed at a specific historical revision of a
                   14519: hash.
                   14520: 
                   14521: B<Warning>: do not store the hash that restore returns directly. This
                   14522: will cause a mess since it will restore the historical keys as if the
                   14523: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14524: 
1.394     bowersj2 14525: Calling convention:
1.191     harris41 14526: 
1.1225    raeburn  14527:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14528:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14529: 
1.394     bowersj2 14530: For more detailed information, see lonnet specific documentation.
1.191     harris41 14531: 
1.394     bowersj2 14532: =head1 RETURN MESSAGES
1.191     harris41 14533: 
1.394     bowersj2 14534: =over 4
1.191     harris41 14535: 
1.394     bowersj2 14536: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14537: 
1.394     bowersj2 14538: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14539: when the connection is brought back up
1.191     harris41 14540: 
1.394     bowersj2 14541: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14542: for later delivery
1.191     harris41 14543: 
1.967     bisitz   14544: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14545: 
1.394     bowersj2 14546: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14547: that was requested
1.191     harris41 14548: 
1.243     albertel 14549: =back
1.191     harris41 14550: 
1.243     albertel 14551: =head1 PUBLIC SUBROUTINES
1.191     harris41 14552: 
1.243     albertel 14553: =head2 Session Environment Functions
1.191     harris41 14554: 
1.243     albertel 14555: =over 4
1.191     harris41 14556: 
1.394     bowersj2 14557: =item * 
                   14558: X<appenv()>
1.949     raeburn  14559: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14560: the user envirnoment file, and will be restored for each access this
1.620     albertel 14561: user makes during this session, also modifies the %env for the current
1.949     raeburn  14562: process. Optional rolesarrayref - if defined contains a reference to an array
                   14563: of roles which are exempt from the restriction on modifying user.role entries 
                   14564: in the user's environment.db and in %env.    
1.191     harris41 14565: 
                   14566: =item *
1.394     bowersj2 14567: X<delenv()>
1.987     raeburn  14568: B<delenv($delthis,$regexp)>: removes all items from the session
                   14569: environment file that begin with $delthis. If the 
                   14570: optional second arg - $regexp - is true, $delthis is treated as a 
                   14571: regular expression, otherwise \Q$delthis\E is used. 
                   14572: The values are also deleted from the current processes %env.
1.191     harris41 14573: 
1.795     albertel 14574: =item * get_env_multiple($name) 
                   14575: 
                   14576: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14577: values may be defined and end up as an array ref.
                   14578: 
                   14579: returns an array of values
                   14580: 
1.243     albertel 14581: =back
                   14582: 
                   14583: =head2 User Information
1.191     harris41 14584: 
1.243     albertel 14585: =over 4
1.191     harris41 14586: 
                   14587: =item *
1.394     bowersj2 14588: X<queryauthenticate()>
                   14589: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14590: authentication scheme
                   14591: 
                   14592: =item *
1.394     bowersj2 14593: X<authenticate()>
1.1073    raeburn  14594: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14595: authenticate user from domain's lib servers (first use the current
                   14596: one). C<$upass> should be the users password.
1.1073    raeburn  14597: $checkdefauth is optional (value is 1 if a check should be made to
                   14598:    authenticate user using default authentication method, and allow
                   14599:    account creation if username does not have account in the domain).
                   14600: $clientcancheckhost is optional (value is 1 if checking whether the
                   14601:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14602: 
                   14603: =item *
1.394     bowersj2 14604: X<homeserver()>
                   14605: B<homeserver($uname,$udom)>: find the server which has
                   14606: the user's directory and files (there must be only one), this caches
                   14607: the answer, and also caches if there is a borken connection.
1.191     harris41 14608: 
                   14609: =item *
1.394     bowersj2 14610: X<idget()>
1.1300    raeburn  14611: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14612: a list of student/employee IDs or clicker IDs
                   14613: (student/employee IDs are a unique resource in a domain, there must be 
                   14614: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14615: clickerIDs are not necessarily unique, as students might share clickers.
                   14616: (returns hash: id=>name,id=>name)
1.191     harris41 14617: 
                   14618: =item *
1.394     bowersj2 14619: X<idrget()>
                   14620: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14621: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14622: 
                   14623: =item *
1.394     bowersj2 14624: X<idput()>
1.1300    raeburn  14625: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14626: names and associated student/employee IDs or clicker IDs.
                   14627: 
                   14628: =item *
                   14629: X<iddel()>
                   14630: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14631: student/employee ID or clicker ID username look-ups from domain.
                   14632: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14633: If no $uhome is provided, it will be determined usig &homeserver()
                   14634: for each user.  If no $namespace is provided, the default is ids.
                   14635: 
                   14636: =item *
                   14637: X<updateclickers()>
                   14638: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14639: clicker ID-to-username look-ups in clickers.db on library server.
                   14640: Permitted actions are add or del (i.e., add or delete). The 
                   14641: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14642: value is an escaped comma-separated list of usernames (for whom the
                   14643: library server is the homeserver), who registered that particular ID.
                   14644: If $critical is true, the update will be sent via &critical, otherwise
                   14645: &reply() will be used.
1.191     harris41 14646: 
                   14647: =item *
1.394     bowersj2 14648: X<rolesinit()>
1.1169    droeschl 14649: B<rolesinit($udom,$username)>: get user privileges.
                   14650: returns user role, first access and timer interval hashes
1.243     albertel 14651: 
                   14652: =item *
1.1171    droeschl 14653: X<privileged()>
                   14654: B<privileged($username,$domain)>: returns a true if user has a
                   14655: privileged and active role (i.e. su or dc), false otherwise.
                   14656: 
                   14657: =item *
1.551     albertel 14658: X<getsection()>
                   14659: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14660: course $cname, return section name/number or '' for "not in course"
                   14661: and '-1' for "no section"
                   14662: 
                   14663: =item *
1.394     bowersj2 14664: X<userenvironment()>
                   14665: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14666: passed in @what from the requested user's environment, returns a hash
                   14667: 
1.858     raeburn  14668: =item * 
                   14669: X<userlog_query()>
1.859     albertel 14670: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14671: activity.log file. %filters defines filters applied when parsing the
                   14672: log file. These can be start or end timestamps, or the type of action
                   14673: - log to look for Login or Logout events, check for Checkin or
                   14674: Checkout, role for role selection. The response is in the form
                   14675: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14676: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14677: 
1.243     albertel 14678: =back
                   14679: 
                   14680: =head2 User Roles
                   14681: 
                   14682: =over 4
                   14683: 
                   14684: =item *
                   14685: 
1.1284    raeburn  14686: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14687: returns codes for allowed actions.
                   14688: 
                   14689: The first argument is required, all others are optional.
                   14690: 
                   14691: $priv is the privilege being checked.
                   14692: $uri contains additional information about what is being checked for access (e.g.,
                   14693: URL, course ID etc.). 
                   14694: $symb is the unique resource instance identifier in a course; if needed,
                   14695: but not provided, it will be retrieved via a call to &symbread(). 
                   14696: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14697: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14698: files).
                   14699: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14700: prevents recursive calls to &allowed.
                   14701: 
1.243     albertel 14702:  F: full access
                   14703:  U,I,K: authentication modes (cxx only)
                   14704:  '': forbidden
                   14705:  1: user needs to choose course
                   14706:  2: browse allowed
1.766     albertel 14707:  A: passphrase authentication needed
1.1284    raeburn  14708:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14709: 
                   14710: =item *
                   14711: 
1.1192    raeburn  14712: constructaccess($url,$setpriv) : check for access to construction space URL
                   14713: 
                   14714: See if the owner domain and name in the URL match those in the
                   14715: expected environment.  If so, return three element list
                   14716: ($ownername,$ownerdomain,$ownerhome).
                   14717: 
                   14718: Otherwise return the null string.
                   14719: 
                   14720: If second argument 'setpriv' is true, it assigns the privileges,
                   14721: and returns the same three element list, unless the owner has
                   14722: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14723: in which case the null string is returned.
                   14724: 
                   14725: =item *
                   14726: 
1.1326    raeburn  14727: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14728: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14729: for system, domain, and course level. $uname and $udom are optional (current
                   14730: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14731: 
                   14732: =item *
                   14733: 
1.988     raeburn  14734: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14735: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14736: $type is Course (default) or Community.
1.988     raeburn  14737: If $forcedefault evaluates to true, text returned will be default 
                   14738: text for $type. Otherwise, if this is a course, the text returned 
                   14739: will be a custom name for the role (if defined in the course's 
                   14740: environment).  If no custom name is defined the default is returned.
                   14741:    
1.832     raeburn  14742: =item *
                   14743: 
1.1219    raeburn  14744: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14745: All arguments are optional. Returns a hash of a roles, either for
                   14746: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14747: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14748: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14749: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14750: For each key, value is set to colon-separated start and end times for
                   14751: the role.  If no username and domain are specified, will default to
1.934     raeburn  14752: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14753: of role statuses (active, future or previous), roles 
                   14754: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14755: to restrict the list of roles reported. If no array ref is 
                   14756: provided for types, will default to return only active roles.
1.834     albertel 14757: 
1.1195    raeburn  14758: =item *
                   14759: 
                   14760: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14761: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14762: 
                   14763: Additional optional arguments are: $type (if role checking is to be restricted 
                   14764: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14765: available roles) or future (roles available in the future), and
                   14766: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14767: have active Domain Coordinator role in course's domain or in additional
                   14768: domains (specified in 'Domains to check for privileged users' in course
                   14769: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14770: 
                   14771: =item *
                   14772: 
                   14773: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14774: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14775: $possdomains and $possroles are optional array refs -- to domains to check and
                   14776: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14777: users' roles.db to check for a dc or su role in any domain. This can be
                   14778: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14779: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14780: this then allows &privileged_by_domain() to be used, which caches the identity
                   14781: of privileged users, eliminating the need for repeated calls to &dump().
                   14782: 
                   14783: =item *
                   14784: 
                   14785: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14786: where the outer hash keys are domains specified in the $possdomains array ref,
                   14787: next inner hash keys are privileged roles specified in the $roles array ref,
                   14788: and the innermost hash contains key = value pairs for username:domain = end:start
                   14789: for active or future "privileged" users with that role in that domain. To avoid
                   14790: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14791: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14792: 
1.243     albertel 14793: =back
                   14794: 
                   14795: =head2 User Modification
                   14796: 
                   14797: =over 4
                   14798: 
                   14799: =item *
                   14800: 
1.957     raeburn  14801: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14802: user for the level given by URL.  Optional start and end dates (leave empty
                   14803: string or zero for "no date")
1.191     harris41 14804: 
                   14805: =item *
                   14806: 
1.243     albertel 14807: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14808: change a users, password, possible return values are: ok,
                   14809: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14810: refused
1.191     harris41 14811: 
                   14812: =item *
                   14813: 
1.243     albertel 14814: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14815: 
                   14816: =item *
                   14817: 
1.1058    raeburn  14818: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14819:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14820: 
                   14821: will update user information (firstname,middlename,lastname,generation,
                   14822: permanentemail), and if forceid is true, student/employee ID also.
                   14823: A user's institutional affiliation(s) can also be updated.
                   14824: User information fields will not be overwritten with empty entries 
                   14825: unless the field is included in the $candelete array reference.
                   14826: This array is included when a single user is modified via "Manage Users",
                   14827: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14828: 
                   14829: =item *
                   14830: 
1.286     matthew  14831: modifystudent
                   14832: 
1.957     raeburn  14833: modify a student's enrollment and identification information.
1.1235    raeburn  14834: The course id is resolved based on the current user's environment.  
                   14835: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14836: associated with a course.
                   14837: 
1.297     matthew  14838: This call is essentially a wrapper for lonnet::modifyuser and
                   14839: lonnet::modify_student_enrollment
1.286     matthew  14840: 
                   14841: Inputs: 
                   14842: 
                   14843: =over 4
                   14844: 
1.957     raeburn  14845: =item B<$udom> Student's loncapa domain
1.286     matthew  14846: 
1.957     raeburn  14847: =item B<$uname> Student's loncapa login name
1.286     matthew  14848: 
1.964     bisitz   14849: =item B<$uid> Student/Employee ID
1.286     matthew  14850: 
1.957     raeburn  14851: =item B<$umode> Student's authentication mode
1.286     matthew  14852: 
1.957     raeburn  14853: =item B<$upass> Student's password
1.286     matthew  14854: 
1.957     raeburn  14855: =item B<$first> Student's first name
1.286     matthew  14856: 
1.957     raeburn  14857: =item B<$middle> Student's middle name
1.286     matthew  14858: 
1.957     raeburn  14859: =item B<$last> Student's last name
1.286     matthew  14860: 
1.957     raeburn  14861: =item B<$gene> Student's generation
1.286     matthew  14862: 
1.957     raeburn  14863: =item B<$usec> Student's section in course
1.286     matthew  14864: 
                   14865: =item B<$end> Unix time of the roles expiration
                   14866: 
                   14867: =item B<$start> Unix time of the roles start date
                   14868: 
                   14869: =item B<$forceid> If defined, allow $uid to be changed
                   14870: 
                   14871: =item B<$desiredhome> server to use as home server for student
                   14872: 
1.957     raeburn  14873: =item B<$email> Student's permanent e-mail address
                   14874: 
                   14875: =item B<$type> Type of enrollment (auto or manual)
                   14876: 
1.963     raeburn  14877: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14878: 
                   14879: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14880: 
1.963     raeburn  14881: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14882: 
1.963     raeburn  14883: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14884: 
1.1216    raeburn  14885: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14886: 
                   14887: =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  14888: 
1.286     matthew  14889: =back
1.297     matthew  14890: 
                   14891: =item *
                   14892: 
                   14893: modify_student_enrollment
                   14894: 
1.1235    raeburn  14895: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14896: 'role.request.course' must be defined for this function to proceed.
                   14897: 
                   14898: Inputs:
                   14899: 
                   14900: =over 4
                   14901: 
1.1235    raeburn  14902: =item $udom, student's domain
1.297     matthew  14903: 
1.1235    raeburn  14904: =item $uname, student's name
1.297     matthew  14905: 
1.1235    raeburn  14906: =item $uid, student's user id
1.297     matthew  14907: 
1.1235    raeburn  14908: =item $first, student's first name
1.297     matthew  14909: 
                   14910: =item $middle
                   14911: 
                   14912: =item $last
                   14913: 
                   14914: =item $gene
                   14915: 
                   14916: =item $usec
                   14917: 
                   14918: =item $end
                   14919: 
                   14920: =item $start
                   14921: 
1.957     raeburn  14922: =item $type
                   14923: 
                   14924: =item $locktype
                   14925: 
                   14926: =item $cid
                   14927: 
                   14928: =item $selfenroll
                   14929: 
                   14930: =item $context
                   14931: 
1.1216    raeburn  14932: =item $credits, number of credits student will earn from this class
                   14933: 
1.1314    raeburn  14934: =item $instsec, institutional course section code for student
                   14935: 
1.297     matthew  14936: =back
                   14937: 
1.191     harris41 14938: 
                   14939: =item *
                   14940: 
1.243     albertel 14941: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14942: custom role; give a custom role to a user for the level given by URL.  Specify
                   14943: name and domain of role author, and role name
1.191     harris41 14944: 
                   14945: =item *
                   14946: 
1.243     albertel 14947: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14948: 
                   14949: =item *
                   14950: 
1.243     albertel 14951: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14952: 
                   14953: =back
                   14954: 
                   14955: =head2 Course Infomation
                   14956: 
                   14957: =over 4
1.191     harris41 14958: 
                   14959: =item *
                   14960: 
1.1118    foxr     14961: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14962: specified course id, including all environment settings for the
                   14963: course, the description of the course will be in the hash under the
                   14964: key 'description'
1.191     harris41 14965: 
1.1118    foxr     14966: $options is an optional parameter that if supplied is a hash reference that controls
                   14967: what how this function works.  It has the following key/values:
                   14968: 
                   14969: =over 4
                   14970: 
                   14971: =item freshen_cache
                   14972: 
                   14973: If defined, and the environment cache for the course is valid, it is 
                   14974: returned in the returned hash.
                   14975: 
                   14976: =item one_time
                   14977: 
                   14978: If defined, the last cache time is set to _now_
                   14979: 
                   14980: =item user
                   14981: 
                   14982: If defined, the supplied username is used instead of the current user.
                   14983: 
                   14984: 
                   14985: =back
                   14986: 
1.191     harris41 14987: =item *
                   14988: 
1.624     albertel 14989: resdata($name,$domain,$type,@which) : request for current parameter
                   14990: setting for a specific $type, where $type is either 'course' or 'user',
                   14991: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14992: answers for 10 minutes.
1.243     albertel 14993: 
1.877     foxr     14994: =item *
                   14995: 
                   14996: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14997: data base, returning a hash that is keyed by the resource name and has
                   14998: values that are the resource value.  I believe that the timestamps and
                   14999: versions are also returned.
                   15000: 
1.1236    raeburn  15001: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15002: supplemental content area. This routine caches the number of files for 
                   15003: 10 minutes.
                   15004: 
1.243     albertel 15005: =back
                   15006: 
                   15007: =head2 Course Modification
                   15008: 
                   15009: =over 4
1.191     harris41 15010: 
                   15011: =item *
                   15012: 
1.243     albertel 15013: writecoursepref($courseid,%prefs) : write preferences (environment
                   15014: database) for a course
1.191     harris41 15015: 
                   15016: =item *
                   15017: 
1.1011    raeburn  15018: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15019: 
                   15020: =item *
                   15021: 
1.1038    raeburn  15022: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15023: 
1.1167    droeschl 15024: =item *
                   15025: 
                   15026: is_course($courseid), is_course($cdom, $cnum)
                   15027: 
                   15028: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15029: two component version $cdom, $cnum. It checks if the specified course exists.
                   15030: 
                   15031: Returns:
                   15032:     undef if the course doesn't exist, otherwise
                   15033:     in scalar context the combined courseid.
                   15034:     in list context the two components of the course identifier, domain and 
                   15035:     courseid.    
                   15036: 
1.243     albertel 15037: =back
                   15038: 
                   15039: =head2 Resource Subroutines
                   15040: 
                   15041: =over 4
1.191     harris41 15042: 
                   15043: =item *
                   15044: 
1.243     albertel 15045: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15046: 
                   15047: =item *
                   15048: 
1.243     albertel 15049: repcopy($filename) : subscribes to the requested file, and attempts to
                   15050: replicate from the owning library server, Might return
1.607     raeburn  15051: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15052: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15053: resource. Expects the local filesystem pathname
                   15054: (/home/httpd/html/res/....)
                   15055: 
                   15056: =back
                   15057: 
                   15058: =head2 Resource Information
                   15059: 
                   15060: =over 4
1.191     harris41 15061: 
                   15062: =item *
                   15063: 
1.1228    raeburn  15064: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15065: and returns the value of a variety of different possible values,
                   15066: $varname should be a request string, and the other parameters can be
                   15067: used to specify who and what one is asking about. Ordinarily, $cid 
                   15068: does not need to be specified, as it is retrived from 
                   15069: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15070: within lonuserstate::loadmap() when initializing a course, before
                   15071: $env{'request.course.id'} has been set, so it needs to be provided
                   15072: in that one case.
1.243     albertel 15073: 
                   15074: Possible values for $varname are environment.lastname (or other item
                   15075: from the envirnment hash), user.name (or someother aspect about the
                   15076: user), resource.0.maxtries (or some other part and parameter of a
                   15077: resource)
1.204     albertel 15078: 
                   15079: =item *
                   15080: 
1.243     albertel 15081: directcondval($number) : get current value of a condition; reads from a state
                   15082: string
1.204     albertel 15083: 
                   15084: =item *
                   15085: 
1.243     albertel 15086: condval($condidx) : value of condition index based on state
1.204     albertel 15087: 
                   15088: =item *
                   15089: 
1.1362    raeburn  15090: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15091: resource's metadata, $what should be either a specific key, or either
                   15092: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15093: packages that this resource currently uses, the last 3 arguments are 
                   15094: only used internally for recursive metadata.
                   15095: 
                   15096: the toolsymb is only used where the uri is for an external tool (for which
                   15097: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15098: 
1.1371    raeburn  15099: this function automatically caches all requests except any made recursively
                   15100: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15101: defined).
1.191     harris41 15102: 
                   15103: =item *
                   15104: 
1.243     albertel 15105: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15106: network of library servers; returns file handle of where SQL and regex results
                   15107: will be stored for query
1.191     harris41 15108: 
                   15109: =item *
                   15110: 
1.1282    raeburn  15111: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15112: return symbolic list entry (all arguments optional). 
                   15113: 
                   15114: Args: filename is the filename (including path) for the file for which a symb 
                   15115: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15116: to check access status if more than one resource was found in the bighash 
                   15117: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15118: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15119: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15120: cause possible symbs to be checked to determine if they are subject to content
                   15121: blocking, if so they will not be included as possible symbs; possibles is a
                   15122: ref to a hash, which, as a side effect, will be populated with all possible 
                   15123: symbs (content blocking not tested).
                   15124:  
1.243     albertel 15125: returns the data handle
1.191     harris41 15126: 
                   15127: =item *
                   15128: 
1.1190    raeburn  15129: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15130: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15131: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15132: on failure, user must be in a course, as it assumes the existence of
                   15133: the course initial hash, and uses $env('request.course.id'}.  The third
                   15134: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15135: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15136: encrypted; otherwise it will be null.  
1.191     harris41 15137: 
                   15138: =item *
                   15139: 
1.243     albertel 15140: symbclean($symb) : removes versions numbers from a symb, returns the
                   15141: cleaned symb
1.191     harris41 15142: 
                   15143: =item *
                   15144: 
1.243     albertel 15145: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15146: course map, user must be in a course for it to work.
1.191     harris41 15147: 
                   15148: =item *
                   15149: 
1.243     albertel 15150: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15151: 
                   15152: =item *
                   15153: 
1.243     albertel 15154: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15155: a random seed, all arguments are optional, if they aren't sent it uses the
                   15156: environment to derive them. Note: if symb isn't sent and it can't get one
                   15157: from &symbread it will use the current time as its return value
1.191     harris41 15158: 
                   15159: =item *
                   15160: 
1.243     albertel 15161: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15162: unfakeable, receipt
1.191     harris41 15163: 
                   15164: =item *
                   15165: 
1.620     albertel 15166: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15167: 
                   15168: =item *
                   15169: 
1.243     albertel 15170: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15171: 
                   15172: =item *
                   15173: 
1.243     albertel 15174: 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 15175: 
                   15176: =item *
                   15177: 
1.243     albertel 15178: 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 15179: 
                   15180: =item *
                   15181: 
1.243     albertel 15182: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15183: 
                   15184: =item *
                   15185: 
1.243     albertel 15186: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15187: forcing spreadsheet to reevaluate the resource scores next time.
                   15188: 
1.1195    raeburn  15189: =item * 
                   15190: 
1.1196    raeburn  15191: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15192: when viewing in course context.
1.1195    raeburn  15193: 
1.1196    raeburn  15194:  input: six args -- filename (decluttered), course number, course domain,
                   15195:                     url, symb (if registered) and group (if this is a 
                   15196:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15197: 
1.1196    raeburn  15198:  output: array of five scalars --
1.1195    raeburn  15199:          $cfile -- url for file editing if editable on current server
                   15200:          $home -- homeserver of resource (i.e., for author if published,
                   15201:                                           or course if uploaded.).
                   15202:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15203:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15204:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15205: 
                   15206: =item *
                   15207: 
                   15208: is_course_upload($file,$cnum,$cdom)
                   15209: 
                   15210: Used in course context to determine if current file was uploaded to 
                   15211: the course (i.e., would be found in /userfiles/docs on the course's 
                   15212: homeserver.
                   15213: 
                   15214:   input: 3 args -- filename (decluttered), course number and course domain.
                   15215:   output: boolean -- 1 if file was uploaded.
                   15216: 
1.243     albertel 15217: =back
                   15218: 
                   15219: =head2 Storing/Retreiving Data
                   15220: 
                   15221: =over 4
1.191     harris41 15222: 
                   15223: =item *
                   15224: 
1.1269    raeburn  15225: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15226: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15227: the remaining args aren't required and if they aren't passed or are '' they will
                   15228: be derived from the env (with the exception of $laststore, which is an 
                   15229: optional arg used when a user's submission is stored in grading).
                   15230: $laststore is $version=$timestamp, where $version is the most recent version
                   15231: number retrieved for the corresponding $symb in the $namespace db file, and
                   15232: $timestamp is the timestamp for that transaction (UNIX time).
                   15233: $laststore is currently only passed when cstore() is called by 
                   15234: structuretags::finalize_storage().
1.191     harris41 15235: 
                   15236: =item *
                   15237: 
1.1269    raeburn  15238: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15239: but uses critical subroutine
1.191     harris41 15240: 
                   15241: =item *
                   15242: 
1.243     albertel 15243: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15244: all args are optional
1.191     harris41 15245: 
                   15246: =item *
                   15247: 
1.717     albertel 15248: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15249: dumps the complete (or key matching regexp) namespace into a hash
                   15250: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15251: normally &store()ed into
                   15252: 
                   15253: $range should be either an integer '100' (give me the first 100
                   15254:                                            matching records)
                   15255:               or be  two integers sperated by a - with no spaces
                   15256:                  '30-50' (give me the 30th through the 50th matching
                   15257:                           records)
                   15258: 
                   15259: 
                   15260: =item *
                   15261: 
1.1269    raeburn  15262: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15263: replaces a &store() version of data with a replacement set of data
                   15264: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15265: reference. If $tolog is true, the transaction is logged in the courselog
                   15266: with an action=PUTSTORE.
1.717     albertel 15267: 
                   15268: =item *
                   15269: 
1.243     albertel 15270: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15271: works very similar to store/cstore, but all data is stored in a
                   15272: temporary location and can be reset using tmpreset, $storehash should
                   15273: be a hash reference, returns nothing on success
1.191     harris41 15274: 
                   15275: =item *
                   15276: 
1.243     albertel 15277: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15278: similar to restore, but all data is stored in a temporary location and
                   15279: can be reset using tmpreset. Returns a hash of values on success,
                   15280: error string otherwise.
1.191     harris41 15281: 
                   15282: =item *
                   15283: 
1.243     albertel 15284: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15285: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15286: 
                   15287: =item *
                   15288: 
1.243     albertel 15289: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15290: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15291: 
                   15292: =item *
                   15293: 
1.243     albertel 15294: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15295: namesp ($udom and $uname are optional)
1.191     harris41 15296: 
                   15297: =item *
                   15298: 
1.702     albertel 15299: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15300: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15301: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15302: 
1.702     albertel 15303: $range should be either an integer '100' (give me the first 100
                   15304:                                            matching records)
                   15305:               or be  two integers sperated by a - with no spaces
                   15306:                  '30-50' (give me the 30th through the 50th matching
                   15307:                           records)
1.449     matthew  15308: =item *
                   15309: 
                   15310: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15311: $store can be a scalar, an array reference, or if the amount to be 
                   15312: incremented is > 1, a hash reference.
                   15313: 
                   15314: ($udom and $uname are optional)
1.191     harris41 15315: 
                   15316: =item *
                   15317: 
1.243     albertel 15318: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15319: ($udom and $uname are optional)
1.191     harris41 15320: 
                   15321: =item *
                   15322: 
1.243     albertel 15323: cput($namespace,$storehash,$udom,$uname) : critical put
                   15324: ($udom and $uname are optional)
1.191     harris41 15325: 
                   15326: =item *
                   15327: 
1.748     albertel 15328: newput($namespace,$storehash,$udom,$uname) :
                   15329: 
                   15330: Attempts to store the items in the $storehash, but only if they don't
                   15331: currently exist, if this succeeds you can be certain that you have 
                   15332: successfully created a new key value pair in the $namespace db.
                   15333: 
                   15334: 
                   15335: Args:
                   15336:  $namespace: name of database to store values to
                   15337:  $storehash: hashref to store to the db
                   15338:  $udom: (optional) domain of user containing the db
                   15339:  $uname: (optional) name of user caontaining the db
                   15340: 
                   15341: Returns:
                   15342:  'ok' -> succeeded in storing all keys of $storehash
                   15343:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15344:                         least <key> already existed in the db (other
                   15345:                         requested keys may also already exist)
1.967     bisitz   15346:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15347:  'con_lost' -> unable to contact request server
                   15348:  'refused' -> action was not allowed by remote machine
                   15349: 
                   15350: 
                   15351: =item *
                   15352: 
1.243     albertel 15353: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15354: reference filled in from namesp (encrypts the return communication)
                   15355: ($udom and $uname are optional)
1.191     harris41 15356: 
                   15357: =item *
                   15358: 
1.243     albertel 15359: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15360: critical subroutine
                   15361: 
1.806     raeburn  15362: =item *
                   15363: 
1.860     raeburn  15364: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15365: array reference filled in from namespace found in domain level on either
                   15366: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15367: 
                   15368: =item *
                   15369: 
1.860     raeburn  15370: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15371: domain level either on specified domain server ($uhome) or primary domain 
                   15372: server ($udom and $uhome are optional)
1.806     raeburn  15373: 
1.943     raeburn  15374: =item * 
                   15375: 
1.1240    raeburn  15376: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15377: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15378: the target domain.
                   15379: 
                   15380: May also include additional key => value pairs for the following groups:
                   15381: 
                   15382: =over
                   15383: 
                   15384: =item
                   15385: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15386: 
                   15387: =over
                   15388: 
                   15389: =item defaultquota, authorquota
                   15390: 
                   15391: =back
                   15392: 
                   15393: =item
                   15394: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15395: portfolio for users).
                   15396: 
                   15397: =over
                   15398: 
                   15399: =item
                   15400: aboutme, blog, webdav, portfolio
                   15401: 
                   15402: =back
                   15403: 
                   15404: =item
                   15405: requestcourses: ability to request courses, and how requests are processed.
                   15406: 
                   15407: =over
                   15408: 
                   15409: =item
1.1305    raeburn  15410: official, unofficial, community, textbook, placement
1.1240    raeburn  15411: 
                   15412: =back
                   15413: 
                   15414: =item
                   15415: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15416: 
                   15417: =over
                   15418: 
                   15419: =item
1.1256    raeburn  15420: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15421: 
                   15422: =back
                   15423: 
                   15424: =item
                   15425: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15426: for course's uploaded content.
                   15427: 
                   15428: =over
                   15429: 
                   15430: =item
1.1246    raeburn  15431: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15432: communityquota, textbookquota, placementquota
1.1240    raeburn  15433: 
                   15434: =back
                   15435: 
                   15436: =item
                   15437: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15438: on your servers.
                   15439: 
                   15440: =over
                   15441: 
                   15442: =item 
                   15443: remotesessions, hostedsessions
                   15444: 
                   15445: =back
                   15446: 
                   15447: =back
                   15448: 
                   15449: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15450: utility to create a configuration.db file on a domain's primary library server 
                   15451: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15452: -- corresponding values are authentication type (internal, krb4, krb5,
                   15453: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15454: will be available. Values are retrieved from cache (if current), unless the
                   15455: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15456: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15457: 
                   15458: Typical usage:
1.943     raeburn  15459: 
1.1240    raeburn  15460: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15461: 
1.243     albertel 15462: =back
                   15463: 
                   15464: =head2 Network Status Functions
                   15465: 
                   15466: =over 4
1.191     harris41 15467: 
                   15468: =item *
                   15469: 
1.1137    raeburn  15470: dirlist() : return directory list based on URI (first arg).
                   15471: 
                   15472: Inputs: 1 required, 5 optional.
                   15473: 
                   15474: =over
                   15475: 
                   15476: =item 
                   15477: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15478: 
                   15479: =item
                   15480: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15481: 
                   15482: =item
                   15483: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15484: 
                   15485: =item
                   15486: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15487: 
                   15488: =item
                   15489: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15490: 
                   15491: =item 
                   15492: $alternateRoot - path to prepend in place of path from $uri.
                   15493: 
                   15494: =back
                   15495: 
                   15496: Returns: Array of up to two items.
                   15497: 
                   15498: =over
                   15499: 
                   15500: a reference to an array of files/subdirectories
                   15501: 
                   15502: =over
                   15503: 
                   15504: Each element in the array of files/subdirectories is a & separated list of
                   15505: item name and the result of running stat on the item.  If dirlist was requested
                   15506: for a file instead of a directory, the item name will be ''. For a directory 
                   15507: listing, if the item is a metadata file, the element will end &N&M 
                   15508: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15509: default copyright set (1).  
                   15510: 
                   15511: =back
                   15512: 
                   15513: a scalar containing error condition (if encountered).
                   15514: 
                   15515: =over
                   15516: 
                   15517: =item 
                   15518: no_host (no homeserver identified for $username:$domain).
                   15519: 
                   15520: =item 
                   15521: no_such_host (server contacted for listing not identified as valid host).
                   15522: 
                   15523: =item 
                   15524: con_lost (connection to remote server failed).
                   15525: 
                   15526: =item 
                   15527: refused (invalid $username:$domain received on lond side).
                   15528: 
                   15529: =item 
                   15530: no_such_dir (directory at specified path on lond side does not exist). 
                   15531: 
                   15532: =item 
                   15533: empty (directory at specified path on lond side is empty).
                   15534: 
                   15535: =over
                   15536: 
                   15537: This is currently not encountered because the &ls3, &ls2, 
                   15538: &ls (_handler) routines on the lond side do not filter out
                   15539: . and .. from a directory listing. 
                   15540: 
                   15541: =back
                   15542: 
                   15543: =back
                   15544: 
                   15545: =back
1.191     harris41 15546: 
                   15547: =item *
                   15548: 
1.243     albertel 15549: spareserver() : find server with least workload from spare.tab
                   15550: 
1.986     foxr     15551: 
                   15552: =item *
                   15553: 
                   15554: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15555: if there is no corresponding loncapa host.
                   15556: 
1.243     albertel 15557: =back
                   15558: 
1.986     foxr     15559: 
1.243     albertel 15560: =head2 Apache Request
                   15561: 
                   15562: =over 4
1.191     harris41 15563: 
                   15564: =item *
                   15565: 
1.243     albertel 15566: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15567: localhost, posts hash
                   15568: 
                   15569: =back
                   15570: 
                   15571: =head2 Data to String to Data
                   15572: 
                   15573: =over 4
1.191     harris41 15574: 
                   15575: =item *
                   15576: 
1.243     albertel 15577: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15578: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15579: 
                   15580: =item *
                   15581: 
1.243     albertel 15582: hashref2str($hashref) : convert a hashref into a string complete with
                   15583: escaping and '=' and '&' separators, supports elements that are
                   15584: arrayrefs and hashrefs
1.191     harris41 15585: 
                   15586: =item *
                   15587: 
1.243     albertel 15588: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15589: with escaping and '&' separators, supports elements that are arrayrefs
                   15590: and hashrefs
1.191     harris41 15591: 
                   15592: =item *
                   15593: 
1.243     albertel 15594: str2hash($string) : convert string to hash using unescaping and
                   15595: splitting on '=' and '&', supports elements that are arrayrefs and
                   15596: hashrefs
1.191     harris41 15597: 
                   15598: =item *
                   15599: 
1.243     albertel 15600: str2array($string) : convert string to hash using unescaping and
                   15601: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15602: 
                   15603: =back
                   15604: 
                   15605: =head2 Logging Routines
                   15606: 
                   15607: 
                   15608: These routines allow one to make log messages in the lonnet.log and
                   15609: lonnet.perm logfiles.
1.191     harris41 15610: 
1.1119    foxr     15611: =over 4
                   15612: 
1.191     harris41 15613: =item *
                   15614: 
1.243     albertel 15615: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15616: 
                   15617: =item *
                   15618: 
1.243     albertel 15619: logthis() : append message to the normal lonnet.log file, it gets
                   15620: preiodically rolled over and deleted.
1.191     harris41 15621: 
                   15622: =item *
                   15623: 
1.243     albertel 15624: logperm() : append a permanent message to lonnet.perm.log, this log
                   15625: file never gets deleted by any automated portion of the system, only
                   15626: messages of critical importance should go in here.
                   15627: 
1.1119    foxr     15628: 
1.243     albertel 15629: =back
                   15630: 
                   15631: =head2 General File Helper Routines
                   15632: 
                   15633: =over 4
1.191     harris41 15634: 
                   15635: =item *
                   15636: 
1.481     raeburn  15637: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15638: (a) files in /uploaded
                   15639:   (i) If a local copy of the file exists - 
                   15640:       compares modification date of local copy with last-modified date for 
                   15641:       definitive version stored on home server for course. If local copy is 
                   15642:       stale, requests a new version from the home server and stores it. 
                   15643:       If the original has been removed from the home server, then local copy 
                   15644:       is unlinked.
                   15645:   (ii) If local copy does not exist -
                   15646:       requests the file from the home server and stores it. 
                   15647:   
                   15648:   If $caller is 'uploadrep':  
                   15649:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15650:     for request for files originally uploaded via DOCS. 
                   15651:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15652:   
                   15653:   Otherwise:
                   15654:      This indicates a call from the content generation phase of the request.
                   15655:      -  returns the entire contents of the file or -1.
                   15656:      
                   15657: (b) files in /res
                   15658:    - returns the entire contents of a file or -1; 
                   15659:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15660: 
1.712     albertel 15661: 
                   15662: =item *
                   15663: 
                   15664: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15665:                   reference
                   15666: 
                   15667: returns either a stat() list of data about the file or an empty list
                   15668: if the file doesn't exist or couldn't find out about it (connection
                   15669: problems or user unknown)
                   15670: 
1.191     harris41 15671: =item *
                   15672: 
1.243     albertel 15673: filelocation($dir,$file) : returns file system location of a file
                   15674: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15675: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15676: and a file of ../bob will become /a/bob)
1.191     harris41 15677: 
                   15678: =item *
                   15679: 
                   15680: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15681: filelocation except for hrefs
                   15682: 
                   15683: =item *
                   15684: 
1.1261    raeburn  15685: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15686: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15687: 
1.243     albertel 15688: =back
                   15689: 
1.608     albertel 15690: =head2 Usererfile file routines (/uploaded*)
                   15691: 
                   15692: =over 4
                   15693: 
                   15694: =item *
                   15695: 
                   15696: userfileupload(): main rotine for putting a file in a user or course's
                   15697:                   filespace, arguments are,
                   15698: 
1.620     albertel 15699:  formname - required - this is the name of the element in $env where the
1.608     albertel 15700:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15701:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15702:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15703:  context - if coursedoc, store the file in the course of the active role
                   15704:              of the current user; 
                   15705:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15706:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15707:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15708:          if undefined, it will be placed in "unknown"
                   15709: 
                   15710:  (This routine calls clean_filename() to remove any dangerous
                   15711:  characters from the filename, and then calls finuserfileupload() to
                   15712:  complete the transaction)
                   15713: 
                   15714:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15715:  and /adm/notfound.html if unsuccessful
                   15716: 
                   15717: =item *
                   15718: 
                   15719: clean_filename(): routine for cleaing a filename up for storage in
                   15720:                  userfile space, argument is:
                   15721: 
                   15722:  filename - proposed filename
                   15723: 
                   15724: returns: the new clean filename
                   15725: 
                   15726: =item *
                   15727: 
1.1090    raeburn  15728: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15729: userspace, probably shouldn't be called directly
                   15730: 
                   15731:   docuname: username or courseid of destination for the file
                   15732:   docudom: domain of user/course of destination for the file
                   15733:   formname: same as for userfileupload()
1.1090    raeburn  15734:   fname: filename (including subdirectories) for the file
                   15735:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15736:   allfiles: reference to hash used to store objects found by parser
                   15737:   codebase: reference to hash used for codebases of java objects found by parser
                   15738:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15739:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15740:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15741:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15742:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15743:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15744:   mimetype: reference to scalar to accommodate mime type determined
                   15745:             from File::MMagic if $parser = parse.
1.608     albertel 15746: 
                   15747:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15748:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15749:  was 'overwrite').
                   15750:  
1.608     albertel 15751: 
                   15752: =item *
                   15753: 
                   15754: renameuserfile(): renames an existing userfile to a new name
                   15755: 
                   15756:   Args:
                   15757:    docuname: username or courseid of destination for the file
                   15758:    docudom: domain of user/course of destination for the file
                   15759:    old: current file name (including any subdirs under userfiles)
                   15760:    new: desired file name (including any subdirs under userfiles)
                   15761: 
                   15762: =item *
                   15763: 
                   15764: mkdiruserfile(): creates a directory is a userfiles dir
                   15765: 
                   15766:   Args:
                   15767:    docuname: username or courseid of destination for the file
                   15768:    docudom: domain of user/course of destination for the file
                   15769:    dir: dir to create (including any subdirs under userfiles)
                   15770: 
                   15771: =item *
                   15772: 
                   15773: removeuserfile(): removes a file that exists in userfiles
                   15774: 
                   15775:   Args:
                   15776:    docuname: username or courseid of destination for the file
                   15777:    docudom: domain of user/course of destination for the file
                   15778:    fname: filname to delete (including any subdirs under userfiles)
                   15779: 
                   15780: =item *
                   15781: 
                   15782: removeuploadedurl(): convience function for removeuserfile()
                   15783: 
                   15784:   Args:
                   15785:    url:  a full /uploaded/... url to delete
                   15786: 
1.747     albertel 15787: =item * 
                   15788: 
                   15789: get_portfile_permissions():
                   15790:   Args:
                   15791:     domain: domain of user or course contain the portfolio files
                   15792:     user: name of user or num of course contain the portfolio files
                   15793:   Returns:
                   15794:     hashref of a dump of the proper file_permissions.db
                   15795:    
                   15796: 
                   15797: =item * 
                   15798: 
                   15799: get_access_controls():
                   15800: 
                   15801: Args:
                   15802:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15803:   group: (optional) the group you want the files associated with
                   15804:   file: (optional) the file you want access info on
                   15805: 
                   15806: Returns:
1.749     raeburn  15807:     a hash (keys are file names) of hashes containing
                   15808:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15809:         values are XML containing access control settings (see below) 
1.747     albertel 15810: 
                   15811: Internal notes:
                   15812: 
1.749     raeburn  15813:  access controls are stored in file_permissions.db as key=value pairs.
                   15814:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15815:         where scope -> public,guest,course,group,domains or users.
                   15816:               end -> UNIX time for end of access (0 -> no end date)
                   15817:               start -> UNIX time for start of access
                   15818: 
                   15819:     value -> XML description of access control
                   15820:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15821:             <start></start>
                   15822:             <end></end>
                   15823: 
                   15824:             <password></password>  for scope type = guest
                   15825: 
                   15826:             <domain></domain>     for scope type = course or group
                   15827:             <number></number>
                   15828:             <roles id="">
                   15829:              <role></role>
                   15830:              <access></access>
                   15831:              <section></section>
                   15832:              <group></group>
                   15833:             </roles>
                   15834: 
                   15835:             <dom></dom>         for scope type = domains
                   15836: 
                   15837:             <users>             for scope type = users
                   15838:              <user>
                   15839:               <uname></uname>
                   15840:               <udom></udom>
                   15841:              </user>
                   15842:             </users>
                   15843:            </scope> 
                   15844:               
                   15845:  Access data is also aggregated for each file in an additional key=value pair:
                   15846:  key -> path to file/file_name\0accesscontrol 
                   15847:  value -> reference to hash
                   15848:           hash contains key = value pairs
                   15849:           where key = uniqueID:scope_end_start
                   15850:                 value = UNIX time record was last updated
                   15851: 
                   15852:           Used to improve speed of look-ups of access controls for each file.  
                   15853:  
                   15854:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15855: 
1.1198    raeburn  15856: =item *
                   15857: 
1.749     raeburn  15858: modify_access_controls():
                   15859: 
                   15860: Modifies access controls for a portfolio file
                   15861: Args
                   15862: 1. file name
                   15863: 2. reference to hash of required changes,
                   15864: 3. domain
                   15865: 4. username
                   15866:   where domain,username are the domain of the portfolio owner 
                   15867:   (either a user or a course) 
                   15868: 
                   15869: Returns:
                   15870: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15871: 2. result of deletions ('ok' or 'error', with error message).
                   15872: 3. reference to hash of any new or updated access controls.
                   15873: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15874:    key = integer (inbound ID)
1.1198    raeburn  15875:    value = uniqueID
                   15876: 
                   15877: =item *
                   15878: 
                   15879: get_timebased_id():
                   15880: 
                   15881: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15882: course via the Course Editor (e.g., folders, composite pages, 
                   15883: group bulletin boards).
                   15884: 
                   15885: Args: (first three required; six others optional)
                   15886: 
                   15887: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15888:    docssequence, or name of group
                   15889: 
                   15890: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15891:    e.g., num, boardids
                   15892: 
                   15893: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15894:    file will be named nohist_namespace.db
                   15895: 
                   15896: 4. cdom: domain of course; default is current course domain from %env
                   15897: 
                   15898: 5. cnum: course number; default is current course number from %env
                   15899: 
                   15900: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15901:    unix timestamp to form the suffix, if the plain timestamp is already
                   15902:    in use.  Default is to not do this, but simply increment the unix 
                   15903:    timestamp by 1 until a unique key is obtained.
                   15904: 
                   15905: 7. who: holder of locking key; defaults to user:domain for user.
                   15906: 
                   15907: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15908:    retrying); default is 3.
                   15909: 
                   15910: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15911: 
                   15912: Returns:
                   15913: 
                   15914: 1. suffix obtained (numeric)
                   15915: 
                   15916: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15917: 
                   15918: 3. error: contains (localized) error message if an error occurred.
                   15919: 
1.747     albertel 15920: 
1.608     albertel 15921: =back
                   15922: 
1.243     albertel 15923: =head2 HTTP Helper Routines
                   15924: 
                   15925: =over 4
                   15926: 
1.191     harris41 15927: =item *
                   15928: 
                   15929: escape() : unpack non-word characters into CGI-compatible hex codes
                   15930: 
                   15931: =item *
                   15932: 
                   15933: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15934: 
1.243     albertel 15935: =back
                   15936: 
                   15937: =head1 PRIVATE SUBROUTINES
                   15938: 
                   15939: =head2 Underlying communication routines (Shouldn't call)
                   15940: 
                   15941: =over 4
                   15942: 
                   15943: =item *
                   15944: 
                   15945: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15946: 
                   15947: =item *
                   15948: 
                   15949: reply() : uses subreply to send a message to remote machine, logs all failures
                   15950: 
                   15951: =item *
                   15952: 
                   15953: critical() : passes a critical message to another server; if cannot
                   15954: get through then place message in connection buffer directory and
                   15955: returns con_delayed, if incapable of saving message, returns
                   15956: con_failed
                   15957: 
                   15958: =item *
                   15959: 
                   15960: reconlonc() : tries to reconnect lonc client processes.
                   15961: 
                   15962: =back
                   15963: 
                   15964: =head2 Resource Access Logging
                   15965: 
                   15966: =over 4
                   15967: 
                   15968: =item *
                   15969: 
                   15970: flushcourselogs() : flush (save) buffer logs and access logs
                   15971: 
                   15972: =item *
                   15973: 
                   15974: courselog($what) : save message for course in hash
                   15975: 
                   15976: =item *
                   15977: 
                   15978: courseacclog($what) : save message for course using &courselog().  Perform
                   15979: special processing for specific resource types (problems, exams, quizzes, etc).
                   15980: 
1.191     harris41 15981: =item *
                   15982: 
                   15983: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15984: as a PerlChildExitHandler
1.243     albertel 15985: 
                   15986: =back
                   15987: 
                   15988: =head2 Other
                   15989: 
                   15990: =over 4
                   15991: 
                   15992: =item *
                   15993: 
                   15994: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15995: 
                   15996: =back
                   15997: 
                   15998: =cut
1.877     foxr     15999: 

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