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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1391  ! raeburn     4: # $Id: lonnet.pm,v 1.1390 2018/11/25 02:27:04 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.486     www        74: use HTTP::Date;
1.977     amueller   75: use Image::Magick;
1.1389    raeburn    76: use CGI::Cookie;
1.1182    foxr       77: 
1.1173    foxr       78: use Encode;
                     79: 
1.1245    raeburn    80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     82:             %managerstab);
1.871     albertel   83: 
                     84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        87:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        88: 
1.1       albertel   89: use IO::Socket;
1.31      www        90: use GDBM_File;
1.208     albertel   91: use HTML::LCParser;
1.88      www        92: use Fcntl qw(:flock);
1.870     albertel   93: use Storable qw(thaw nfreeze);
1.1289    damieng    94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   95: use Cache::Memcached;
1.676     albertel   96: use Digest::MD5;
1.790     albertel   97: use Math::Random;
1.1024    raeburn    98: use File::MMagic;
1.807     albertel   99: use LONCAPA qw(:DEFAULT :match);
1.740     www       100: use LONCAPA::Configuration;
1.1160    www       101: use LONCAPA::lonmetadata;
1.1167    droeschl  102: use LONCAPA::Lond;
1.1345    raeburn   103: use LONCAPA::LWPReq;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
1.1359    raeburn   149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.1359    raeburn   161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.1359    raeburn   174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.1315    raeburn   232: sub get_servercerts_info {
1.1383    raeburn   233:     my ($lonhost,$hostname,$context) = @_;
                    234:     return if ($lonhost eq '');
                    235:     if ($hostname eq '') {
                    236:         $hostname = &hostname($lonhost);
                    237:     }
                    238:     return if ($hostname eq '');
1.1315    raeburn   239:     my ($rep,$uselocal);
1.1388    raeburn   240:     if ($context eq 'install') {
1.1387    raeburn   241:         $uselocal = 1;
                    242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   243:         $uselocal = 1;
                    244:     }
1.1387    raeburn   245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   247:         if ($distro eq '') {
                    248:             $uselocal = 0;
                    249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   250:             if ($1 < 6) {
                    251:                 $uselocal = 0;
                    252:             }
1.1346    raeburn   253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    254:             if ($1 < 12) {
                    255:                 $uselocal = 0;
                    256:             }
1.1315    raeburn   257:         }
                    258:     }
                    259:     if ($uselocal) {
1.1383    raeburn   260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   261:     } else {
                    262:         $rep=&reply('servercerts',$lonhost);
                    263:     }
                    264:     my ($result,%returnhash);
                    265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    266:         ($rep eq 'unknown_cmd')) {
                    267:         $result = $rep;
                    268:     } else {
                    269:         $result = 'ok';
                    270:         my @pairs=split(/\&/,$rep);
                    271:         foreach my $item (@pairs) {
                    272:             my ($key,$value)=split(/=/,$item,2);
                    273:             my $what = &unescape($key);
                    274:             $returnhash{$what}=&thaw_unescape($value);
                    275:         }
                    276:     }
                    277:     return ($result,\%returnhash);
                    278: }
                    279: 
1.993     raeburn   280: sub get_server_loncaparev {
1.1073    raeburn   281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   282:     if (defined($lonhost)) {
                    283:         if (!defined(&hostname($lonhost))) {
                    284:             undef($lonhost);
                    285:         }
                    286:     }
                    287:     if (!defined($lonhost)) {
                    288:         if (defined(&domain($dom,'primary'))) {
                    289:             $lonhost=&domain($dom,'primary');
                    290:             if ($lonhost eq 'no_host') {
                    291:                 undef($lonhost);
                    292:             }
                    293:         }
                    294:     }
                    295:     if (defined($lonhost)) {
1.1073    raeburn   296:         my $cachetime = 12*3600;
                    297:         if (!$ignore_cache) {
                    298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    299:             if (defined($cached)) {
                    300:                 return $loncaparev;
                    301:             }
                    302:         }
                    303:         my ($answer,$loncaparev);
                    304:         my @ids=&current_machine_ids();
                    305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    306:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   308:                 $loncaparev = $1;
                    309:             }
                    310:         } else {
                    311:             $answer = &reply('serverloncaparev',$lonhost);
                    312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    313:                 if ($caller eq 'loncron') {
                    314:                     my $protocol = $protocol{$lonhost};
                    315:                     $protocol = 'http' if ($protocol ne 'https');
                    316:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    317:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   318:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   319:                     unless ($response->is_error()) {
                    320:                         my $content = $response->content;
1.1081    raeburn   321:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   322:                             $loncaparev = $1;
                    323:                         }
                    324:                     }
                    325:                 } else {
                    326:                     $loncaparev = $loncaparevs{$lonhost};
                    327:                 }
1.1081    raeburn   328:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   329:                 $loncaparev = $1;
                    330:             }
1.993     raeburn   331:         }
1.1073    raeburn   332:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   333:     }
                    334: }
                    335: 
1.1074    raeburn   336: sub get_server_homeID {
                    337:     my ($hostname,$ignore_cache,$caller) = @_;
                    338:     unless ($ignore_cache) {
                    339:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    340:         if (defined($cached)) {
                    341:             return $serverhomeID;
                    342:         }
                    343:     }
                    344:     my $cachetime = 12*3600;
                    345:     my $serverhomeID;
                    346:     if ($caller eq 'loncron') { 
                    347:         my @machine_ids = &machine_ids($hostname);
                    348:         foreach my $id (@machine_ids) {
                    349:             my $response = &reply('serverhomeID',$id);
                    350:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    351:                 $serverhomeID = $response;
                    352:                 last;
                    353:             }
                    354:         }
                    355:         if ($serverhomeID eq '') {
                    356:             $serverhomeID = $machine_ids[-1];
                    357:         }
                    358:     } else {
                    359:         $serverhomeID = $serverhomeIDs{$hostname};
                    360:     }
                    361:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    362: }
                    363: 
1.1121    raeburn   364: sub get_remote_globals {
                    365:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   366:     my ($result,%returnhash,%whatneeded);
                    367:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   368:         foreach my $what (sort(keys(%{$whathash}))) {
                    369:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   370:             my ($response,$cached);
1.1121    raeburn   371:             unless ($ignore_cache) {
1.1125    raeburn   372:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   373:             }
                    374:             if (defined($cached)) {
1.1125    raeburn   375:                 $returnhash{$what} = $response;
1.1121    raeburn   376:             } else {
1.1125    raeburn   377:                 $whatneeded{$what} = 1;
1.1121    raeburn   378:             }
                    379:         }
1.1125    raeburn   380:         if (keys(%whatneeded) == 0) {
                    381:             $result = 'ok';
                    382:         } else {
1.1121    raeburn   383:             my $requested = &freeze_escape(\%whatneeded);
                    384:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   385:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    386:                 ($rep eq 'unknown_cmd')) {
                    387:                 $result = $rep;
                    388:             } else {
                    389:                 $result = 'ok';
1.1121    raeburn   390:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   391:                 foreach my $item (@pairs) {
                    392:                     my ($key,$value)=split(/=/,$item,2);
                    393:                     my $what = &unescape($key);
                    394:                     my $hashid = $lonhost.'-'.$what;
                    395:                     $returnhash{$what}=&thaw_unescape($value);
                    396:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   397:                 }
                    398:             }
                    399:         }
                    400:     }
1.1125    raeburn   401:     return ($result,\%returnhash);
1.1121    raeburn   402: }
                    403: 
1.1124    raeburn   404: sub remote_devalidate_cache {
1.1241    raeburn   405:     my ($lonhost,$cachekeys) = @_;
                    406:     my $items;
                    407:     return unless (ref($cachekeys) eq 'ARRAY');
                    408:     my $cachestr = join('&',@{$cachekeys});
                    409:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   410:     return $response;
                    411: }
                    412: 
1.1       albertel  413: # -------------------------------------------------- Non-critical communication
                    414: sub subreply {
                    415:     my ($cmd,$server)=@_;
1.838     albertel  416:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      417:     #
                    418:     #  With loncnew process trimming, there's a timing hole between lonc server
                    419:     #  process exit and the master server picking up the listen on the AF_UNIX
                    420:     #  socket.  In that time interval, a lock file will exist:
                    421: 
                    422:     my $lockfile=$peerfile.".lock";
                    423:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   424: 	sleep(0.1);
1.549     foxr      425:     }
                    426:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      427:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      428:     #
1.550     foxr      429:     #   We'll give the connection a few tries before abandoning it.  If
                    430:     #   connection is not possible, we'll con_lost back to the client.
                    431:     #   
                    432:     my $client;
                    433:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    434: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    435: 				      Type    => SOCK_STREAM,
                    436: 				      Timeout => 10);
1.869     albertel  437: 	if ($client) {
1.550     foxr      438: 	    last;		# Connected!
1.850     albertel  439: 	} else {
1.853     albertel  440: 	    &create_connection(&hostname($server),$server);
1.550     foxr      441: 	}
1.1289    damieng   442:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      443:     }
                    444:     my $answer;
                    445:     if ($client) {
1.704     albertel  446: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      447: 	$answer=<$client>;
                    448: 	if (!$answer) { $answer="con_lost"; }
                    449: 	chomp($answer);
                    450:     } else {
                    451: 	$answer = 'con_lost';	# Failed connection.
                    452:     }
1.1       albertel  453:     return $answer;
                    454: }
                    455: 
                    456: sub reply {
                    457:     my ($cmd,$server)=@_;
1.838     albertel  458:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  459:     my $answer=subreply($cmd,$server);
1.65      www       460:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  461:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       462:                 " $cmd to $server returned $answer</font>");
                    463:     }
1.1       albertel  464:     return $answer;
                    465: }
                    466: 
                    467: # ----------------------------------------------------------- Send USR1 to lonc
                    468: 
                    469: sub reconlonc {
1.891     albertel  470:     my ($lonid) = @_;
                    471:     if ($lonid) {
1.1295    raeburn   472:         my $hostname = &hostname($lonid);
1.891     albertel  473: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    474: 	if ($hostname && -e $peerfile) {
                    475: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    476: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    477: 					     Type    => SOCK_STREAM,
                    478: 					     Timeout => 10);
                    479: 	    if ($client) {
                    480: 		print $client ("reset_retries\n");
                    481: 		my $answer=<$client>;
                    482: 		#reset just this one.
                    483: 	    }
                    484: 	}
                    485: 	return;
                    486:     }
                    487: 
1.836     www       488:     &logthis("Trying to reconnect lonc");
1.1       albertel  489:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   490:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  491: 	my $loncpid=<$fh>;
                    492:         chomp($loncpid);
                    493:         if (kill 0 => $loncpid) {
                    494: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    495:             kill USR1 => $loncpid;
                    496:             sleep 1;
1.1295    raeburn   497:         } else {
1.12      www       498: 	    &logthis(
1.672     albertel  499:                "<font color=\"blue\">WARNING:".
1.12      www       500:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  501:         }
                    502:     } else {
1.836     www       503: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  504:     }
                    505: }
                    506: 
                    507: # ------------------------------------------------------ Critical communication
1.12      www       508: 
1.1       albertel  509: sub critical {
                    510:     my ($cmd,$server)=@_;
1.838     albertel  511:     unless (&hostname($server)) {
1.672     albertel  512:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       513:                " Critical message to unknown server ($server)</font>");
                    514:         return 'no_such_host';
                    515:     }
1.1       albertel  516:     my $answer=reply($cmd,$server);
                    517:     if ($answer eq 'con_lost') {
1.1295    raeburn   518: 	&reconlonc($server);
1.589     albertel  519: 	my $answer=reply($cmd,$server);
1.1       albertel  520:         if ($answer eq 'con_lost') {
                    521:             my $now=time;
                    522:             my $middlename=$cmd;
1.5       www       523:             $middlename=substr($middlename,0,16);
1.1       albertel  524:             $middlename=~s/\W//g;
                    525:             my $dfilename=
1.305     www       526:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    527:             $dumpcount++;
1.1       albertel  528:             {
1.448     albertel  529: 		my $dfh;
1.1359    raeburn   530: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  531: 		    print $dfh "$cmd\n"; 
                    532: 		    close($dfh);
                    533: 		}
1.1       albertel  534:             }
1.1288    damieng   535:             sleep 1;
1.1       albertel  536:             my $wcmd='';
                    537:             {
1.448     albertel  538: 		my $dfh;
1.1359    raeburn   539: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  540: 		    $wcmd=<$dfh>; 
                    541: 		    close($dfh);
                    542: 		}
1.1       albertel  543:             }
                    544:             chomp($wcmd);
1.7       www       545:             if ($wcmd eq $cmd) {
1.672     albertel  546: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       547:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  548:                 &logperm("D:$server:$cmd");
                    549: 	        return 'con_delayed';
                    550:             } else {
1.672     albertel  551:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       552:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  553:                 &logperm("F:$server:$cmd");
                    554:                 return 'con_failed';
                    555:             }
                    556:         }
                    557:     }
                    558:     return $answer;
1.405     albertel  559: }
                    560: 
1.755     albertel  561: # ------------------------------------------- check if return value is an error
                    562: 
                    563: sub error {
                    564:     my ($result) = @_;
1.756     albertel  565:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  566: 	if ($2 == 2) { return undef; }
                    567: 	return $1;
                    568:     }
                    569:     return undef;
                    570: }
                    571: 
1.783     albertel  572: sub convert_and_load_session_env {
                    573:     my ($lonidsdir,$handle)=@_;
                    574:     my @profile;
                    575:     {
1.917     albertel  576: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    577: 	if (!$opened) {
1.915     albertel  578: 	    return 0;
                    579: 	}
1.783     albertel  580: 	flock($idf,LOCK_SH);
                    581: 	@profile=<$idf>;
                    582: 	close($idf);
                    583:     }
                    584:     my %temp_env;
                    585:     foreach my $line (@profile) {
1.786     albertel  586: 	if ($line !~ m/=/) {
                    587: 	    return 0;
                    588: 	}
1.783     albertel  589: 	chomp($line);
                    590: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    591: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    592:     }
                    593:     unlink("$lonidsdir/$handle.id");
                    594:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    595: 	    0640)) {
                    596: 	%disk_env = %temp_env;
                    597: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    598: 	untie(%disk_env);
                    599:     }
1.786     albertel  600:     return 1;
1.783     albertel  601: }
                    602: 
1.374     www       603: # ------------------------------------------- Transfer profile into environment
1.780     albertel  604: my $env_loaded;
                    605: sub transfer_profile_to_env {
1.788     albertel  606:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    607:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       608: 
1.720     albertel  609:     if (!defined($lonidsdir)) {
                    610: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    611:     }
                    612:     if (!defined($handle)) {
                    613:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    614:     }
                    615: 
1.786     albertel  616:     my $convert;
                    617:     {
1.917     albertel  618:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    619: 	if (!$opened) {
1.915     albertel  620: 	    return;
                    621: 	}
1.786     albertel  622: 	flock($idf,LOCK_SH);
                    623: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    624: 		&GDBM_READER(),0640)) {
                    625: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    626: 	    untie(%disk_env);
                    627: 	} else {
                    628: 	    $convert = 1;
                    629: 	}
                    630:     }
                    631:     if ($convert) {
                    632: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    633: 	    &logthis("Failed to load session, or convert session.");
                    634: 	}
1.374     www       635:     }
1.783     albertel  636: 
1.786     albertel  637:     my %remove;
1.783     albertel  638:     while ( my $envname = each(%env) ) {
1.433     matthew   639:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    640:             if ($time < time-300) {
1.783     albertel  641:                 $remove{$key}++;
1.433     matthew   642:             }
                    643:         }
                    644:     }
1.783     albertel  645: 
1.619     albertel  646:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  647:     $env_loaded=1;
1.783     albertel  648:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   649:         &delenv($expired_key);
1.374     www       650:     }
1.1       albertel  651: }
                    652: 
1.916     albertel  653: # ---------------------------------------------------- Check for valid session 
                    654: sub check_for_valid_session {
1.1355    raeburn   655:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  656:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   657:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    658:     if ($name eq 'lonDAV') {
                    659:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    660:     } else {
                    661:         $lonidsdir=$r->dir_config('lonIDsDir');
                    662:         if ($name eq '') {
                    663:             $name = 'lonID';
                    664:         }
                    665:     }
                    666:     if ($name eq 'lonID') {
                    667:         $secure = 'lonSID';
1.1337    raeburn   668:         $linkname = 'lonLinkID';
                    669:         $pubname = 'lonPubID';
1.1378    raeburn   670:         if (exists($cookies{$secure})) {
                    671:             $lonid=$cookies{$secure};
                    672:         } elsif (exists($cookies{$name})) {
                    673:             $lonid=$cookies{$name};
                    674:         } elsif (exists($cookies{$linkname})) {
1.1337    raeburn   675:             $lonid=$cookies{$linkname};
1.1378    raeburn   676:         } elsif (exists($cookies{$pubname})) {
                    677:             $lonid=$cookies{$pubname};
1.1337    raeburn   678:         }
1.1378    raeburn   679:     } else {
                    680:         $lonid=$cookies{$name};
1.1337    raeburn   681:     }
1.916     albertel  682:     return undef if (!$lonid);
                    683: 
                    684:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   685:     if (-l "$lonidsdir/$handle.id") {
                    686:         my $link = readlink("$lonidsdir/$handle.id");
                    687:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    688:             $handle = $1;
                    689:         }
1.1155    raeburn   690:     }
1.1355    raeburn   691:     if (!-e "$lonidsdir/$handle.id") {
                    692:         if ((ref($domref)) && ($name eq 'lonID') && 
                    693:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    694:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    695:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    696:                 $$domref = $possudom;
                    697:             }
                    698:         }
                    699:         return undef;
                    700:     }
1.916     albertel  701: 
1.917     albertel  702:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    703:     return undef if (!$opened);
1.916     albertel  704: 
                    705:     flock($idf,LOCK_SH);
                    706:     my %disk_env;
                    707:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    708: 	    &GDBM_READER(),0640)) {
                    709: 	return undef;	
                    710:     }
                    711: 
                    712:     if (!defined($disk_env{'user.name'})
                    713: 	|| !defined($disk_env{'user.domain'})) {
                    714: 	return undef;
                    715:     }
1.1245    raeburn   716: 
                    717:     if (ref($userhashref) eq 'HASH') {
                    718:         $userhashref->{'name'} = $disk_env{'user.name'};
                    719:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   720:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   721:         if ($userhashref->{'lti'}) {
                    722:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    723:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    724:         }
1.1212    raeburn   725:     }
1.1245    raeburn   726: 
1.916     albertel  727:     return $handle;
                    728: }
                    729: 
1.830     albertel  730: sub timed_flock {
                    731:     my ($file,$lock_type) = @_;
                    732:     my $failed=0;
                    733:     eval {
                    734: 	local $SIG{__DIE__}='DEFAULT';
                    735: 	local $SIG{ALRM}=sub {
                    736: 	    $failed=1;
                    737: 	    die("failed lock");
                    738: 	};
                    739: 	alarm(13);
                    740: 	flock($file,$lock_type);
                    741: 	alarm(0);
                    742:     };
                    743:     if ($failed) {
                    744: 	return undef;
                    745:     } else {
                    746: 	return 1;
                    747:     }
                    748: }
                    749: 
1.5       www       750: # ---------------------------------------------------------- Append Environment
                    751: 
                    752: sub appenv {
1.949     raeburn   753:     my ($newenv,$roles) = @_;
                    754:     if (ref($newenv) eq 'HASH') {
                    755:         foreach my $key (keys(%{$newenv})) {
                    756:             my $refused = 0;
                    757: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    758:                 $refused = 1;
                    759:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   760:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   761:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    762:                         $refused = 0;
                    763:                     }
                    764:                 }
                    765:             }
                    766:             if ($refused) {
                    767:                 &logthis("<font color=\"blue\">WARNING: ".
                    768:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    769:                          .'</font>');
                    770: 	        delete($newenv->{$key});
                    771:             } else {
                    772:                 $env{$key}=$newenv->{$key};
                    773:             }
                    774:         }
1.1376    raeburn   775:         my $lonids = $perlvar{'lonIDsDir'};
                    776:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    777:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    778:             if ($opened
                    779: 	        && &timed_flock($env_file,LOCK_EX)
                    780: 	        &&
                    781: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    782: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    783: 	        while (my ($key,$value) = each(%{$newenv})) {
                    784: 	            $disk_env{$key} = $value;
                    785: 	        }
                    786: 	        untie(%disk_env);
                    787:             }
1.35      www       788:         }
1.191     harris41  789:     }
1.56      www       790:     return 'ok';
                    791: }
                    792: # ----------------------------------------------------- Delete from Environment
                    793: 
                    794: sub delenv {
1.1104    raeburn   795:     my ($delthis,$regexp,$roles) = @_;
                    796:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    797:         my $refused = 1;
                    798:         if (ref($roles) eq 'ARRAY') {
                    799:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    800:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    801:                 $refused = 0;
                    802:             }
                    803:         }
                    804:         if ($refused) {
                    805:             &logthis("<font color=\"blue\">WARNING: ".
                    806:                      "Attempt to delete from environment ".$delthis);
                    807:             return 'error';
                    808:         }
1.56      www       809:     }
1.917     albertel  810:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    811:     if ($opened
1.915     albertel  812: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  813: 	&&
                    814: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    815: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  816: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   817: 	    if ($regexp) {
                    818:                 if ($key=~/^$delthis/) {
                    819:                     delete($env{$key});
                    820:                     delete($disk_env{$key});
                    821:                 } 
                    822:             } else {
                    823:                 if ($key=~/^\Q$delthis\E/) {
                    824: 		    delete($env{$key});
                    825: 		    delete($disk_env{$key});
                    826: 	        }
                    827:             }
1.448     albertel  828: 	}
1.783     albertel  829: 	untie(%disk_env);
1.5       www       830:     }
                    831:     return 'ok';
1.369     albertel  832: }
                    833: 
1.790     albertel  834: sub get_env_multiple {
                    835:     my ($name) = @_;
                    836:     my @values;
                    837:     if (defined($env{$name})) {
                    838:         # exists is it an array
                    839:         if (ref($env{$name})) {
                    840:             @values=@{ $env{$name} };
                    841:         } else {
                    842:             $values[0]=$env{$name};
                    843:         }
                    844:     }
                    845:     return(@values);
                    846: }
                    847: 
1.958     www       848: # ------------------------------------------------------------------- Locking
                    849: 
                    850: sub set_lock {
                    851:     my ($text)=@_;
                    852:     $locknum++;
                    853:     my $id=$$.'-'.$locknum;
                    854:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    855:              'session.lock.'.$id => $text});
                    856:     return $id;
                    857: }
                    858: 
                    859: sub get_locks {
                    860:     my $num=0;
                    861:     my %texts=();
                    862:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    863:        if ($lock=~/\w/) {
                    864:           $num++;
                    865:           $texts{$lock}=$env{'session.lock.'.$lock};
                    866:        }
                    867:    }
                    868:    return ($num,%texts);
                    869: }
                    870: 
                    871: sub remove_lock {
                    872:     my ($id)=@_;
                    873:     my $newlocks='';
                    874:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    875:        if (($lock=~/\w/) && ($lock ne $id)) {
                    876:           $newlocks.=','.$lock;
                    877:        }
                    878:     }
                    879:     &appenv({'session.locks' => $newlocks});
                    880:     &delenv('session.lock.'.$id);
                    881: }
                    882: 
                    883: sub remove_all_locks {
                    884:     my $activelocks=$env{'session.locks'};
                    885:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    886:        if ($lock=~/\w/) {
                    887:           &remove_lock($lock);
                    888:        }
                    889:     }
                    890: }
                    891: 
                    892: 
1.369     albertel  893: # ------------------------------------------ Find out current server userload
                    894: sub userload {
                    895:     my $numusers=0;
                    896:     {
                    897: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    898: 	my $filename;
                    899: 	my $curtime=time;
                    900: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  901: 	    next if ($filename eq '.' || $filename eq '..');
                    902: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   903:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  904: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  905: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  906: 	}
                    907: 	closedir(LONIDS);
                    908:     }
                    909:     my $userloadpercent=0;
                    910:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    911:     if ($maxuserload) {
1.371     albertel  912: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  913:     }
1.372     albertel  914:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  915:     return $userloadpercent;
1.283     www       916: }
                    917: 
1.1       albertel  918: # ------------------------------ Find server with least workload from spare.tab
1.11      www       919: 
1.1       albertel  920: sub spareserver {
1.1083    raeburn   921:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  922:     my $spare_server;
1.370     albertel  923:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  924:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    925:                                                      :  $userloadpercent;
1.1083    raeburn   926:     my ($uint_dom,$remotesessions);
                    927:     if (($udom ne '') && (&domain($udom) ne '')) {
                    928:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    929:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    930:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    931:         $remotesessions = $udomdefaults{'remotesessions'};
                    932:     }
1.1123    raeburn   933:     my $spareshash = &this_host_spares($udom);
                    934:     if (ref($spareshash) eq 'HASH') {
                    935:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    936:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   937:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    938:                                              $try_server));
1.1123    raeburn   939: 	        ($spare_server, $lowest_load) =
                    940: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    941:             }
1.1083    raeburn   942:         }
1.784     albertel  943: 
1.1123    raeburn   944:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    945: 
                    946:         if (!$found_server) {
                    947:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    948: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   949:                     next unless (&spare_can_host($udom,$uint_dom,
                    950:                                                  $remotesessions,$try_server));
1.1123    raeburn   951: 	            ($spare_server, $lowest_load) =
                    952: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    953:                 }
                    954: 	    }
                    955:         }
1.784     albertel  956:     }
                    957: 
                    958:     if (!$want_server_name) {
1.968     raeburn   959:         my $protocol = 'http';
                    960:         if ($protocol{$spare_server} eq 'https') {
                    961:             $protocol = $protocol{$spare_server};
                    962:         }
1.1001    raeburn   963:         if (defined($spare_server)) {
                    964:             my $hostname = &hostname($spare_server);
1.1083    raeburn   965:             if (defined($hostname)) {
1.1001    raeburn   966: 	        $spare_server = $protocol.'://'.$hostname;
                    967:             }
                    968:         }
1.784     albertel  969:     }
                    970:     return $spare_server;
                    971: }
                    972: 
                    973: sub compare_server_load {
1.1253    raeburn   974:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    975: 
                    976:     if ($required) {
                    977:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    978:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    979:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    980:         if (($major eq '' && $minor eq '') ||
                    981:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    982:             return ($spare_server,$lowest_load);
                    983:         }
                    984:     }
1.784     albertel  985: 
                    986:     my $loadans     = &reply('load',    $try_server);
                    987:     my $userloadans = &reply('userload',$try_server);
                    988: 
                    989:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   990: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  991:     }
                    992: 
                    993:     my $load;
                    994:     if ($loadans =~ /\d/) {
                    995: 	if ($userloadans =~ /\d/) {
                    996: 	    #both are numbers, pick the bigger one
                    997: 	    $load = ($loadans > $userloadans) ? $loadans 
                    998: 		                              : $userloadans;
1.411     albertel  999: 	} else {
1.784     albertel 1000: 	    $load = $loadans;
1.411     albertel 1001: 	}
1.784     albertel 1002:     } else {
                   1003: 	$load = $userloadans;
                   1004:     }
                   1005: 
                   1006:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1007: 	$spare_server = $try_server;
                   1008: 	$lowest_load  = $load;
1.370     albertel 1009:     }
1.784     albertel 1010:     return ($spare_server,$lowest_load);
1.202     matthew  1011: }
1.914     albertel 1012: 
                   1013: # --------------------------- ask offload servers if user already has a session
                   1014: sub find_existing_session {
                   1015:     my ($udom,$uname) = @_;
1.1123    raeburn  1016:     my $spareshash = &this_host_spares($udom);
                   1017:     if (ref($spareshash) eq 'HASH') {
                   1018:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1019:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1020:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1021:             }
                   1022:         }
                   1023:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1024:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1025:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1026:             }
                   1027:         }
1.914     albertel 1028:     }
                   1029:     return;
                   1030: }
                   1031: 
1.1389    raeburn  1032: # check if user's browser sent load balancer cookie and server still has session
                   1033: # and is not overloaded.
                   1034: sub check_for_balancer_cookie {
                   1035:     my ($r,$update_mtime) = @_;
                   1036:     my ($otherserver,$cookie);
                   1037:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1038:     if (exists($cookies{'balanceID'})) {
                   1039:         my $balid = $cookies{'balanceID'};
                   1040:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1041:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1042:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1043:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1044:                 my ($possudom,$possuname) = ($1,$2);
                   1045:                 my $has_session = 0;
                   1046:                 if ((&domain($possudom) ne '') &&
                   1047:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1048:                     my $try_server;
                   1049:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1050:                     if ($opened) {
                   1051:                         flock($idf,LOCK_SH);
                   1052:                         while (my $line = <$idf>) {
                   1053:                             chomp($line);
                   1054:                             if (&hostname($line) ne '') {
                   1055:                                 $try_server = $line;
                   1056:                                 last;
                   1057:                             }
                   1058:                         }
                   1059:                         close($idf);
                   1060:                         if (($try_server) &&
                   1061:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1062:                             my $lowest_load = 30000;
                   1063:                             ($otherserver,$lowest_load) =
                   1064:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1065:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1066:                                 $has_session = 1;
                   1067:                             } else {
                   1068:                                 undef($otherserver);
                   1069:                             }
                   1070:                         }
                   1071:                     }
                   1072:                 }
                   1073:                 if ($has_session) {
                   1074:                     if ($update_mtime) {
                   1075:                         my $atime = my $mtime = time;
                   1076:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1077:                     }
                   1078:                 } else {
                   1079:                     unlink("$balancedir/$cookie.id");
                   1080:                 }
                   1081:             }
                   1082:         }
                   1083:     }
                   1084:     return ($otherserver,$cookie);
                   1085: }
                   1086: 
                   1087: sub delbalcookie {
                   1088:     my ($cookie,$balancer) =@_;
                   1089:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1090:         my ($udom,$uname) = ($1,$2);
                   1091:         my $uprimary_id = &domain($udom,'primary');
                   1092:         my $uintdom = &internet_dom($uprimary_id);
                   1093:         my $intdom = &internet_dom($balancer);
                   1094:         my $serverhomedom = &host_domain($balancer);
                   1095:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1096:             return &reply("delbalcookie:$cookie",$balancer);
                   1097:         }
                   1098:     }
                   1099: }
                   1100: 
1.914     albertel 1101: # -------------------------------- ask if server already has a session for user
                   1102: sub has_user_session {
                   1103:     my ($lonid,$udom,$uname) = @_;
                   1104:     my $result = &reply(join(':','userhassession',
                   1105: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1106:     return 1 if ($result eq 'ok');
                   1107: 
                   1108:     return 0;
                   1109: }
                   1110: 
1.1076    raeburn  1111: # --------- determine least loaded server in a user's domain which allows login
                   1112: 
                   1113: sub choose_server {
1.1259    raeburn  1114:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1115:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1116:     my %servers = &get_servers($udom);
1.1076    raeburn  1117:     my $lowest_load = 30000;
1.1259    raeburn  1118:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1119:     if ($skiploadbal) {
                   1120:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1121:         unless (defined($cached)) {
                   1122:             my $cachetime = 60*60*24;
                   1123:             my %domconfig =
                   1124:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1125:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1126:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1127:                                            $cachetime);
                   1128:             }
                   1129:         }
                   1130:     }
1.1076    raeburn  1131:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1132:         if ($skiploadbal) {
                   1133:             if (ref($balancers) eq 'HASH') {
                   1134:                 next if (exists($balancers->{$lonhost}));
                   1135:             }
1.1389    raeburn  1136:         }
1.1115    raeburn  1137:         my $loginvia;
                   1138:         if ($checkloginvia) {
                   1139:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1140:             if ($loginvia) {
                   1141:                 my ($server,$path) = split(/:/,$loginvia);
                   1142:                 ($login_host, $lowest_load) =
1.1253    raeburn  1143:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1144:                 if ($login_host eq $server) {
                   1145:                     $portal_path = $path;
1.1151    raeburn  1146:                     $isredirect = 1;
1.1116    raeburn  1147:                 }
                   1148:             } else {
                   1149:                 ($login_host, $lowest_load) =
1.1253    raeburn  1150:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1151:                 if ($login_host eq $lonhost) {
                   1152:                     $portal_path = '';
1.1151    raeburn  1153:                     $isredirect = ''; 
1.1116    raeburn  1154:                 }
                   1155:             }
                   1156:         } else {
1.1076    raeburn  1157:             ($login_host, $lowest_load) =
1.1253    raeburn  1158:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1159:         }
                   1160:     }
                   1161:     if ($login_host ne '') {
1.1116    raeburn  1162:         $hostname = &hostname($login_host);
1.1076    raeburn  1163:     }
1.1331    raeburn  1164:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1165: }
                   1166: 
1.202     matthew  1167: # --------------------------------------------- Try to change a user's password
                   1168: 
                   1169: sub changepass {
1.799     raeburn  1170:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1171:     $currentpass = &escape($currentpass);
                   1172:     $newpass     = &escape($newpass);
1.1030    raeburn  1173:     my $lonhost = $perlvar{'lonHostID'};
                   1174:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1175: 		       $server);
                   1176:     if (! $answer) {
                   1177: 	&logthis("No reply on password change request to $server ".
                   1178: 		 "by $uname in domain $udom.");
                   1179:     } elsif ($answer =~ "^ok") {
                   1180:         &logthis("$uname in $udom successfully changed their password ".
                   1181: 		 "on $server.");
                   1182:     } elsif ($answer =~ "^pwchange_failure") {
                   1183: 	&logthis("$uname in $udom was unable to change their password ".
                   1184: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1185: 		 "or pwchange");
                   1186:     } elsif ($answer =~ "^non_authorized") {
                   1187:         &logthis("$uname in $udom did not get their password correct when ".
                   1188: 		 "attempting to change it on $server.");
                   1189:     } elsif ($answer =~ "^auth_mode_error") {
                   1190:         &logthis("$uname in $udom attempted to change their password despite ".
                   1191: 		 "not being locally or internally authenticated on $server.");
                   1192:     } elsif ($answer =~ "^unknown_user") {
                   1193:         &logthis("$uname in $udom attempted to change their password ".
                   1194: 		 "on $server but were unable to because $server is not ".
                   1195: 		 "their home server.");
                   1196:     } elsif ($answer =~ "^refused") {
                   1197: 	&logthis("$server refused to change $uname in $udom password because ".
                   1198: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1199:     } elsif ($answer =~ "invalid_client") {
                   1200:         &logthis("$server refused to change $uname in $udom password because ".
                   1201:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1202:     }
                   1203:     return $answer;
1.1       albertel 1204: }
                   1205: 
1.169     harris41 1206: # ----------------------- Try to determine user's current authentication scheme
                   1207: 
                   1208: sub queryauthenticate {
                   1209:     my ($uname,$udom)=@_;
1.456     albertel 1210:     my $uhome=&homeserver($uname,$udom);
                   1211:     if (!$uhome) {
                   1212: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1213: 	return 'no_host';
                   1214:     }
                   1215:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1216:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1217: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1218:     }
1.456     albertel 1219:     return $answer;
1.169     harris41 1220: }
                   1221: 
1.1       albertel 1222: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1223: 
1.1       albertel 1224: sub authenticate {
1.1073    raeburn  1225:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1226:     $upass=&escape($upass);
                   1227:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1228:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1229:     my $newhome;
1.836     www      1230:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1231: # Maybe the machine was offline and only re-appeared again recently?
                   1232:         &reconlonc();
                   1233: # One more
1.952     raeburn  1234: 	$uhome=&homeserver($uname,$udom,1);
                   1235:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1236:             if (defined(&domain($udom,'primary'))) {
                   1237:                 $newhome=&domain($udom,'primary');
                   1238:             }
                   1239:             if ($newhome ne '') {
                   1240:                 $uhome = $newhome;
                   1241:             }
                   1242:         }
1.836     www      1243: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1244: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1245: 	    return 'no_host';
                   1246:         }
1.1       albertel 1247:     }
1.1073    raeburn  1248:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1249:     if ($answer eq 'authorized') {
1.952     raeburn  1250:         if ($newhome) {
                   1251:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1252:             return 'no_account_on_host'; 
                   1253:         } else {
                   1254:             &logthis("User $uname at $udom authorized by $uhome");
                   1255:             return $uhome;
                   1256:         }
1.471     albertel 1257:     }
                   1258:     if ($answer eq 'non_authorized') {
                   1259: 	&logthis("User $uname at $udom rejected by $uhome");
                   1260: 	return 'no_host'; 
1.9       www      1261:     }
1.471     albertel 1262:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1263:     return 'no_host';
                   1264: }
                   1265: 
1.1073    raeburn  1266: sub can_host_session {
1.1074    raeburn  1267:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1268:     my $canhost = 1;
1.1074    raeburn  1269:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1270:     if (ref($remotesessions) eq 'HASH') {
                   1271:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1272:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1273:                 $canhost = 0;
                   1274:             } else {
                   1275:                 $canhost = 1;
                   1276:             }
                   1277:         }
                   1278:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1279:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1280:                 $canhost = 1;
                   1281:             } else {
                   1282:                 $canhost = 0;
                   1283:             }
                   1284:         }
                   1285:         if ($canhost) {
                   1286:             if ($remotesessions->{'version'} ne '') {
                   1287:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1288:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1289:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1290:                         my $major = $1;
                   1291:                         my $minor = $2;
                   1292:                         if (($major < $reqmajor ) ||
                   1293:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1294:                             $canhost = 0;
                   1295:                         }
                   1296:                     } else {
                   1297:                         $canhost = 0;
                   1298:                     }
                   1299:                 }
                   1300:             }
                   1301:         }
                   1302:     }
                   1303:     if ($canhost) {
                   1304:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1305:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1306:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1307:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1308:                 if (($uint_dom ne '') && 
                   1309:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1310:                     $canhost = 0;
                   1311:                 } else {
                   1312:                     $canhost = 1;
                   1313:                 }
                   1314:             }
                   1315:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1316:                 if (($uint_dom ne '') && 
                   1317:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1318:                     $canhost = 1;
                   1319:                 } else {
                   1320:                     $canhost = 0;
                   1321:                 }
                   1322:             }
                   1323:         }
                   1324:     }
                   1325:     return $canhost;
                   1326: }
                   1327: 
1.1083    raeburn  1328: sub spare_can_host {
                   1329:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1330:     my $canhost=1;
1.1279    raeburn  1331:     my $try_server_hostname = &hostname($try_server);
                   1332:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1333:     my $serverhomedom = &host_domain($serverhomeID);
                   1334:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1335:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1336:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1337:             $canhost = 0;
                   1338:         }
                   1339:     }
                   1340:     if (($canhost) && ($uint_dom)) {
                   1341:         my @intdoms;
                   1342:         my $internet_names = &get_internet_names($try_server);
                   1343:         if (ref($internet_names) eq 'ARRAY') {
                   1344:             @intdoms = @{$internet_names};
                   1345:         }
                   1346:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1347:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1348:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1349:                                          $remotesessions,
                   1350:                                          $defdomdefaults{'hostedsessions'});
                   1351:         }
1.1083    raeburn  1352:     }
                   1353:     return $canhost;
                   1354: }
                   1355: 
1.1123    raeburn  1356: sub this_host_spares {
                   1357:     my ($dom) = @_;
1.1126    raeburn  1358:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1359:     my @hosts = &current_machine_ids();
                   1360:     foreach my $lonhost (@hosts) {
                   1361:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1362:             $dom_in_use = $dom;
                   1363:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1364:             last;
                   1365:         }
                   1366:     }
1.1126    raeburn  1367:     if ($dom_in_use ne '') {
                   1368:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1369:     }
                   1370:     if (ref($result) ne 'HASH') {
                   1371:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1372:         $dom_in_use = &host_domain($lonhost_in_use);
                   1373:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1374:         if (ref($result) ne 'HASH') {
                   1375:             $result = \%spareid;
                   1376:         }
                   1377:     }
                   1378:     return $result;
                   1379: }
                   1380: 
                   1381: sub spares_for_offload  {
                   1382:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1383:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1384:     if (defined($cached)) {
                   1385:         return $result;
                   1386:     } else {
1.1126    raeburn  1387:         my $cachetime = 60*60*24;
                   1388:         my %domconfig =
                   1389:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1390:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1391:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1392:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1393:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1394:                 }
                   1395:             }
                   1396:         }
                   1397:     }
1.1126    raeburn  1398:     return;
1.1123    raeburn  1399: }
                   1400: 
1.1129    raeburn  1401: sub get_lonbalancer_config {
                   1402:     my ($servers) = @_;
                   1403:     my ($currbalancer,$currtargets);
                   1404:     if (ref($servers) eq 'HASH') {
                   1405:         foreach my $server (keys(%{$servers})) {
                   1406:             my %what = (
                   1407:                          spareid => 1,
                   1408:                          perlvar => 1,
                   1409:                        );
                   1410:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1411:             if ($result eq 'ok') {
                   1412:                 if (ref($returnhash) eq 'HASH') {
                   1413:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1414:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1415:                             $currbalancer = $server;
                   1416:                             $currtargets = {};
                   1417:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1418:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1419:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1420:                                 }
                   1421:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1422:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1423:                                 }
                   1424:                             }
                   1425:                             last;
                   1426:                         }
                   1427:                     }
                   1428:                 }
                   1429:             }
                   1430:         }
                   1431:     }
                   1432:     return ($currbalancer,$currtargets);
                   1433: }
                   1434: 
                   1435: sub check_loadbalancing {
1.1331    raeburn  1436:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1437:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391  ! raeburn  1438:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1439:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1440:     my @hosts = &current_machine_ids();
1.1129    raeburn  1441:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1442:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1443:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1444:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1445:     my $domneedscache;
1.1129    raeburn  1446:     my $cachetime = 60*60*24;
                   1447: 
                   1448:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1449:         $dom_in_use = $udom;
                   1450:         $homeintdom = 1;
                   1451:     } else {
                   1452:         $dom_in_use = $serverhomedom;
                   1453:     }
                   1454:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1455:     unless (defined($cached)) {
                   1456:         my %domconfig =
                   1457:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1458:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1459:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1460:         } else {
                   1461:             $domneedscache = $dom_in_use;
1.1129    raeburn  1462:         }
                   1463:     }
                   1464:     if (ref($result) eq 'HASH') {
1.1391  ! raeburn  1465:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1466:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1467:         if ($is_balancer) {
                   1468:             if (ref($currrules) eq 'HASH') {
                   1469:                 if ($homeintdom) {
                   1470:                     if ($uname ne '') {
                   1471:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1472:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1473:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1474:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1475:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1476:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1477:                             }
                   1478:                         }
                   1479:                         if ($rule_in_effect eq '') {
                   1480:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1481:                             if ($userenv{'inststatus'} ne '') {
                   1482:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1483:                                 my ($othertitle,$usertypes,$types) =
                   1484:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1485:                                 if (ref($types) eq 'ARRAY') {
                   1486:                                     foreach my $type (@{$types}) {
                   1487:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1488:                                             if (exists($currrules->{$type})) {
                   1489:                                                 $rule_in_effect = $currrules->{$type};
                   1490:                                             }
                   1491:                                         }
                   1492:                                     }
                   1493:                                 }
                   1494:                             } else {
                   1495:                                 if (exists($currrules->{'default'})) {
                   1496:                                     $rule_in_effect = $currrules->{'default'};
                   1497:                                 }
                   1498:                             }
                   1499:                         }
                   1500:                     } else {
                   1501:                         if (exists($currrules->{'default'})) {
                   1502:                             $rule_in_effect = $currrules->{'default'};
                   1503:                         }
                   1504:                     }
                   1505:                 } else {
                   1506:                     if ($currrules->{'_LC_external'} ne '') {
                   1507:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1508:                     }
                   1509:                 }
                   1510:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1511:                                                        $uname,$udom);
                   1512:             }
                   1513:         }
                   1514:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1515:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1516:         unless (defined($cached)) {
                   1517:             my %domconfig =
                   1518:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1519:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1520:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1521:             } else {
                   1522:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1523:             }
                   1524:         }
                   1525:         if (ref($result) eq 'HASH') {
1.1391  ! raeburn  1526:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1527:                 &check_balancer_result($result,@hosts);
                   1528:             if ($is_balancer) {
1.1129    raeburn  1529:                 if (ref($currrules) eq 'HASH') {
                   1530:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1531:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1532:                     }
                   1533:                 }
                   1534:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1535:                                                        $uname,$udom);
                   1536:             }
                   1537:         } else {
                   1538:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1539:                 $is_balancer = 1;
                   1540:                 $offloadto = &this_host_spares($dom_in_use);
                   1541:             }
1.1307    raeburn  1542:             unless (defined($cached)) {
                   1543:                 $domneedscache = $serverhomedom;
                   1544:             }
1.1129    raeburn  1545:         }
                   1546:     } else {
                   1547:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1548:             $is_balancer = 1;
                   1549:             $offloadto = &this_host_spares($dom_in_use);
                   1550:         }
1.1307    raeburn  1551:         unless (defined($cached)) {
                   1552:             $domneedscache = $serverhomedom;
                   1553:         }
                   1554:     }
                   1555:     if ($domneedscache) {
                   1556:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1557:     }
1.1176    raeburn  1558:     if ($is_balancer) {
                   1559:         my $lowest_load = 30000;
                   1560:         if (ref($offloadto) eq 'HASH') {
                   1561:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1562:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1563:                     ($otherserver,$lowest_load) =
                   1564:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1565:                 }
1.1129    raeburn  1566:             }
1.1176    raeburn  1567:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1568: 
1.1176    raeburn  1569:             if (!$found_server) {
                   1570:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1571:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1572:                         ($otherserver,$lowest_load) =
                   1573:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1574:                     }
                   1575:                 }
                   1576:             }
                   1577:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1578:             if (@{$offloadto} == 1) {
                   1579:                 $otherserver = $offloadto->[0];
                   1580:             } elsif (@{$offloadto} > 1) {
                   1581:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1582:                     ($otherserver,$lowest_load) =
                   1583:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1584:                 }
                   1585:             }
                   1586:         }
1.1331    raeburn  1587:         unless ($caller eq 'login') {
                   1588:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1589:                 $is_balancer = 0;
                   1590:                 if ($uname ne '' && $udom ne '') {
                   1591:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1592:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1593:                                  'user.loadbalcheck.time' => time});
                   1594:                     }
1.1176    raeburn  1595:                 }
1.1129    raeburn  1596:             }
                   1597:         }
1.1389    raeburn  1598:         unless ($homeintdom) {
                   1599:             undef($setcookie);
                   1600:         }
1.1129    raeburn  1601:     }
1.1391  ! raeburn  1602:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1603: }
                   1604: 
1.1191    raeburn  1605: sub check_balancer_result {
                   1606:     my ($result,@hosts) = @_;
1.1391  ! raeburn  1607:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1608:     if (ref($result) eq 'HASH') {
                   1609:         if ($result->{'lonhost'} ne '') {
                   1610:             my $currbalancer = $result->{'lonhost'};
                   1611:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1612:                 $is_balancer = 1;
                   1613:                 $currtargets = $result->{'targets'};
                   1614:                 $currrules = $result->{'rules'};
1.1391  ! raeburn  1615:                 $dom_balancers = $currbalancer;
1.1191    raeburn  1616:             }
1.1391  ! raeburn  1617:             $dom_balancers = $currbalancer;
1.1191    raeburn  1618:         } else {
1.1391  ! raeburn  1619:             if (keys(%{$result})) {
        !          1620:                 foreach my $key (keys(%{$result})) {
        !          1621:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
        !          1622:                         (ref($result->{$key}) eq 'HASH')) {
        !          1623:                         $is_balancer = 1;
        !          1624:                         $currrules = $result->{$key}{'rules'};
        !          1625:                         $currtargets = $result->{$key}{'targets'};
        !          1626:                         $setcookie = $result->{$key}{'cookie'};
        !          1627:                         last;
        !          1628:                     }
1.1191    raeburn  1629:                 }
1.1391  ! raeburn  1630:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1631:             }
                   1632:         }
                   1633:     }
1.1391  ! raeburn  1634:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1635: }
                   1636: 
1.1129    raeburn  1637: sub get_loadbalancer_targets {
                   1638:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1639:     my $offloadto;
1.1175    raeburn  1640:     if ($rule_in_effect eq 'none') {
                   1641:         return [$perlvar{'lonHostID'}];
                   1642:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1643:         $offloadto = $currtargets;
                   1644:     } else {
                   1645:         if ($rule_in_effect eq 'homeserver') {
                   1646:             my $homeserver = &homeserver($uname,$udom);
                   1647:             if ($homeserver ne 'no_host') {
                   1648:                 $offloadto = [$homeserver];
                   1649:             }
                   1650:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1651:             my %domconfig =
                   1652:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1653:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1654:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1655:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1656:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1657:                     }
                   1658:                 }
                   1659:             } else {
1.1178    raeburn  1660:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1661:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1662:                 if (&hostname($remotebalancer) ne '') {
                   1663:                     $offloadto = [$remotebalancer];
                   1664:                 }
                   1665:             }
                   1666:         } elsif (&hostname($rule_in_effect) ne '') {
                   1667:             $offloadto = [$rule_in_effect];
                   1668:         }
                   1669:     }
                   1670:     return $offloadto;
                   1671: }
                   1672: 
1.1127    raeburn  1673: sub internet_dom_servers {
                   1674:     my ($dom) = @_;
                   1675:     my (%uniqservers,%servers);
                   1676:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1677:     my @machinedoms = &machine_domains($primaryserver);
                   1678:     foreach my $mdom (@machinedoms) {
                   1679:         my %currservers = %servers;
                   1680:         my %server = &get_servers($mdom);
                   1681:         %servers = (%currservers,%server);
                   1682:     }
                   1683:     my %by_hostname;
                   1684:     foreach my $id (keys(%servers)) {
                   1685:         push(@{$by_hostname{$servers{$id}}},$id);
                   1686:     }
                   1687:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1688:         if (@{$by_hostname{$hostname}} > 1) {
                   1689:             my $match = 0;
                   1690:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1691:                 if (&host_domain($id) eq $dom) {
                   1692:                     $uniqservers{$id} = $hostname;
                   1693:                     $match = 1;
                   1694:                 }
                   1695:             }
                   1696:             unless ($match) {
                   1697:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1698:             }
                   1699:         } else {
                   1700:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1701:         }
                   1702:     }
                   1703:     return %uniqservers;
                   1704: }
                   1705: 
1.1347    raeburn  1706: sub trusted_domains {
                   1707:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1708:     my ($trusted,$untrusted);
1.1347    raeburn  1709:     if (&domain($calldom) eq '') {
1.1349    raeburn  1710:         return ($trusted,$untrusted);
1.1347    raeburn  1711:     }
                   1712:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1713:         return ($trusted,$untrusted);
1.1347    raeburn  1714:     }
                   1715:     my $callprimary = &domain($calldom,'primary');
                   1716:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1717:     if ($intcalldom eq '') {
1.1349    raeburn  1718:         return ($trusted,$untrusted);
1.1347    raeburn  1719:     }
                   1720: 
                   1721:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1722:     unless (defined($cached)) {
                   1723:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1724:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1725:         $trustconfig = $domconfig{'trust'};
                   1726:     }
                   1727:     if (ref($trustconfig)) {
                   1728:         my (%possexc,%possinc,@allexc,@allinc); 
                   1729:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1730:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1731:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1732:             }
                   1733:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1734:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1735:             }
                   1736:         }
                   1737:         if (keys(%possexc)) {
                   1738:             if (keys(%possinc)) {
                   1739:                 foreach my $key (sort(keys(%possexc))) {
                   1740:                     next if ($key eq $intcalldom);
                   1741:                     unless ($possinc{$key}) {
                   1742:                         push(@allexc,$key);
                   1743:                     }
                   1744:                 }
                   1745:             } else {
                   1746:                 @allexc = sort(keys(%possexc));
                   1747:             }
                   1748:         }
                   1749:         if (keys(%possinc)) {
                   1750:             $possinc{$intcalldom} = 1;
                   1751:             @allinc = sort(keys(%possinc));
                   1752:         }
                   1753:         if ((@allexc > 0) || (@allinc > 0)) {
                   1754:             my %doms_by_intdom;
                   1755:             my %allintdoms = &all_host_intdom();
                   1756:             my %alldoms = &all_host_domain();
                   1757:             foreach my $key (%allintdoms) {
                   1758:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1759:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1760:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1761:                     }
                   1762:                 } else {
                   1763:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1764:                 }
                   1765:             }
                   1766:             foreach my $exc (@allexc) {
                   1767:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349    raeburn  1768:                     $untrusted = $doms_by_intdom{$exc};
1.1347    raeburn  1769:                 }
                   1770:             }
                   1771:             foreach my $inc (@allinc) {
                   1772:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349    raeburn  1773:                     $trusted = $doms_by_intdom{$inc};
1.1347    raeburn  1774:                 }
                   1775:             }
                   1776:         }
                   1777:     }
1.1349    raeburn  1778:     return ($trusted,$untrusted);
1.1347    raeburn  1779: }
                   1780: 
                   1781: sub will_trust {
                   1782:     my ($cmdtype,$domain,$possdom) = @_;
                   1783:     return 1 if ($domain eq $possdom);
                   1784:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1785:     my $willtrust; 
                   1786:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1787:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1788:             $willtrust = 1;
                   1789:         }
                   1790:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1791:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1792:             $willtrust = 1;
                   1793:         }
                   1794:     } else {
                   1795:         $willtrust = 1;
                   1796:     }
                   1797:     return $willtrust;
                   1798: }
                   1799: 
1.1       albertel 1800: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1801: 
1.599     albertel 1802: my %homecache;
1.1       albertel 1803: sub homeserver {
1.230     stredwic 1804:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1805:     my $index="$uname:$udom";
1.426     albertel 1806: 
1.599     albertel 1807:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1808: 
                   1809:     my %servers = &get_servers($udom,'library');
                   1810:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1811:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1812: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1813: 
                   1814: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1815: 	if ($answer eq 'found') {
                   1816: 	    delete($badServerCache{$tryserver}); 
                   1817: 	    return $homecache{$index}=$tryserver;
                   1818: 	} elsif ($answer eq 'no_host') {
                   1819: 	    $badServerCache{$tryserver}=1;
                   1820: 	}
1.1       albertel 1821:     }    
                   1822:     return 'no_host';
1.70      www      1823: }
                   1824: 
1.1300    raeburn  1825: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1826: 
                   1827: sub idget {
1.1300    raeburn  1828:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1829:     my %returnhash=();
1.1300    raeburn  1830:     my @ids=(); 
                   1831:     if (ref($idsref) eq 'ARRAY') {
                   1832:         @ids = @{$idsref};
                   1833:     } else {
                   1834:         return %returnhash; 
                   1835:     }
                   1836:     if ($namespace eq '') {
                   1837:         $namespace = 'ids';
                   1838:     }
1.70      www      1839:     
1.841     albertel 1840:     my %servers = &get_servers($udom,'library');
                   1841:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1842: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1843: 	if ($namespace eq 'ids') {
                   1844: 	    $idlist=~tr/A-Z/a-z/;
                   1845: 	}
                   1846: 	my $reply;
                   1847: 	if ($namespace eq 'ids') {
                   1848: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1849: 	} else {
                   1850: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1851: 	}
1.841     albertel 1852: 	my @answer=();
                   1853: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1854: 	    @answer=split(/\&/,$reply);
                   1855: 	}                    ;
                   1856: 	my $i;
                   1857: 	for ($i=0;$i<=$#ids;$i++) {
                   1858: 	    if ($answer[$i]) {
1.1299    raeburn  1859: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1860: 	    }
1.841     albertel 1861: 	}
1.1300    raeburn  1862:     }
1.70      www      1863:     return %returnhash;
                   1864: }
                   1865: 
                   1866: # ------------------------------------- Find the IDs behind a list of usernames
                   1867: 
                   1868: sub idrget {
                   1869:     my ($udom,@unames)=@_;
                   1870:     my %returnhash=();
1.800     albertel 1871:     foreach my $uname (@unames) {
                   1872:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1873:     }
1.70      www      1874:     return %returnhash;
                   1875: }
                   1876: 
1.1300    raeburn  1877: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1878: 
                   1879: sub idput {
1.1300    raeburn  1880:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1881:     my %servers=();
1.1300    raeburn  1882:     my %ids=();
                   1883:     my %byid = ();
                   1884:     if (ref($idsref) eq 'HASH') {
                   1885:         %ids=%{$idsref};
                   1886:     }
                   1887:     if ($namespace eq '') {
                   1888:         $namespace = 'ids'; 
                   1889:     }
1.800     albertel 1890:     foreach my $uname (keys(%ids)) {
                   1891: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1892:         if ($uhom eq '') {
                   1893:             $uhom=&homeserver($uname,$udom);
                   1894:         }
1.70      www      1895:         if ($uhom ne 'no_host') {
1.800     albertel 1896:             my $esc_unam=&escape($uname);
1.1300    raeburn  1897:             if ($namespace eq 'ids') {
                   1898:                 my $id=&escape($ids{$uname});
                   1899:                 $id=~tr/A-Z/a-z/;
                   1900:                 my $esc_unam=&escape($uname);
                   1901:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1902:             } else {
1.1300    raeburn  1903:                 my @currids = split(/,/,$ids{$uname});
                   1904:                 foreach my $id (@currids) {
                   1905:                     $byid{$uhom}{$id} .= $uname.',';
                   1906:                 }
                   1907:             }
                   1908:         }
                   1909:     }
                   1910:     if ($namespace eq 'clickers') {
                   1911:         foreach my $server (keys(%byid)) {
                   1912:             if (ref($byid{$server}) eq 'HASH') {
                   1913:                 foreach my $id (keys(%{$byid{$server}})) {
                   1914:                     $byid{$server} =~ s/,$//;
                   1915:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1916:                 }
1.70      www      1917:             }
                   1918:         }
1.191     harris41 1919:     }
1.800     albertel 1920:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1921:         $servers{$server} =~ s/\&$//;
                   1922:         if ($namespace eq 'ids') {     
                   1923:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1924:         } else {
                   1925:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1926:         }
1.191     harris41 1927:     }
1.344     www      1928: }
                   1929: 
1.1300    raeburn  1930: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1931: 
                   1932: sub iddel {
1.1300    raeburn  1933:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1934:     my %result=();
1.1300    raeburn  1935:     my %ids=();
                   1936:     my %byid = ();
                   1937:     if (ref($idshashref) eq 'HASH') {
                   1938:         %ids=%{$idshashref};
                   1939:     } else {
1.1231    raeburn  1940:         return %result;
                   1941:     }
1.1300    raeburn  1942:     if ($namespace eq '') {
                   1943:         $namespace = 'ids';
                   1944:     }
1.1231    raeburn  1945:     my %servers=();
1.1300    raeburn  1946:     while (my ($id,$unamestr) = each(%ids)) {
                   1947:         if ($namespace eq 'ids') {
                   1948:             my $uhom = $uhome;
                   1949:             if ($uhom eq '') { 
                   1950:                 $uhom=&homeserver($unamestr,$udom);
                   1951:             }
                   1952:             if ($uhom ne 'no_host') {
                   1953:                 $servers{$uhom}.='&'.&escape($id);
                   1954:             }
                   1955:          } else {
                   1956:             my @curritems = split(/,/,$ids{$id});
                   1957:             foreach my $uname (@curritems) {
                   1958:                 my $uhom = $uhome;
                   1959:                 if ($uhom eq '') {
                   1960:                     $uhom=&homeserver($uname,$udom);
                   1961:                 }
                   1962:                 if ($uhom ne 'no_host') { 
                   1963:                     $byid{$uhom}{$id} .= $uname.',';
                   1964:                 }
                   1965:             }
1.1231    raeburn  1966:         }
1.1300    raeburn  1967:     }
                   1968:     if ($namespace eq 'clickers') {
                   1969:         foreach my $server (keys(%byid)) {
                   1970:             if (ref($byid{$server}) eq 'HASH') {
                   1971:                 foreach my $id (keys(%{$byid{$server}})) {
                   1972:                     $byid{$server}{$id} =~ s/,$//;
                   1973:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1974:                 }
1.1231    raeburn  1975:             }
                   1976:         }
                   1977:     }
                   1978:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1979:         $servers{$server} =~ s/\&$//;
                   1980:         if ($namespace eq 'ids') {
                   1981:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1982:         } elsif ($namespace eq 'clickers') {
                   1983:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1984:         }
1.1231    raeburn  1985:     }
                   1986:     return %result;
                   1987: }
                   1988: 
1.1300    raeburn  1989: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1990: 
                   1991: sub updateclickers {
                   1992:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1993:     my %clickers;
                   1994:     if (ref($idshashref) eq 'HASH') {
                   1995:         %clickers=%{$idshashref};
                   1996:     } else {
                   1997:         return;
                   1998:     }
                   1999:     my $items='';
                   2000:     foreach my $item (keys(%clickers)) {
                   2001:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2002:     }
                   2003:     $items=~s/\&$//;
                   2004:     my $request = "updateclickers:$udom:$action:$items";
                   2005:     if ($critical) {
                   2006:         return &critical($request,$uhome);
                   2007:     } else {
                   2008:         return &reply($request,$uhome);
                   2009:     }
                   2010: }
                   2011: 
1.1023    raeburn  2012: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2013: sub dump_dom {
1.1165    droeschl 2014:     my ($namespace, $udom, $regexp) = @_;
                   2015: 
                   2016:     $udom ||= $env{'user.domain'};
                   2017: 
                   2018:     return () unless $udom;
                   2019: 
                   2020:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2021: }
                   2022: 
1.1023    raeburn  2023: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2024: 
                   2025: sub get_dom {
1.860     raeburn  2026:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2027:     return if ($udom eq 'public');
1.806     raeburn  2028:     my $items='';
                   2029:     foreach my $item (@$storearr) {
                   2030:         $items.=&escape($item).'&';
                   2031:     }
                   2032:     $items=~s/\&$//;
1.860     raeburn  2033:     if (!$udom) {
                   2034:         $udom=$env{'user.domain'};
1.1267    raeburn  2035:         return if ($udom eq 'public');
1.860     raeburn  2036:         if (defined(&domain($udom,'primary'))) {
                   2037:             $uhome=&domain($udom,'primary');
                   2038:         } else {
1.874     albertel 2039:             undef($uhome);
1.860     raeburn  2040:         }
                   2041:     } else {
                   2042:         if (!$uhome) {
                   2043:             if (defined(&domain($udom,'primary'))) {
                   2044:                 $uhome=&domain($udom,'primary');
                   2045:             }
                   2046:         }
                   2047:     }
                   2048:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2049:         my $rep;
                   2050:         if ($namespace =~ /^enc/) {
                   2051:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2052:         } else {
                   2053:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2054:         }
1.866     raeburn  2055:         my %returnhash;
1.875     albertel 2056:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2057:             return %returnhash;
                   2058:         }
1.806     raeburn  2059:         my @pairs=split(/\&/,$rep);
                   2060:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2061:             return @pairs;
                   2062:         }
                   2063:         my $i=0;
                   2064:         foreach my $item (@$storearr) {
                   2065:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2066:             $i++;
                   2067:         }
                   2068:         return %returnhash;
                   2069:     } else {
1.880     banghart 2070:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2071:     }
                   2072: }
                   2073: 
                   2074: # -------------------------------------------- put items in domain db files 
                   2075: 
                   2076: sub put_dom {
1.860     raeburn  2077:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2078:     if (!$udom) {
                   2079:         $udom=$env{'user.domain'};
                   2080:         if (defined(&domain($udom,'primary'))) {
                   2081:             $uhome=&domain($udom,'primary');
                   2082:         } else {
1.874     albertel 2083:             undef($uhome);
1.860     raeburn  2084:         }
                   2085:     } else {
                   2086:         if (!$uhome) {
                   2087:             if (defined(&domain($udom,'primary'))) {
                   2088:                 $uhome=&domain($udom,'primary');
                   2089:             }
                   2090:         }
                   2091:     } 
                   2092:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2093:         my $items='';
                   2094:         foreach my $item (keys(%$storehash)) {
                   2095:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2096:         }
                   2097:         $items=~s/\&$//;
1.1344    raeburn  2098:         if ($namespace =~ /^enc/) {
                   2099:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2100:         } else {
                   2101:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2102:         }
1.806     raeburn  2103:     } else {
1.860     raeburn  2104:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2105:     }
                   2106: }
                   2107: 
1.1023    raeburn  2108: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2109: sub newput_dom {
1.1023    raeburn  2110:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2111:     my $result;
                   2112:     if (!$udom) {
                   2113:         $udom=$env{'user.domain'};
                   2114:     }
1.1023    raeburn  2115:     if ($udom) {
                   2116:         my $uname = &get_domainconfiguser($udom);
                   2117:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2118:     }
                   2119:     return $result;
                   2120: }
                   2121: 
1.1023    raeburn  2122: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2123: sub del_dom {
1.1023    raeburn  2124:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2125:     if (ref($storearr) eq 'ARRAY') {
                   2126:         if (!$udom) {
                   2127:             $udom=$env{'user.domain'};
                   2128:         }
1.1023    raeburn  2129:         if ($udom) {
                   2130:             my $uname = &get_domainconfiguser($udom); 
                   2131:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2132:         }
                   2133:     }
                   2134: }
                   2135: 
1.1023    raeburn  2136: # ----------------------------------construct domainconfig user for a domain 
                   2137: sub get_domainconfiguser {
                   2138:     my ($udom) = @_;
                   2139:     return $udom.'-domainconfig';
                   2140: }
                   2141: 
1.837     raeburn  2142: sub retrieve_inst_usertypes {
                   2143:     my ($udom) = @_;
                   2144:     my (%returnhash,@order);
1.989     raeburn  2145:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2146:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2147:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2148:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2149:     } else {
                   2150:         if (defined(&domain($udom,'primary'))) {
                   2151:             my $uhome=&domain($udom,'primary');
                   2152:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2153:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2154:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2155:                 return (\%returnhash,\@order);
                   2156:             }
                   2157:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2158:             my @pairs=split(/\&/,$hashitems);
                   2159:             foreach my $item (@pairs) {
                   2160:                 my ($key,$value)=split(/=/,$item,2);
                   2161:                 $key = &unescape($key);
                   2162:                 next if ($key =~ /^error: 2 /);
                   2163:                 $returnhash{$key}=&thaw_unescape($value);
                   2164:             }
                   2165:             my @esc_order = split(/\&/,$orderitems);
                   2166:             foreach my $item (@esc_order) {
                   2167:                 push(@order,&unescape($item));
                   2168:             }
                   2169:         } else {
1.1256    raeburn  2170:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2171:         }
1.1256    raeburn  2172:         return (\%returnhash,\@order);
1.837     raeburn  2173:     }
                   2174: }
                   2175: 
1.868     raeburn  2176: sub is_domainimage {
                   2177:     my ($url) = @_;
1.1306    raeburn  2178:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2179:         if (&domain($1) ne '') {
                   2180:             return '1';
                   2181:         }
                   2182:     }
                   2183:     return;
                   2184: }
                   2185: 
1.899     raeburn  2186: sub inst_directory_query {
                   2187:     my ($srch) = @_;
                   2188:     my $udom = $srch->{'srchdomain'};
                   2189:     my %results;
                   2190:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2191:     my $outcome;
1.899     raeburn  2192:     if ($homeserver ne '') {
1.1357    raeburn  2193:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2194:             if ($srch->{'srchby'} eq 'email') {
                   2195:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2196:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2197:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2198:                     (($major == 2) && ($minor < 12))) {
                   2199:                     return;
                   2200:                 }
                   2201:             }
                   2202:         }
1.904     albertel 2203: 	my $queryid=&reply("querysend:instdirsearch:".
                   2204: 			   &escape($srch->{'srchby'}).':'.
                   2205: 			   &escape($srch->{'srchterm'}).':'.
                   2206: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2207: 	my $host=&hostname($homeserver);
                   2208: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2209: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2210: 	    return;
                   2211: 	}
                   2212: 	my $response = &get_query_reply($queryid);
                   2213: 	my $maxtries = 5;
                   2214: 	my $tries = 1;
                   2215: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2216: 	    $response = &get_query_reply($queryid);
                   2217: 	    $tries ++;
                   2218: 	}
                   2219: 
                   2220:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2221:             if ($response eq 'unavailable') {
                   2222:                 $outcome = $response;
                   2223:             } else {
                   2224:                 $outcome = 'ok';
                   2225:                 my @matches = split(/\n/,$response);
                   2226:                 foreach my $match (@matches) {
                   2227:                     my ($key,$value) = split(/=/,$match);
                   2228:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2229:                 }
1.899     raeburn  2230:             }
                   2231:         }
                   2232:     }
1.909     raeburn  2233:     return ($outcome,%results);
1.899     raeburn  2234: }
                   2235: 
                   2236: sub usersearch {
                   2237:     my ($srch) = @_;
                   2238:     my $dom = $srch->{'srchdomain'};
                   2239:     my %results;
                   2240:     my %libserv = &all_library();
                   2241:     my $query = 'usersearch';
                   2242:     foreach my $tryserver (keys(%libserv)) {
                   2243:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2244:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2245:                 if ($srch->{'srchby'} eq 'email') {
                   2246:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2247:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2248:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2249:                              (($major == 2) && ($minor < 12)));
                   2250:                 }
                   2251:             }
1.899     raeburn  2252:             my $host=&hostname($tryserver);
                   2253:             my $queryid=
1.911     raeburn  2254:                 &reply("querysend:".&escape($query).':'.
                   2255:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2256:                        &escape($srch->{'srchtype'}).':'.
                   2257:                        &escape($srch->{'srchterm'}),$tryserver);
                   2258:             if ($queryid !~/^\Q$host\E\_/) {
                   2259:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2260:                 next;
1.899     raeburn  2261:             }
                   2262:             my $reply = &get_query_reply($queryid);
                   2263:             my $maxtries = 1;
                   2264:             my $tries = 1;
                   2265:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2266:                 $reply = &get_query_reply($queryid);
                   2267:                 $tries ++;
                   2268:             }
                   2269:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2270:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2271:             } else {
1.911     raeburn  2272:                 my @matches;
                   2273:                 if ($reply =~ /\n/) {
                   2274:                     @matches = split(/\n/,$reply);
                   2275:                 } else {
                   2276:                     @matches = split(/\&/,$reply);
                   2277:                 }
1.899     raeburn  2278:                 foreach my $match (@matches) {
                   2279:                     my ($uname,$udom,%userhash);
1.911     raeburn  2280:                     foreach my $entry (split(/:/,$match)) {
                   2281:                         my ($key,$value) =
                   2282:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2283:                         $userhash{$key} = $value;
                   2284:                         if ($key eq 'username') {
                   2285:                             $uname = $value;
                   2286:                         } elsif ($key eq 'domain') {
                   2287:                             $udom = $value;
1.911     raeburn  2288:                         }
1.899     raeburn  2289:                     }
                   2290:                     $results{$uname.':'.$udom} = \%userhash;
                   2291:                 }
                   2292:             }
                   2293:         }
                   2294:     }
                   2295:     return %results;
                   2296: }
                   2297: 
1.912     raeburn  2298: sub get_instuser {
                   2299:     my ($udom,$uname,$id) = @_;
                   2300:     my $homeserver = &domain($udom,'primary');
                   2301:     my ($outcome,%results);
                   2302:     if ($homeserver ne '') {
                   2303:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2304:                            &escape($id).':'.&escape($udom),$homeserver);
                   2305:         my $host=&hostname($homeserver);
                   2306:         if ($queryid !~/^\Q$host\E\_/) {
                   2307:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2308:             return;
                   2309:         }
                   2310:         my $response = &get_query_reply($queryid);
                   2311:         my $maxtries = 5;
                   2312:         my $tries = 1;
                   2313:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2314:             $response = &get_query_reply($queryid);
                   2315:             $tries ++;
                   2316:         }
                   2317:         if (!&error($response) && $response ne 'refused') {
                   2318:             if ($response eq 'unavailable') {
                   2319:                 $outcome = $response;
                   2320:             } else {
                   2321:                 $outcome = 'ok';
                   2322:                 my @matches = split(/\n/,$response);
                   2323:                 foreach my $match (@matches) {
                   2324:                     my ($key,$value) = split(/=/,$match);
                   2325:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2326:                 }
                   2327:             }
                   2328:         }
                   2329:     }
                   2330:     my %userinfo;
                   2331:     if (ref($results{$uname}) eq 'HASH') {
                   2332:         %userinfo = %{$results{$uname}};
                   2333:     } 
                   2334:     return ($outcome,%userinfo);
                   2335: }
                   2336: 
1.1290    raeburn  2337: sub get_multiple_instusers {
                   2338:     my ($udom,$users,$caller) = @_;
                   2339:     my ($outcome,$results);
                   2340:     if (ref($users) eq 'HASH') {
                   2341:         my $count = keys(%{$users}); 
                   2342:         my $requested = &freeze_escape($users);
                   2343:         my $homeserver = &domain($udom,'primary');
                   2344:         if ($homeserver ne '') {
                   2345:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2346:             my $host=&hostname($homeserver);
                   2347:             if ($queryid !~/^\Q$host\E\_/) {
                   2348:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2349:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2350:                 return ($outcome,$results);
                   2351:             }
                   2352:             my $response = &get_query_reply($queryid);
                   2353:             my $maxtries = 5;
                   2354:             if ($count > 100) {
                   2355:                 $maxtries = 1+int($count/20);
                   2356:             }
                   2357:             my $tries = 1;
                   2358:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2359:                 $response = &get_query_reply($queryid);
                   2360:                 $tries ++;
                   2361:             }
                   2362:             if ($response eq '') {
                   2363:                 $results = {};
                   2364:                 foreach my $key (keys(%{$users})) {
                   2365:                     my ($uname,$id);
                   2366:                     if ($caller eq 'id') {
                   2367:                         $id = $key;
                   2368:                     } else {
                   2369:                         $uname = $key;
                   2370:                     }
                   2371:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2372:                     $outcome = $resp;
1.1290    raeburn  2373:                     if ($resp eq 'ok') {
                   2374:                         %{$results} = (%{$results}, %info);
                   2375:                     } else {
                   2376:                         last;
                   2377:                     }
                   2378:                 }
                   2379:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2380:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2381:                     $outcome = $response;
                   2382:                 } else {
1.1291    raeburn  2383:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2384:                     if ($outcome eq 'ok') {
                   2385:                         $results = &thaw_unescape($userdata); 
                   2386:                     }
                   2387:                 }
                   2388:             }
                   2389:         }
                   2390:     }
                   2391:     return ($outcome,$results);
                   2392: }
                   2393: 
1.912     raeburn  2394: sub inst_rulecheck {
1.923     raeburn  2395:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2396:     my %returnhash;
                   2397:     if ($udom ne '') {
                   2398:         if (ref($rules) eq 'ARRAY') {
                   2399:             @{$rules} = map {&escape($_);} (@{$rules});
                   2400:             my $rulestr = join(':',@{$rules});
                   2401:             my $homeserver=&domain($udom,'primary');
                   2402:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2403:                 my $response;
                   2404:                 if ($item eq 'username') {                
                   2405:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2406:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2407:                                               $homeserver));
1.923     raeburn  2408:                 } elsif ($item eq 'id') {
                   2409:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2410:                                               ':'.&escape($id).':'.$rulestr,
                   2411:                                               $homeserver));
1.945     raeburn  2412:                 } elsif ($item eq 'selfcreate') {
                   2413:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2414:                                                &escape($udom).':'.&escape($uname).
                   2415:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2416:                 }
1.912     raeburn  2417:                 if ($response ne 'refused') {
                   2418:                     my @pairs=split(/\&/,$response);
                   2419:                     foreach my $item (@pairs) {
                   2420:                         my ($key,$value)=split(/=/,$item,2);
                   2421:                         $key = &unescape($key);
                   2422:                         next if ($key =~ /^error: 2 /);
                   2423:                         $returnhash{$key}=&thaw_unescape($value);
                   2424:                     }
                   2425:                 }
                   2426:             }
                   2427:         }
                   2428:     }
                   2429:     return %returnhash;
                   2430: }
                   2431: 
                   2432: sub inst_userrules {
1.923     raeburn  2433:     my ($udom,$check) = @_;
1.912     raeburn  2434:     my (%ruleshash,@ruleorder);
                   2435:     if ($udom ne '') {
                   2436:         my $homeserver=&domain($udom,'primary');
                   2437:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2438:             my $response;
                   2439:             if ($check eq 'id') {
                   2440:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2441:                                  $homeserver);
1.943     raeburn  2442:             } elsif ($check eq 'email') {
                   2443:                 $response=&reply('instemailrules:'.&escape($udom),
                   2444:                                  $homeserver);
1.923     raeburn  2445:             } else {
                   2446:                 $response=&reply('instuserrules:'.&escape($udom),
                   2447:                                  $homeserver);
                   2448:             }
1.912     raeburn  2449:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2450:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2451:                 ($response ne 'no_such_host')) {
                   2452:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2453:                 my @pairs=split(/\&/,$hashitems);
                   2454:                 foreach my $item (@pairs) {
                   2455:                     my ($key,$value)=split(/=/,$item,2);
                   2456:                     $key = &unescape($key);
                   2457:                     next if ($key =~ /^error: 2 /);
                   2458:                     $ruleshash{$key}=&thaw_unescape($value);
                   2459:                 }
                   2460:                 my @esc_order = split(/\&/,$orderitems);
                   2461:                 foreach my $item (@esc_order) {
                   2462:                     push(@ruleorder,&unescape($item));
                   2463:                 }
                   2464:             }
                   2465:         }
                   2466:     }
                   2467:     return (\%ruleshash,\@ruleorder);
                   2468: }
                   2469: 
1.976     raeburn  2470: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2471: 
                   2472: sub get_domain_defaults {
1.1240    raeburn  2473:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2474:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2475:     my $cachetime = 60*60*24;
1.1240    raeburn  2476:     unless ($ignore_cache) {
                   2477:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2478:         if (defined($cached)) {
                   2479:             if (ref($result) eq 'HASH') {
                   2480:                 return %{$result};
                   2481:             }
1.943     raeburn  2482:         }
                   2483:     }
                   2484:     my %domdefaults;
                   2485:     my %domconfig =
1.989     raeburn  2486:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2487:                                   'requestcourses','inststatus',
1.1183    raeburn  2488:                                   'coursedefaults','usersessions',
1.1258    raeburn  2489:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2490:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2491:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2492:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2493:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2494:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2495:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2496:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2497:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2498:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2499:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2500:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2501:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2502:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2503:     } else {
                   2504:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2505:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2506:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2507:     }
1.976     raeburn  2508:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2509:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2510:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2511:         } else {
                   2512:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2513:         }
1.1177    raeburn  2514:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2515:         foreach my $item (@usertools) {
                   2516:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2517:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2518:             }
                   2519:         }
1.1229    raeburn  2520:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2521:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2522:         }
1.976     raeburn  2523:     }
1.985     raeburn  2524:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2525:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2526:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2527:         }
                   2528:     }
1.1183    raeburn  2529:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2530:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2531:     }
1.989     raeburn  2532:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2533:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2534:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2535:         }
                   2536:     }
1.1047    raeburn  2537:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2538:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2539:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2540:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2541:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2542:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2543:         }
1.1254    raeburn  2544:         foreach my $type (@coursetypes) {
                   2545:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2546:                 unless ($type eq 'community') {
                   2547:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2548:                 }
                   2549:             }
                   2550:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2551:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2552:             }
1.1277    raeburn  2553:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2554:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2555:                     $domdefaults{$type.'postsubtimeout'} = 
                   2556:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2557:                 }
                   2558:             }
1.1230    raeburn  2559:         }
1.1286    raeburn  2560:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2561:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2562:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2563:                 if (@clonecodes) {
                   2564:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2565:                 }
                   2566:             }
                   2567:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2568:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2569:         }
1.1356    raeburn  2570:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2571:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2572:         } 
1.1047    raeburn  2573:     }
1.1073    raeburn  2574:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2575:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2576:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2577:         }
                   2578:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2579:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2580:         }
1.1279    raeburn  2581:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2582:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2583:         }
1.1073    raeburn  2584:     }
1.1254    raeburn  2585:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2586:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2587:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2588:                             'approval','limit');
                   2589:             foreach my $type (@coursetypes) {
                   2590:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2591:                     my @mgrdc = ();
                   2592:                     foreach my $item (@settings) {
                   2593:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2594:                             push(@mgrdc,$item);
                   2595:                         }
                   2596:                     }
                   2597:                     if (@mgrdc) {
                   2598:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2599:                     }
                   2600:                 }
                   2601:             }
                   2602:         }
                   2603:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2604:             foreach my $type (@coursetypes) {
                   2605:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2606:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2607:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2608:                     }
                   2609:                 }
                   2610:             }
                   2611:         }
                   2612:     }
1.1258    raeburn  2613:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2614:         $domdefaults{'catauth'} = 'std';
                   2615:         $domdefaults{'catunauth'} = 'std';
                   2616:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2617:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2618:         }
                   2619:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2620:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2621:         }
                   2622:     }
1.1315    raeburn  2623:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2624:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2625:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2626:         }
1.1338    raeburn  2627:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2628:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2629:         }
                   2630:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2631:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2632:         }
                   2633:     }
1.1320    raeburn  2634:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2635:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2636:         foreach my $prefix (@prefixes) {
                   2637:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2638:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2639:             }
                   2640:         }
                   2641:     }
1.1314    raeburn  2642:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2643:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2644:     }
1.1332    raeburn  2645:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2646:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2647:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2648:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2649:         }
                   2650:     }
1.1219    raeburn  2651:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2652:     return %domdefaults;
                   2653: }
                   2654: 
1.1311    raeburn  2655: sub course_portal_url {
                   2656:     my ($cnum,$cdom) = @_;
                   2657:     my $chome = &homeserver($cnum,$cdom);
                   2658:     my $hostname = &hostname($chome);
                   2659:     my $protocol = $protocol{$chome};
                   2660:     $protocol = 'http' if ($protocol ne 'https');
                   2661:     my %domdefaults = &get_domain_defaults($cdom);
                   2662:     my $firsturl;
                   2663:     if ($domdefaults{'portal_def'}) {
                   2664:         $firsturl = $domdefaults{'portal_def'};
                   2665:     } else {
                   2666:         $firsturl = $protocol.'://'.$hostname;
                   2667:     }
                   2668:     return $firsturl;
                   2669: }
                   2670: 
1.344     www      2671: # --------------------------------------------------- Assign a key to a student
                   2672: 
                   2673: sub assign_access_key {
1.364     www      2674: #
                   2675: # a valid key looks like uname:udom#comments
                   2676: # comments are being appended
                   2677: #
1.498     www      2678:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2679:     $kdom=
1.620     albertel 2680:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2681:     $knum=
1.620     albertel 2682:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2683:     $cdom=
1.620     albertel 2684:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2685:     $cnum=
1.620     albertel 2686:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2687:     $udom=$env{'user.name'} unless (defined($udom));
                   2688:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2689:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2690:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2691:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2692:                                                   # assigned to this person
                   2693:                                                   # - this should not happen,
1.345     www      2694:                                                   # unless something went wrong
                   2695:                                                   # the first time around
                   2696: # ready to assign
1.364     www      2697:         $logentry=$1.'; '.$logentry;
1.496     www      2698:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2699:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2700: # key now belongs to user
1.346     www      2701: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2702:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2703:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2704:                 return 'ok';
                   2705:             } else {
                   2706:                 return 
                   2707:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2708: 	    }
                   2709:         } else {
                   2710:             return 'error: Could not assign key, try again later.';
                   2711:         }
1.364     www      2712:     } elsif (!$existing{$ckey}) {
1.345     www      2713: # the key does not exist
                   2714: 	return 'error: The key does not exist';
                   2715:     } else {
                   2716: # the key is somebody else's
                   2717: 	return 'error: The key is already in use';
                   2718:     }
1.344     www      2719: }
                   2720: 
1.364     www      2721: # ------------------------------------------ put an additional comment on a key
                   2722: 
                   2723: sub comment_access_key {
                   2724: #
                   2725: # a valid key looks like uname:udom#comments
                   2726: # comments are being appended
                   2727: #
                   2728:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2729:     $cdom=
1.620     albertel 2730:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2731:     $cnum=
1.620     albertel 2732:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2733:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2734:     if ($existing{$ckey}) {
                   2735:         $existing{$ckey}.='; '.$logentry;
                   2736: # ready to assign
1.367     www      2737:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2738:                                                  $cdom,$cnum) eq 'ok') {
                   2739: 	    return 'ok';
                   2740:         } else {
                   2741: 	    return 'error: Count not store comment.';
                   2742:         }
                   2743:     } else {
                   2744: # the key does not exist
                   2745: 	return 'error: The key does not exist';
                   2746:     }
                   2747: }
                   2748: 
1.344     www      2749: # ------------------------------------------------------ Generate a set of keys
                   2750: 
                   2751: sub generate_access_keys {
1.364     www      2752:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2753:     $cdom=
1.620     albertel 2754:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2755:     $cnum=
1.620     albertel 2756:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2757:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2758:     unless (($cdom) && ($cnum)) { return 0; }
                   2759:     if ($number>10000) { return 0; }
                   2760:     sleep(2); # make sure don't get same seed twice
                   2761:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2762:     my $total=0;
                   2763:     for (my $i=1;$i<=$number;$i++) {
                   2764:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2765:                   sprintf("%lx",int(100000*rand)).'-'.
                   2766:                   sprintf("%lx",int(100000*rand));
                   2767:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2768:        $newkey=~s/0/h/g; # and also 0 and O
                   2769:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2770:        if ($existing{$newkey}) {
                   2771:            $i--;
                   2772:        } else {
1.364     www      2773: 	  if (&put('accesskeys',
                   2774:               { $newkey => '# generated '.localtime().
1.620     albertel 2775:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2776:                            '; '.$logentry },
                   2777: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2778:               $total++;
                   2779: 	  }
                   2780:        }
                   2781:     }
1.620     albertel 2782:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2783:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2784:     return $total;
                   2785: }
                   2786: 
                   2787: # ------------------------------------------------------- Validate an accesskey
                   2788: 
                   2789: sub validate_access_key {
                   2790:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2791:     $cdom=
1.620     albertel 2792:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2793:     $cnum=
1.620     albertel 2794:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2795:     $udom=$env{'user.domain'} unless (defined($udom));
                   2796:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2797:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2798:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2799: }
                   2800: 
                   2801: # ------------------------------------- Find the section of student in a course
1.652     albertel 2802: sub devalidate_getsection_cache {
                   2803:     my ($udom,$unam,$courseid)=@_;
                   2804:     my $hashid="$udom:$unam:$courseid";
                   2805:     &devalidate_cache_new('getsection',$hashid);
                   2806: }
1.298     matthew  2807: 
1.815     albertel 2808: sub courseid_to_courseurl {
                   2809:     my ($courseid) = @_;
                   2810:     #already url style courseid
                   2811:     return $courseid if ($courseid =~ m{^/});
                   2812: 
                   2813:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2814: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2815: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2816: 	return "/$cdom/$cnum";
                   2817:     }
                   2818: 
                   2819:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2820:     if (exists($courseinfo{'num'})) {
                   2821: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2822:     }
                   2823: 
                   2824:     return undef;
                   2825: }
                   2826: 
1.298     matthew  2827: sub getsection {
                   2828:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2829:     my $cachetime=1800;
1.551     albertel 2830: 
                   2831:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2832:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2833:     if (defined($cached)) { return $result; }
                   2834: 
1.298     matthew  2835:     my %Pending; 
                   2836:     my %Expired;
                   2837:     #
                   2838:     # Each role can either have not started yet (pending), be active, 
                   2839:     #    or have expired.
                   2840:     #
                   2841:     # If there is an active role, we are done.
                   2842:     #
                   2843:     # If there is more than one role which has not started yet, 
                   2844:     #     choose the one which will start sooner
                   2845:     # If there is one role which has not started yet, return it.
                   2846:     #
                   2847:     # If there is more than one expired role, choose the one which ended last.
                   2848:     # If there is a role which has expired, return it.
                   2849:     #
1.815     albertel 2850:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2851:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2852:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2853:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2854:         my $section=$1;
                   2855:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2856:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2857:         my $now=time;
1.548     albertel 2858:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2859:             $Expired{$end}=$section;
                   2860:             next;
                   2861:         }
1.548     albertel 2862:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2863:             $Pending{$start}=$section;
                   2864:             next;
                   2865:         }
1.599     albertel 2866:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2867:     }
                   2868:     #
                   2869:     # Presumedly there will be few matching roles from the above
                   2870:     # loop and the sorting time will be negligible.
                   2871:     if (scalar(keys(%Pending))) {
                   2872:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2873:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2874:     } 
                   2875:     if (scalar(keys(%Expired))) {
                   2876:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2877:         my $time = pop(@sorted);
1.599     albertel 2878:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2879:     }
1.599     albertel 2880:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2881: }
1.70      www      2882: 
1.599     albertel 2883: sub save_cache {
                   2884:     &purge_remembered();
1.722     albertel 2885:     #&Apache::loncommon::validate_page();
1.620     albertel 2886:     undef(%env);
1.780     albertel 2887:     undef($env_loaded);
1.599     albertel 2888: }
1.452     albertel 2889: 
1.599     albertel 2890: my $to_remember=-1;
                   2891: my %remembered;
                   2892: my %accessed;
                   2893: my $kicks=0;
                   2894: my $hits=0;
1.849     albertel 2895: sub make_key {
                   2896:     my ($name,$id) = @_;
1.872     albertel 2897:     if (length($id) > 65 
                   2898: 	&& length(&escape($id)) > 200) {
                   2899: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2900:     }
1.849     albertel 2901:     return &escape($name.':'.$id);
                   2902: }
                   2903: 
1.599     albertel 2904: sub devalidate_cache_new {
                   2905:     my ($name,$id,$debug) = @_;
                   2906:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2907:     my $remembered_id=$name.':'.$id;
1.849     albertel 2908:     $id=&make_key($name,$id);
1.599     albertel 2909:     $memcache->delete($id);
1.1319    damieng  2910:     delete($remembered{$remembered_id});
                   2911:     delete($accessed{$remembered_id});
1.599     albertel 2912: }
                   2913: 
                   2914: sub is_cached_new {
                   2915:     my ($name,$id,$debug) = @_;
1.1319    damieng  2916:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2917:     if (exists($remembered{$remembered_id})) {
                   2918: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2919: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2920: 	$hits++;
1.1319    damieng  2921: 	return ($remembered{$remembered_id},1);
1.599     albertel 2922:     }
1.1319    damieng  2923:     $id=&make_key($name,$id);
1.599     albertel 2924:     my $value = $memcache->get($id);
                   2925:     if (!(defined($value))) {
                   2926: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2927: 	return (undef,undef);
1.416     albertel 2928:     }
1.599     albertel 2929:     if ($value eq '__undef__') {
                   2930: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2931: 	$value=undef;
                   2932:     }
1.1319    damieng  2933:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2934:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2935:     return ($value,1);
                   2936: }
                   2937: 
                   2938: sub do_cache_new {
                   2939:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2940:     my $remembered_id=$name.':'.$id;
1.849     albertel 2941:     $id=&make_key($name,$id);
1.599     albertel 2942:     my $setvalue=$value;
                   2943:     if (!defined($setvalue)) {
                   2944: 	$setvalue='__undef__';
                   2945:     }
1.623     albertel 2946:     if (!defined($time) ) {
                   2947: 	$time=600;
                   2948:     }
1.599     albertel 2949:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2950:     my $result = $memcache->set($id,$setvalue,$time);
                   2951:     if (! $result) {
1.872     albertel 2952: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2953: 	$memcache->disconnect_all();
1.872     albertel 2954:     }
1.600     albertel 2955:     # need to make a copy of $value
1.1319    damieng  2956:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2957:     return $value;
                   2958: }
                   2959: 
                   2960: sub make_room {
1.1319    damieng  2961:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2962: 
1.1319    damieng  2963:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2964:                                     : $value;
1.599     albertel 2965:     if ($to_remember<0) { return; }
1.1319    damieng  2966:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2967:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2968:     my $to_kick;
                   2969:     my $max_time=0;
                   2970:     foreach my $other (keys(%accessed)) {
                   2971: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2972: 	    $to_kick=$other;
                   2973: 	    $max_time=&tv_interval($accessed{$other});
                   2974: 	}
                   2975:     }
                   2976:     delete($remembered{$to_kick});
                   2977:     delete($accessed{$to_kick});
                   2978:     $kicks++;
                   2979:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2980:     return;
                   2981: }
                   2982: 
1.599     albertel 2983: sub purge_remembered {
1.604     albertel 2984:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2985:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2986:     undef(%remembered);
                   2987:     undef(%accessed);
1.428     albertel 2988: }
1.70      www      2989: # ------------------------------------- Read an entry from a user's environment
                   2990: 
                   2991: sub userenvironment {
                   2992:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2993:     my $items;
                   2994:     foreach my $item (@what) {
                   2995:         $items.=&escape($item).'&';
                   2996:     }
                   2997:     $items=~s/\&$//;
1.70      www      2998:     my %returnhash=();
1.1009    raeburn  2999:     my $uhome = &homeserver($unam,$udom);
                   3000:     unless ($uhome eq 'no_host') {
                   3001:         my @answer=split(/\&/, 
                   3002:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3003:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3004:             return %returnhash;
                   3005:         }
1.1009    raeburn  3006:         my $i;
                   3007:         for ($i=0;$i<=$#what;$i++) {
                   3008: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3009:         }
1.70      www      3010:     }
                   3011:     return %returnhash;
1.1       albertel 3012: }
                   3013: 
1.617     albertel 3014: # ---------------------------------------------------------- Get a studentphoto
                   3015: sub studentphoto {
                   3016:     my ($udom,$unam,$ext) = @_;
                   3017:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3018:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3019:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3020:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3021:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3022:             } else {
                   3023:                 my ($result,$perm_reqd)=
1.707     albertel 3024: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3025:                 if ($result eq 'ok') {
                   3026:                     if (!($perm_reqd eq 'yes')) {
                   3027:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3028:                     }
                   3029:                 }
                   3030:             }
                   3031:         }
                   3032:     } else {
                   3033:         my ($result,$perm_reqd) = 
1.707     albertel 3034: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3035:         if ($result eq 'ok') {
                   3036:             if (!($perm_reqd eq 'yes')) {
                   3037:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3038:             }
                   3039:         }
                   3040:     }
                   3041:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3042: }
                   3043: 
                   3044: sub retrievestudentphoto {
                   3045:     my ($udom,$unam,$ext,$type) = @_;
                   3046:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3047:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3048:     if ($ret eq 'ok') {
                   3049:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3050:         if ($type eq 'thumbnail') {
                   3051:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3052:         }
                   3053:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3054:         return $tokenurl;
                   3055:     } else {
                   3056:         if ($type eq 'thumbnail') {
                   3057:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3058:         } else { 
                   3059:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3060:         }
1.617     albertel 3061:     }
                   3062: }
                   3063: 
1.263     www      3064: # -------------------------------------------------------------------- New chat
                   3065: 
                   3066: sub chatsend {
1.724     raeburn  3067:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3068:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3069:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3070:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3071:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3072: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3073: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3074: }
                   3075: 
                   3076: # ------------------------------------------ Find current version of a resource
                   3077: 
                   3078: sub getversion {
                   3079:     my $fname=&clutter(shift);
1.1189    raeburn  3080:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3081:     return &currentversion(&filelocation('',$fname));
                   3082: }
                   3083: 
                   3084: sub currentversion {
                   3085:     my $fname=shift;
                   3086:     my $author=$fname;
                   3087:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3088:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3089:     my $home=&homeserver($uname,$udom);
1.292     www      3090:     if ($home eq 'no_host') { 
                   3091:         return -1; 
                   3092:     }
1.1112    www      3093:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3094:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3095: 	return -1;
                   3096:     }
1.1112    www      3097:     return $answer;
1.263     www      3098: }
                   3099: 
1.1111    www      3100: #
                   3101: # Return special version number of resource if set by override, empty otherwise
                   3102: #
                   3103: sub usedversion {
                   3104:     my $fname=shift;
                   3105:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3106:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3107:     if ($urlversion) { return $urlversion; }
                   3108:     return '';
                   3109: }
                   3110: 
1.1       albertel 3111: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3112: 
1.1       albertel 3113: sub subscribe {
                   3114:     my $fname=shift;
1.761     raeburn  3115:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3116:     $fname=~s/[\n\r]//g;
1.1       albertel 3117:     my $author=$fname;
                   3118:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3119:     my ($udom,$uname)=split(/\//,$author);
                   3120:     my $home=homeserver($uname,$udom);
1.335     albertel 3121:     if ($home eq 'no_host') {
                   3122:         return 'not_found';
1.1       albertel 3123:     }
                   3124:     my $answer=reply("sub:$fname",$home);
1.64      www      3125:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3126: 	$answer.=' by '.$home;
                   3127:     }
1.1       albertel 3128:     return $answer;
                   3129: }
                   3130:     
1.8       www      3131: # -------------------------------------------------------------- Replicate file
                   3132: 
                   3133: sub repcopy {
                   3134:     my $filename=shift;
1.23      www      3135:     $filename=~s/\/+/\//g;
1.1142    raeburn  3136:     my $londocroot = $perlvar{'lonDocRoot'};
                   3137:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3138:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3139:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3140: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3141: 	return &repcopy_userfile($filename);
                   3142:     }
1.532     albertel 3143:     $filename=~s/[\n\r]//g;
1.8       www      3144:     my $transname="$filename.in.transfer";
1.828     www      3145: # FIXME: this should flock
1.607     raeburn  3146:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3147:     my $remoteurl=subscribe($filename);
1.64      www      3148:     if ($remoteurl =~ /^con_lost by/) {
                   3149: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3150:            return 'unavailable';
1.8       www      3151:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3152: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3153: 	   return 'not_found';
1.64      www      3154:     } elsif ($remoteurl =~ /^rejected by/) {
                   3155: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3156:            return 'forbidden';
1.20      www      3157:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3158:            return 'ok';
1.8       www      3159:     } else {
1.290     www      3160:         my $author=$filename;
                   3161:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3162:         my ($udom,$uname)=split(/\//,$author);
                   3163:         my $home=homeserver($uname,$udom);
                   3164:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3165:            my @parts=split(/\//,$filename);
                   3166:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3167:            if ($path ne "$londocroot/res") {
1.8       www      3168:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3169: 	       return 'bad_request';
1.8       www      3170:            }
                   3171:            my $count;
                   3172:            for ($count=5;$count<$#parts;$count++) {
                   3173:                $path.="/$parts[$count]";
                   3174:                if ((-e $path)!=1) {
                   3175: 		   mkdir($path,0777);
                   3176:                }
                   3177:            }
                   3178:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3179:            my $response;
                   3180:            if ($remoteurl =~ m{/raw/}) {
                   3181:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3182:            } else {
                   3183:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3184:            }
1.8       www      3185:            if ($response->is_error()) {
                   3186: 	       unlink($transname);
                   3187:                my $message=$response->status_line;
1.672     albertel 3188:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3189:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3190:                return 'unavailable';
1.8       www      3191:            } else {
1.16      www      3192: 	       if ($remoteurl!~/\.meta$/) {
                   3193:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3194:                   my $mresponse;
                   3195:                   if ($remoteurl =~ m{/raw/}) {
                   3196:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3197:                   } else {
                   3198:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3199:                   }
1.16      www      3200:                   if ($mresponse->is_error()) {
                   3201: 		      unlink($filename.'.meta');
                   3202:                       &logthis(
1.672     albertel 3203:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3204:                   }
                   3205: 	       }
1.8       www      3206:                rename($transname,$filename);
1.607     raeburn  3207:                return 'ok';
1.8       www      3208:            }
1.290     www      3209:        }
1.8       www      3210:     }
1.330     www      3211: }
                   3212: 
                   3213: # ------------------------------------------------ Get server side include body
                   3214: sub ssi_body {
1.381     albertel 3215:     my ($filelink,%form)=@_;
1.606     matthew  3216:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3217:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3218:     }
1.953     www      3219:     my $output='';
                   3220:     my $response;
1.980     raeburn  3221:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3222:        ($output,$response)=&externalssi($filelink);
1.953     www      3223:     } else {
1.1004    droeschl 3224:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3225:        $filelink .= 'inhibitmenu=yes';
1.953     www      3226:        ($output,$response)=&ssi($filelink,%form);
                   3227:     }
1.778     albertel 3228:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3229:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3230:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3231:     if (wantarray) {
                   3232:         return ($output, $response);
                   3233:     } else {
                   3234:         return $output;
                   3235:     }
1.8       www      3236: }
                   3237: 
1.15      www      3238: # --------------------------------------------------------- Server Side Include
                   3239: 
1.782     albertel 3240: sub absolute_url {
                   3241:     my ($host_name) = @_;
                   3242:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3243:     if ($host_name eq '') {
                   3244: 	$host_name = $ENV{'SERVER_NAME'};
                   3245:     }
                   3246:     return $protocol.$host_name;
                   3247: }
                   3248: 
1.942     foxr     3249: #
                   3250: #   Server side include.
                   3251: # Parameters:
                   3252: #  fn     Possibly encrypted resource name/id.
                   3253: #  form   Hash that describes how the rendering should be done
                   3254: #         and other things.
1.944     foxr     3255: # Returns:
1.950     raeburn  3256: #   Scalar context: The content of the response.
                   3257: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3258: #     
1.15      www      3259: sub ssi {
                   3260: 
1.944     foxr     3261:     my ($fn,%form)=@_;
1.23      www      3262:     my $request;
1.711     albertel 3263: 
                   3264:     $form{'no_update_last_known'}=1;
1.895     albertel 3265:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3266:     if (%form) {
1.782     albertel 3267:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3268:       $request->content(join('&',map { 
                   3269:             my $name = escape($_);
                   3270:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3271:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3272:             : &escape($form{$_}) );    
                   3273:         } keys(%form)));
1.23      www      3274:     } else {
1.782     albertel 3275:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3276:     }
                   3277: 
1.15      www      3278:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3279:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3280:     my $islocal;
                   3281:     if (($env{'request.course.id'}) &&
                   3282:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3283:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3284:         ($form{'grade_symb'} ne '') &&
                   3285:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3286:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3287:         $islocal = 1;
                   3288:     }
1.1384    raeburn  3289:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3290:                                                 '','','',$islocal);
1.1182    foxr     3291: 
1.944     foxr     3292:     if (wantarray) {
1.1345    raeburn  3293: 	return ($response->content, $response);
1.944     foxr     3294:     } else {
1.1345    raeburn  3295: 	return $response->content;
1.942     foxr     3296:     }
1.324     www      3297: }
                   3298: 
                   3299: sub externalssi {
                   3300:     my ($url)=@_;
                   3301:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3302:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3303:     if (wantarray) {
                   3304:         return ($response->content, $response);
                   3305:     } else {
                   3306:         return $response->content;
                   3307:     }
1.15      www      3308: }
1.254     www      3309: 
1.1354    raeburn  3310: 
                   3311: # If the local copy of a replicated resource is outdated, trigger a  
                   3312: # connection from the homeserver to flush the delayed queue. If no update 
                   3313: # happens, remove local copies of outdated resource (and corresponding
                   3314: # metadata file).
                   3315: 
1.1352    raeburn  3316: sub remove_stale_resfile {
                   3317:     my ($url) = @_;
1.1354    raeburn  3318:     my $removed;
1.1352    raeburn  3319:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3320:         my $audom = $1;
                   3321:         my $auname = $2;
1.1353    raeburn  3322:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3323:             my $homeserver = &homeserver($auname,$audom);
                   3324:             unless (($homeserver eq 'no_host') ||
                   3325:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3326:                 my $fname = &filelocation('',$url);
                   3327:                 if (-e $fname) {
                   3328:                     my $protocol = $protocol{$homeserver};
                   3329:                     $protocol = 'http' if ($protocol ne 'https');
                   3330:                     my $hostname = &hostname($homeserver);
                   3331:                     if ($hostname) {
                   3332:                         my $uri = &declutter($url);
                   3333:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3334:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3335:                         if ($response->is_success()) {
                   3336:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3337:                             my $locmodtime = (stat($fname))[9];
                   3338:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3339:                                 my $stale;
                   3340:                                 my $answer = &reply('pong',$homeserver);
                   3341:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3342:                                     sleep(0.2);
                   3343:                                     $locmodtime = (stat($fname))[9];
                   3344:                                     if ($locmodtime < $remmodtime) {
                   3345:                                         my $posstransfer = $fname.'.in.transfer';
                   3346:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3347:                                             $removed = 1;
                   3348:                                         } else {
                   3349:                                             $stale = 1;
                   3350:                                         }
                   3351:                                     } else {
                   3352:                                         $removed = 1;
                   3353:                                     }
                   3354:                                 } else {
                   3355:                                     $stale = 1;
                   3356:                                 }
                   3357:                                 if ($stale) {
                   3358:                                     unlink($fname);
                   3359:                                     if ($uri!~/\.meta$/) {
                   3360:                                         unlink($fname.'.meta');
                   3361:                                     }
                   3362:                                     &reply("unsub:$fname",$homeserver);
                   3363:                                     $removed = 1;
1.1352    raeburn  3364:                                 }
                   3365:                             }
                   3366:                         }
                   3367:                     }
                   3368:                 }
                   3369:             }
                   3370:         }
                   3371:     }
1.1354    raeburn  3372:     return $removed;
1.1352    raeburn  3373: }
                   3374: 
1.492     albertel 3375: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3376: 
                   3377: sub allowuploaded {
                   3378:     my ($srcurl,$url)=@_;
                   3379:     $url=&clutter(&declutter($url));
                   3380:     my $dir=$url;
                   3381:     $dir=~s/\/[^\/]+$//;
                   3382:     my %httpref=();
                   3383:     my $httpurl=&hreflocation('',$url);
                   3384:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3385:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3386: }
1.477     raeburn  3387: 
1.1193    raeburn  3388: #
                   3389: # Determine if the current user should be able to edit a particular resource,
                   3390: # when viewing in course context.
                   3391: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3392: #     Functions.
                   3393: # (b) When displaying folder contents in course editor, used to determine if
                   3394: #     "Edit" link will be displayed alongside resource.
                   3395: #
1.1196    raeburn  3396: #  input: six args -- filename (decluttered), course number, course domain,
                   3397: #                   url, symb (if registered) and group (if this is a group
                   3398: #                   item -- e.g., bulletin board, group page etc.).
                   3399: #  output: array of five scalars -- 
1.1193    raeburn  3400: #          $cfile -- url for file editing if editable on current server
                   3401: #          $home -- homeserver of resource (i.e., for author if published,
                   3402: #                                           or course if uploaded.).
                   3403: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3404: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3405: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3406: #
                   3407: 
                   3408: sub can_edit_resource {
1.1194    raeburn  3409:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3410:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3411: #
                   3412: # For aboutme pages user can only edit his/her own.
                   3413: #
1.1199    raeburn  3414:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3415:         my ($sdom,$sname) = ($1,$2);
                   3416:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3417:             $home = $env{'user.home'};
                   3418:             $cfile = $resurl;
                   3419:             if ($env{'form.forceedit'}) {
                   3420:                 $forceview = 1;
                   3421:             } else {
                   3422:                 $forceedit = 1;
                   3423:             }
                   3424:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3425:         } else {
                   3426:             return;
                   3427:         }
                   3428:     }
                   3429: 
                   3430:     if ($env{'request.course.id'}) {
                   3431:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3432:         if ($group ne '') {
                   3433: # if this is a group homepage or group bulletin board, check group privs
                   3434:             my $allowed = 0;
1.1197    raeburn  3435:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3436:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3437:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3438:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3439:                     $allowed = 1;
                   3440:                 }
1.1197    raeburn  3441:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3442:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3443:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3444:                     $allowed = 1;
                   3445:                 }
                   3446:             }
                   3447:             if ($allowed) {
                   3448:                 $home=&homeserver($cnum,$cdom);
                   3449:                 if ($env{'form.forceedit'}) {
                   3450:                     $forceview = 1;
                   3451:                 } else {
                   3452:                     $forceedit = 1;
                   3453:                 }
                   3454:                 $cfile = $resurl;
                   3455:             } else {
                   3456:                 return;
                   3457:             }
                   3458:         } else {
1.1208    raeburn  3459:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3460:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3461:                     return;
                   3462:                 }
                   3463:             } elsif (!$crsedit) {
1.1194    raeburn  3464: #
                   3465: # No edit allowed where CC has switched to student role.
                   3466: #
                   3467:                 return;
                   3468:             }
                   3469:         }
                   3470:     }
                   3471: 
1.1193    raeburn  3472:     if ($file ne '') {
                   3473:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3474:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3475:                 $uploaded = 1;
                   3476:                 $incourse = 1;
1.1193    raeburn  3477:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3478:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3479:                     if ($env{'form.forceedit'}) {
                   3480:                         $forceview = 1;
                   3481:                     } else {
                   3482:                         $forceedit = 1;
                   3483:                     }
1.1194    raeburn  3484:                 }
                   3485:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3486:                 $incourse = 1;
                   3487:                 if ($env{'form.forceedit'}) {
                   3488:                     $forceview = 1;
                   3489:                 } else {
                   3490:                     $forceedit = 1;
                   3491:                 }
                   3492:                 $cfile = $resurl;
                   3493:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3494:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3495:                     $incourse = 1;
                   3496:                     if ($env{'form.forceedit'}) {
                   3497:                         $forceview = 1;
                   3498:                     } else {
                   3499:                         $forceedit = 1;
                   3500:                     }
                   3501:                     $cfile = $resurl;
1.1199    raeburn  3502:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3503:                     $incourse = 1;
                   3504:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3505:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3506:                     $incourse = 1;
1.1199    raeburn  3507:                     if ($env{'form.forceedit'}) {
                   3508:                         $forceview = 1;
                   3509:                     } else {
                   3510:                         $forceedit = 1;
                   3511:                     }
                   3512:                     $cfile = $resurl;
1.1343    raeburn  3513:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3514:                     $incourse = 1;
                   3515:                     if ($env{'form.forceedit'}) {
                   3516:                         $forceview = 1;
                   3517:                     } else {
                   3518:                         $forceedit = 1;
                   3519:                     }
                   3520:                     $cfile = $resurl;
1.1208    raeburn  3521:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3522:                     $incourse = 1;
                   3523:                     if ($env{'form.forceedit'}) {
                   3524:                         $forceview = 1;
                   3525:                     } else {
                   3526:                         $forceedit = 1;
                   3527:                     }
                   3528:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3529:                 }
                   3530:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3531:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3532:                 if (&is_on_map($template)) { 
                   3533:                     $incourse = 1;
                   3534:                     $forceview = 1;
                   3535:                     $cfile = $template;
1.1193    raeburn  3536:                 }
1.1199    raeburn  3537:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3538:                     $incourse = 1;
                   3539:                     if ($env{'form.forceedit'}) {
                   3540:                         $forceview = 1;
                   3541:                     } else {
                   3542:                         $forceedit = 1;
                   3543:                     }
                   3544:                     $cfile = $resurl;
1.1343    raeburn  3545:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3546:                 $incourse = 1;
                   3547:                 if ($env{'form.forceedit'}) {
                   3548:                     $forceview = 1;
                   3549:                 } else {
                   3550:                     $forceedit = 1;
                   3551:                 }
                   3552:                 $cfile = $resurl;
1.1199    raeburn  3553:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3554:                 $incourse = 1;
                   3555:                 $forceview = 1;
                   3556:                 if ($symb) {
                   3557:                     my ($map,$id,$res)=&decode_symb($symb);
                   3558:                     $env{'request.symb'} = $symb;
                   3559:                     $cfile = &clutter($res);
                   3560:                 } else {
                   3561:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3562:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3563:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3564:                         $cfile = '/adm/wrapper'.$escfile;
                   3565:                     } else {
                   3566:                         $escfile =~ s{^http://}{};
                   3567:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3568:                     }
1.1199    raeburn  3569:                 }
1.1234    raeburn  3570:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3571:                 if ($env{'form.forceedit'}) {
                   3572:                     $forceview = 1;
                   3573:                 } else {
                   3574:                     $forceedit = 1;
                   3575:                 }
                   3576:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3577:             }
                   3578:         }
1.1194    raeburn  3579:         if ($uploaded || $incourse) {
                   3580:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3581:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3582:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3583:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3584:             # Check that the user has permission to edit this resource
                   3585:             my $setpriv = 1;
                   3586:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3587:             if (defined($cfudom)) {
                   3588:                 $home=&homeserver($cfuname,$cfudom);
                   3589:                 $cfile=$file;
                   3590:             }
                   3591:         }
1.1194    raeburn  3592:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3593:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3594:             my @ids=&current_machine_ids();
                   3595:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3596:                 $switchserver=1;
                   3597:             }
                   3598:         }
                   3599:     }
1.1194    raeburn  3600:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3601: }
                   3602: 
                   3603: sub is_course_upload {
                   3604:     my ($file,$cnum,$cdom) = @_;
                   3605:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3606:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3607:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3608:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3609:         return 1;
                   3610:     }
                   3611:     return;
                   3612: }
                   3613: 
1.1194    raeburn  3614: sub in_course {
1.1195    raeburn  3615:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3616:     if ($hideprivileged) {
                   3617:         my $skipuser;
1.1219    raeburn  3618:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3619:         my @possdoms = ($cdom);  
                   3620:         if ($coursehash{'checkforpriv'}) { 
                   3621:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3622:         }
                   3623:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3624:             $skipuser = 1;
                   3625:             if ($coursehash{'nothideprivileged'}) {
                   3626:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3627:                     my $user;
                   3628:                     if ($item =~ /:/) {
                   3629:                         $user = $item;
                   3630:                     } else {
                   3631:                         $user = join(':',split(/[\@]/,$item));
                   3632:                     }
                   3633:                     if ($user eq $uname.':'.$udom) {
                   3634:                         undef($skipuser);
                   3635:                         last;
                   3636:                     }
                   3637:                 }
                   3638:             }
                   3639:             if ($skipuser) {
                   3640:                 return 0;
                   3641:             }
                   3642:         }
                   3643:     }
1.1194    raeburn  3644:     $type ||= 'any';
                   3645:     if (!defined($cdom) || !defined($cnum)) {
                   3646:         my $cid  = $env{'request.course.id'};
                   3647:         $cdom = $env{'course.'.$cid.'.domain'};
                   3648:         $cnum = $env{'course.'.$cid.'.num'};
                   3649:     }
                   3650:     my $typesref;
1.1195    raeburn  3651:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3652:         $typesref = ['active','previous','future'];
                   3653:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3654:         $typesref = [$type];
                   3655:     }
                   3656:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3657:                               $typesref,undef,[$cdom]);
                   3658:     my ($tmp) = keys(%roles);
                   3659:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3660:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3661:     if (@course_roles > 0) {
                   3662:         return 1;
                   3663:     }
                   3664:     return 0;
                   3665: }
                   3666: 
1.478     albertel 3667: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3668: # input: action, courseID, current domain, intended
1.637     raeburn  3669: #        path to file, source of file, instruction to parse file for objects,
                   3670: #        ref to hash for embedded objects,
                   3671: #        ref to hash for codebase of java objects.
1.1095    raeburn  3672: #        reference to scalar to accommodate mime type determined
                   3673: #          from File::MMagic if $parser = parse.
1.637     raeburn  3674: #
1.485     raeburn  3675: # output: url to file (if action was uploaddoc), 
                   3676: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3677: #
1.478     albertel 3678: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3679: # course.
1.477     raeburn  3680: #
1.478     albertel 3681: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3682: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3683: #          course's home server.
1.477     raeburn  3684: #
1.478     albertel 3685: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3686: #          be copied from $source (current location) to 
                   3687: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3688: #         and will then be copied to
                   3689: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3690: #         course's home server.
1.485     raeburn  3691: #
1.481     raeburn  3692: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3693: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3694: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3695: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3696: #         in course's home server.
1.637     raeburn  3697: #
1.477     raeburn  3698: 
                   3699: sub process_coursefile {
1.1095    raeburn  3700:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3701:         $mimetype)=@_;
1.477     raeburn  3702:     my $fetchresult;
1.638     albertel 3703:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3704:     if ($action eq 'propagate') {
1.638     albertel 3705:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3706: 			     $home);
1.481     raeburn  3707:     } else {
1.477     raeburn  3708:         my $fpath = '';
                   3709:         my $fname = $file;
1.478     albertel 3710:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3711:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3712:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3713:         if ($action eq 'copy') {
                   3714:             if ($source eq '') {
                   3715:                 $fetchresult = 'no source file';
                   3716:                 return $fetchresult;
                   3717:             } else {
                   3718:                 my $destination = $filepath.'/'.$fname;
                   3719:                 rename($source,$destination);
                   3720:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3721:                                  $home);
1.481     raeburn  3722:             }
                   3723:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3724:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3725:             print $fh $env{'form.'.$source};
1.481     raeburn  3726:             close($fh);
1.637     raeburn  3727:             if ($parser eq 'parse') {
1.1024    raeburn  3728:                 my $mm = new File::MMagic;
1.1095    raeburn  3729:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3730:                 if ($type eq 'text/html') {
1.1024    raeburn  3731:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3732:                     unless ($parse_result eq 'ok') {
                   3733:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3734:                     }
1.637     raeburn  3735:                 }
1.1095    raeburn  3736:                 if (ref($mimetype)) {
                   3737:                     $$mimetype = $type;
                   3738:                 } 
1.637     raeburn  3739:             }
1.477     raeburn  3740:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3741:                                  $home);
1.481     raeburn  3742:             if ($fetchresult eq 'ok') {
                   3743:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3744:             } else {
                   3745:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3746:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3747:                 return '/adm/notfound.html';
                   3748:             }
1.477     raeburn  3749:         }
                   3750:     }
1.485     raeburn  3751:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3752:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3753:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3754:     }
                   3755:     return $fetchresult;
                   3756: }
                   3757: 
1.637     raeburn  3758: sub build_filepath {
                   3759:     my ($fpath) = @_;
                   3760:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3761:     unless ($fpath eq '') {
                   3762:         my @parts=split('/',$fpath);
                   3763:         foreach my $part (@parts) {
                   3764:             $filepath.= '/'.$part;
                   3765:             if ((-e $filepath)!=1) {
                   3766:                 mkdir($filepath,0777);
                   3767:             }
                   3768:         }
                   3769:     }
                   3770:     return $filepath;
                   3771: }
                   3772: 
                   3773: sub store_edited_file {
1.638     albertel 3774:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3775:     my $file = $primary_url;
                   3776:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3777:     my $fpath = '';
                   3778:     my $fname = $file;
                   3779:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3780:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3781:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3782:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3783:     print $fh $content;
                   3784:     close($fh);
1.638     albertel 3785:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3786:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3787: 			  $home);
1.637     raeburn  3788:     if ($$fetchresult eq 'ok') {
                   3789:         return '/uploaded/'.$fpath.'/'.$fname;
                   3790:     } else {
1.638     albertel 3791:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3792: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3793:         return '/adm/notfound.html';
                   3794:     }
                   3795: }
                   3796: 
1.531     albertel 3797: sub clean_filename {
1.831     albertel 3798:     my ($fname,$args)=@_;
1.315     www      3799: # Replace Windows backslashes by forward slashes
1.257     www      3800:     $fname=~s/\\/\//g;
1.831     albertel 3801:     if (!$args->{'keep_path'}) {
                   3802:         # Get rid of everything but the actual filename
                   3803: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3804:     }
1.315     www      3805: # Replace spaces by underscores
                   3806:     $fname=~s/\s+/\_/g;
                   3807: # Replace all other weird characters by nothing
1.831     albertel 3808:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3809: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3810: # numbers
                   3811:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3812:     return $fname;
                   3813: }
1.1051    raeburn  3814: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3815: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3816: # image with the same aspect ratio as the original, but with dimensions which do 
                   3817: # not exceed $resizewidth and $resizeheight.
                   3818:  
1.984     neumanie 3819: sub resizeImage {
1.1051    raeburn  3820:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3821:     my $ima = Image::Magick->new;
                   3822:     my $resized;
                   3823:     if (-e $img_path) {
                   3824:         $ima->Read($img_path);
                   3825:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3826:             my $width = $ima->Get('width');
                   3827:             my $height = $ima->Get('height');
                   3828:             if ($width > $resizewidth) {
                   3829: 	        my $factor = $width/$resizewidth;
                   3830:                 my $newheight = $height/$factor;
                   3831:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3832:                 $resized = 1;
                   3833:             }
                   3834:         }
                   3835:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3836:             my $width = $ima->Get('width');
                   3837:             my $height = $ima->Get('height');
                   3838:             if ($height > $resizeheight) {
                   3839:                 my $factor = $height/$resizeheight;
                   3840:                 my $newwidth = $width/$factor;
                   3841:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3842:                 $resized = 1;
                   3843:             }
                   3844:         }
                   3845:         if ($resized) {
                   3846:             $ima->Write($img_path);
                   3847:         }
                   3848:     }
                   3849:     return;
1.977     amueller 3850: }
                   3851: 
1.608     albertel 3852: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3853: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3854: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3855: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3856: #                                    canceloverwrite, or ''. 
                   3857: #                   if 'coursedoc': upload to the current course
                   3858: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3859: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3860: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3861: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3862: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3863: #        $allfiles - reference to hash for embedded objects
                   3864: #        $codebase - reference to hash for codebase of java objects
                   3865: #        $desuname - username for permanent storage of uploaded file
                   3866: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3867: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3868: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3869: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3870: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3871: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3872: #                    from File::MMagic.
1.858     raeburn  3873: # 
1.686     albertel 3874: # output: url of file in userspace, or error: <message> 
                   3875: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3876: 
1.531     albertel 3877: sub userfileupload {
1.1090    raeburn  3878:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3879:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3880:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3881:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3882:     $fname=&clean_filename($fname);
1.1090    raeburn  3883:     # See if there is anything left
1.257     www      3884:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3885:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3886:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3887:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3888:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3889:         my $now = time;
1.1090    raeburn  3890:         my $filepath;
1.1095    raeburn  3891:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3892:              $filepath = 'tmp/helprequests/'.$now;
                   3893:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3894:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3895:                          '_'.$env{'user.domain'}.'/pending';
                   3896:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3897:             my ($docuname,$docudom);
1.1350    raeburn  3898:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3899:                 $docudom = $destudom;
                   3900:             } else {
                   3901:                 $docudom = $env{'user.domain'};
                   3902:             }
1.1350    raeburn  3903:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3904:                 $docuname = $destuname;
                   3905:             } else {
                   3906:                 $docuname = $env{'user.name'};
                   3907:             }
                   3908:             if (exists($env{'form.group'})) {
                   3909:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3910:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3911:             }
                   3912:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3913:             if ($context eq 'canceloverwrite') {
                   3914:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3915:                 if (-e  $tempfile) {
                   3916:                     my @info = stat($tempfile);
                   3917:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3918:                         unlink($tempfile);
                   3919:                     }
                   3920:                 }
                   3921:                 return;
1.523     raeburn  3922:             }
                   3923:         }
1.1090    raeburn  3924:         # Create the directory if not present
1.741     raeburn  3925:         my @parts=split(/\//,$filepath);
                   3926:         my $fullpath = $perlvar{'lonDaemons'};
                   3927:         for (my $i=0;$i<@parts;$i++) {
                   3928:             $fullpath .= '/'.$parts[$i];
                   3929:             if ((-e $fullpath)!=1) {
                   3930:                 mkdir($fullpath,0777);
                   3931:             }
                   3932:         }
1.1359    raeburn  3933:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3934:         print $fh $env{'form.'.$formname};
                   3935:         close($fh);
1.1090    raeburn  3936:         if ($context eq 'existingfile') {
                   3937:             my @info = stat($fullpath.'/'.$fname);
                   3938:             return ($fullpath.'/'.$fname,$info[9]);
                   3939:         } else {
                   3940:             return $fullpath.'/'.$fname;
                   3941:         }
1.523     raeburn  3942:     }
1.995     raeburn  3943:     if ($subdir eq 'scantron') {
                   3944:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3945:     } else {
1.995     raeburn  3946:         $fname="$subdir/$fname";
                   3947:     }
1.1090    raeburn  3948:     if ($context eq 'coursedoc') {
1.638     albertel 3949: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3950: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3951:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3952:             return &finishuserfileupload($docuname,$docudom,
                   3953: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3954: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3955:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3956:         } else {
1.1218    raeburn  3957:             if ($env{'form.folder'}) {
                   3958:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3959:             }
1.638     albertel 3960:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3961: 				       $fname,$formname,$parser,
1.1095    raeburn  3962: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3963:         }
1.719     banghart 3964:     } elsif (defined($destuname)) {
                   3965:         my $docuname=$destuname;
                   3966:         my $docudom=$destudom;
1.860     raeburn  3967: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3968: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3969:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3970:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3971:     } else {
1.638     albertel 3972:         my $docuname=$env{'user.name'};
                   3973:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3974:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3975:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3976:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3977:         }
1.860     raeburn  3978: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3979: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3980:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3981:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3982:     }
1.271     www      3983: }
                   3984: 
                   3985: sub finishuserfileupload {
1.860     raeburn  3986:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3987:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3988:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3989:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3990:   
1.860     raeburn  3991:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3992:     $file=$fname;
                   3993:     if ($fname=~m|/|) {
                   3994:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3995: 	$path.=$fnamepath.'/';
                   3996:     }
1.259     www      3997:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3998:     my $count;
                   3999:     for ($count=4;$count<=$#parts;$count++) {
                   4000:         $filepath.="/$parts[$count]";
                   4001:         if ((-e $filepath)!=1) {
                   4002: 	    mkdir($filepath,0777);
                   4003:         }
                   4004:     }
1.984     neumanie 4005: 
1.258     www      4006: # Save the file
                   4007:     {
1.1359    raeburn  4008: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4009: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4010: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4011: 	    return '/adm/notfound.html';
                   4012: 	}
1.1090    raeburn  4013:         if ($context eq 'overwrite') {
1.1117    foxr     4014:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4015:             my $target = $filepath.'/'.$file;
                   4016:             if (-e $source) {
                   4017:                 my @info = stat($source);
                   4018:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4019:                     unless (&File::Copy::move($source,$target)) {
                   4020:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4021:                         return "Moving from $source failed";
                   4022:                     }
                   4023:                 } else {
                   4024:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4025:                 }
                   4026:             } else {
                   4027:                 return "Temporary file: $source missing";
                   4028:             }
                   4029:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4030: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4031: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4032: 	    return '/adm/notfound.html';
                   4033: 	}
1.570     albertel 4034: 	close(FH);
1.1051    raeburn  4035:         if ($resizewidth && $resizeheight) {
                   4036:             my $mm = new File::MMagic;
                   4037:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4038:             if ($mime_type =~ m{^image/}) {
                   4039: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4040:             }  
1.977     amueller 4041: 	}
1.258     www      4042:     }
1.1152    raeburn  4043:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4044:         if (ref($mimetype)) {
                   4045:             if ($$mimetype eq '') {
                   4046:                 my $mm = new File::MMagic;
                   4047:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4048:                 $$mimetype = $type;
                   4049:             }
                   4050:         }
                   4051:     }
1.637     raeburn  4052:     if ($parser eq 'parse') {
1.1152    raeburn  4053:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4054:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4055:                                                        $allfiles,$codebase);
                   4056:             unless ($parse_result eq 'ok') {
                   4057:                 &logthis('Failed to parse '.$filepath.$file.
                   4058: 	   	         ' for embedded media: '.$parse_result); 
                   4059:             }
1.637     raeburn  4060:         }
                   4061:     }
1.860     raeburn  4062:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4063:         my $input = $filepath.'/'.$file;
                   4064:         my $output = $filepath.'/'.'tn-'.$file;
                   4065:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4066:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4067:         system({$args[0]} @args);
1.860     raeburn  4068:         if (-e $filepath.'/'.'tn-'.$file) {
                   4069:             $fetchthumb  = 1; 
                   4070:         }
                   4071:     }
1.858     raeburn  4072:  
1.259     www      4073: # Notify homeserver to grep it
                   4074: #
1.984     neumanie 4075:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4076:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4077:     if ($fetchresult eq 'ok') {
1.860     raeburn  4078:         if ($fetchthumb) {
                   4079:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4080:             if ($thumbresult ne 'ok') {
                   4081:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4082:                          $docuhome.': '.$thumbresult);
                   4083:             }
                   4084:         }
1.259     www      4085: #
1.258     www      4086: # Return the URL to it
1.494     albertel 4087:         return '/uploaded/'.$path.$file;
1.263     www      4088:     } else {
1.494     albertel 4089:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4090: 		 ': '.$fetchresult);
1.263     www      4091:         return '/adm/notfound.html';
1.858     raeburn  4092:     }
1.493     albertel 4093: }
                   4094: 
1.637     raeburn  4095: sub extract_embedded_items {
1.961     raeburn  4096:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4097:     my @state = ();
1.1164    raeburn  4098:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4099:     my %javafiles = (
                   4100:                       codebase => '',
                   4101:                       code => '',
                   4102:                       archive => ''
                   4103:                     );
                   4104:     my %mediafiles = (
                   4105:                       src => '',
                   4106:                       movie => '',
                   4107:                      );
1.648     raeburn  4108:     my $p;
                   4109:     if ($content) {
                   4110:         $p = HTML::LCParser->new($content);
                   4111:     } else {
1.961     raeburn  4112:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4113:     }
1.641     albertel 4114:     while (my $t=$p->get_token()) {
1.640     albertel 4115: 	if ($t->[0] eq 'S') {
                   4116: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4117: 	    push(@state, $tagname);
1.648     raeburn  4118:             if (lc($tagname) eq 'allow') {
                   4119:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4120:             }
1.640     albertel 4121: 	    if (lc($tagname) eq 'img') {
                   4122: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4123: 	    }
1.886     albertel 4124: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4125:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4126:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4127:                 }
1.886     albertel 4128: 	    }
1.645     raeburn  4129:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4130:                 my $src;
1.645     raeburn  4131:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4132:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4133:                 } else {
1.1164    raeburn  4134:                     if ($attr->{'src'} ne '') {
                   4135:                         $src = $attr->{'src'};
                   4136:                         &add_filetype($allfiles,$src,'src');
                   4137:                     }
                   4138:                 }
                   4139:                 my $text = $p->get_trimmed_text();
                   4140:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4141:                     my @swfargs = split(/,/,$1);
                   4142:                     foreach my $item (@swfargs) {
                   4143:                         $item =~ s/["']//g;
                   4144:                         $item =~ s/^\s+//;
                   4145:                         $item =~ s/\s+$//;
                   4146:                     }
                   4147:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4148:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4149:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4150:                         } else {
                   4151:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4152:                         }
                   4153:                     }
1.645     raeburn  4154:                 }
                   4155:             }
                   4156:             if (lc($tagname) eq 'link') {
                   4157:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4158:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4159:                 }
                   4160:             }
1.640     albertel 4161: 	    if (lc($tagname) eq 'object' ||
                   4162: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4163: 		foreach my $item (keys(%javafiles)) {
                   4164: 		    $javafiles{$item} = '';
                   4165: 		}
1.1164    raeburn  4166:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4167:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4168:                 }
1.640     albertel 4169: 	    }
                   4170: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4171: 		my $name = lc($attr->{'name'});
                   4172: 		foreach my $item (keys(%javafiles)) {
                   4173: 		    if ($name eq $item) {
                   4174: 			$javafiles{$item} = $attr->{'value'};
                   4175: 			last;
                   4176: 		    }
                   4177: 		}
1.1164    raeburn  4178:                 my $pathfrom;
1.640     albertel 4179: 		foreach my $item (keys(%mediafiles)) {
                   4180: 		    if ($name eq $item) {
1.1164    raeburn  4181:                         $pathfrom = $attr->{'value'};
                   4182:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4183: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4184: 			last;
                   4185: 		    }
                   4186: 		}
1.1164    raeburn  4187:                 if ($name eq 'flashvars') {
                   4188:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4189:                 }
                   4190:                 if ($pathfrom ne '') {
                   4191:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4192:                                          $pathfrom);
                   4193:                 }
1.640     albertel 4194: 	    }
                   4195: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4196: 		foreach my $item (keys(%javafiles)) {
                   4197: 		    if ($attr->{$item}) {
                   4198: 			$javafiles{$item} = $attr->{$item};
                   4199: 			last;
                   4200: 		    }
                   4201: 		}
                   4202: 		foreach my $item (keys(%mediafiles)) {
                   4203: 		    if ($attr->{$item}) {
                   4204: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4205: 			last;
                   4206: 		    }
                   4207: 		}
1.1164    raeburn  4208:                 if (lc($tagname) eq 'embed') {
                   4209:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4210:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4211:                                              $attr->{'src'});
                   4212:                     }
                   4213:                 }
1.640     albertel 4214: 	    }
1.1243    raeburn  4215:             if (lc($tagname) eq 'iframe') {
                   4216:                 my $src = $attr->{'src'} ;
                   4217:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4218:                     &add_filetype($allfiles,$src,'src');
                   4219:                 } elsif ($src =~ m{^/}) {
                   4220:                     if ($env{'request.course.id'}) {
                   4221:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4222:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4223:                         my $url = &hreflocation('',$fullpath);
                   4224:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4225:                             my $relpath = $1;
                   4226:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4227:                                 &add_filetype($allfiles,$1,'src');
                   4228:                             }
                   4229:                         }
                   4230:                     }
                   4231:                 }
                   4232:             }
1.1164    raeburn  4233:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4234:                 pop(@state);
1.1164    raeburn  4235:             }
1.640     albertel 4236: 	} elsif ($t->[0] eq 'E') {
                   4237: 	    my ($tagname) = ($t->[1]);
                   4238: 	    if ($javafiles{'codebase'} ne '') {
                   4239: 		$javafiles{'codebase'} .= '/';
                   4240: 	    }  
                   4241: 	    if (lc($tagname) eq 'applet' ||
                   4242: 		lc($tagname) eq 'object' ||
                   4243: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4244: 		) {
                   4245: 		foreach my $item (keys(%javafiles)) {
                   4246: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4247: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4248: 			&add_filetype($allfiles,$file,$item);
                   4249: 		    }
                   4250: 		}
                   4251: 	    } 
                   4252: 	    pop @state;
                   4253: 	}
                   4254:     }
1.1164    raeburn  4255:     foreach my $id (sort(keys(%flashvars))) {
                   4256:         if ($shockwave{$id} ne '') {
                   4257:             my @pairs = split(/\&/,$flashvars{$id});
                   4258:             foreach my $pair (@pairs) {
                   4259:                 my ($key,$value) = split(/\=/,$pair);
                   4260:                 if ($key eq 'thumb') {
                   4261:                     &add_filetype($allfiles,$value,$key);
                   4262:                 } elsif ($key eq 'content') {
                   4263:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4264:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4265:                     if ($ext ne '') {
                   4266:                         &add_filetype($allfiles,$path.$value,$ext);
                   4267:                     }
                   4268:                 }
                   4269:             }
                   4270:         }
                   4271:     }
1.637     raeburn  4272:     return 'ok';
                   4273: }
                   4274: 
1.639     albertel 4275: sub add_filetype {
                   4276:     my ($allfiles,$file,$type)=@_;
                   4277:     if (exists($allfiles->{$file})) {
                   4278: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4279: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4280: 	}
                   4281:     } else {
                   4282: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4283:     }
                   4284: }
                   4285: 
1.1164    raeburn  4286: sub embedded_dependency {
                   4287:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4288:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4289:         if (($identifier ne '') &&
                   4290:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4291:             ($pathfrom ne '')) {
                   4292:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4293:             foreach my $dep (@{$related->{$identifier}}) {
                   4294:                 &add_filetype($allfiles,$path.$dep,'object');
                   4295:             }
                   4296:         }
                   4297:     }
                   4298:     return;
                   4299: }
                   4300: 
1.493     albertel 4301: sub removeuploadedurl {
1.984     neumanie 4302:     my ($url)=@_;	
                   4303:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4304:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4305: }
                   4306: 
                   4307: sub removeuserfile {
                   4308:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4309:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4310:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4311:     if ($result eq 'ok') {	
1.798     raeburn  4312:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4313:             my $metafile = $fname.'.meta';
                   4314:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4315: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4316:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4317:             my $sqlresult = 
1.823     albertel 4318:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4319:                                         'portfolio_metadata',$group,
                   4320:                                         'delete');
1.798     raeburn  4321:         }
                   4322:     }
                   4323:     return $result;
1.257     www      4324: }
1.15      www      4325: 
1.530     albertel 4326: sub mkdiruserfile {
                   4327:     my ($docuname,$docudom,$dir)=@_;
                   4328:     my $home=&homeserver($docuname,$docudom);
                   4329:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4330: }
                   4331: 
1.531     albertel 4332: sub renameuserfile {
                   4333:     my ($docuname,$docudom,$old,$new)=@_;
                   4334:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4335:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4336:                         &escape("$old").':'.&escape("$new"),$home);
                   4337:     if ($result eq 'ok') {
                   4338:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4339:             my $oldmeta = $old.'.meta';
                   4340:             my $newmeta = $new.'.meta';
                   4341:             my $metaresult = 
                   4342:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4343: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4344:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4345:             my $sqlresult = 
1.823     albertel 4346:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4347:                                         'portfolio_metadata',$group,
                   4348:                                         'delete');
1.798     raeburn  4349:         }
                   4350:     }
                   4351:     return $result;
1.531     albertel 4352: }
                   4353: 
1.14      www      4354: # ------------------------------------------------------------------------- Log
                   4355: 
                   4356: sub log {
                   4357:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4358:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4359: }
                   4360: 
                   4361: # ------------------------------------------------------------------ Course Log
1.352     www      4362: #
                   4363: # This routine flushes several buffers of non-mission-critical nature
                   4364: #
1.157     www      4365: 
                   4366: sub flushcourselogs {
1.352     www      4367:     &logthis('Flushing log buffers');
                   4368: #
                   4369: # course logs
                   4370: # This is a log of all transactions in a course, which can be used
                   4371: # for data mining purposes
                   4372: #
                   4373: # It also collects the courseid database, which lists last transaction
                   4374: # times and course titles for all courseids
                   4375: #
                   4376:     my %courseidbuffer=();
1.921     raeburn  4377:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4378:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4379: 		          &escape($courselogs{$crsid}),
                   4380: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4381: 	    delete $courselogs{$crsid};
                   4382:         } else {
                   4383:             &logthis('Failed to flush log buffer for '.$crsid);
                   4384:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4385:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4386:                         " exceeded maximum size, deleting.</font>");
                   4387:                delete $courselogs{$crsid};
                   4388:             }
1.352     www      4389:         }
1.920     raeburn  4390:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4391:             'description' => $coursedescrbuf{$crsid},
                   4392:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4393:             'type'        => $coursetypebuf{$crsid},
                   4394:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4395:         };
1.191     harris41 4396:     }
1.352     www      4397: #
                   4398: # Write course id database (reverse lookup) to homeserver of courses 
                   4399: # Is used in pickcourse
                   4400: #
1.840     albertel 4401:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4402:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4403:                                     $courseidbuffer{$crs_home},
                   4404:                                     $crs_home,'timeonly');
1.352     www      4405:     }
                   4406: #
                   4407: # File accesses
                   4408: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4409: #
1.449     matthew  4410:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4411:         if ($entry =~ /___count$/) {
                   4412:             my ($dom,$name);
1.807     albertel 4413:             ($dom,$name,undef)=
1.811     albertel 4414: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4415:             if (! defined($dom) || $dom eq '' || 
                   4416:                 ! defined($name) || $name eq '') {
1.620     albertel 4417:                 my $cid = $env{'request.course.id'};
                   4418:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4419:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4420:             }
1.450     matthew  4421:             my $value = $accesshash{$entry};
                   4422:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4423:             my %temphash=($url => $value);
1.449     matthew  4424:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4425:             if ($result eq 'ok') {
                   4426:                 delete $accesshash{$entry};
                   4427:             }
                   4428:         } else {
1.811     albertel 4429:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4430:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4431:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4432:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4433:                 delete $accesshash{$entry};
                   4434:             }
1.185     www      4435:         }
1.191     harris41 4436:     }
1.352     www      4437: #
                   4438: # Roles
                   4439: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4440: #
1.800     albertel 4441:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4442:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4443: 	    split(/\:/,$entry);
                   4444:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4445:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4446:                 $rudom,$runame) eq 'ok') {
                   4447: 	    delete $userrolehash{$entry};
                   4448:         }
                   4449:     }
1.662     raeburn  4450: #
1.1334    raeburn  4451: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4452: #
                   4453:     my %domrolebuffer = ();
1.1000    raeburn  4454:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4455:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4456:         if ($domrolebuffer{$rudom}) {
                   4457:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4458:                       '='.&escape($domainrolehash{$entry});
                   4459:         } else {
                   4460:             $domrolebuffer{$rudom}.=&escape($entry).
                   4461:                       '='.&escape($domainrolehash{$entry});
                   4462:         }
                   4463:         delete $domainrolehash{$entry};
                   4464:     }
                   4465:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4466: 	my %servers;
                   4467: 	if (defined(&domain($dom,'primary'))) {
                   4468: 	    my $primary=&domain($dom,'primary');
                   4469: 	    my $hostname=&hostname($primary);
                   4470: 	    $servers{$primary} = $hostname;
                   4471: 	} else { 
                   4472: 	    %servers = &get_servers($dom,'library');
                   4473: 	}
1.841     albertel 4474: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4475: 	    if (&reply('domroleput:'.$dom.':'.
                   4476: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4477: 		last;
                   4478: 	    } else {  
1.841     albertel 4479: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4480: 	    }
1.662     raeburn  4481:         }
                   4482:     }
1.186     www      4483:     $dumpcount++;
1.157     www      4484: }
                   4485: 
                   4486: sub courselog {
                   4487:     my $what=shift;
1.158     www      4488:     $what=time.':'.$what;
1.620     albertel 4489:     unless ($env{'request.course.id'}) { return ''; }
                   4490:     $coursedombuf{$env{'request.course.id'}}=
                   4491:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4492:     $coursenumbuf{$env{'request.course.id'}}=
                   4493:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4494:     $coursehombuf{$env{'request.course.id'}}=
                   4495:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4496:     $coursedescrbuf{$env{'request.course.id'}}=
                   4497:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4498:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4499:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4500:     $courseownerbuf{$env{'request.course.id'}}=
                   4501:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4502:     $coursetypebuf{$env{'request.course.id'}}=
                   4503:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4504:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4505: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4506:     } else {
1.620     albertel 4507: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4508:     }
1.620     albertel 4509:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4510: 	&flushcourselogs();
                   4511:     }
1.158     www      4512: }
                   4513: 
                   4514: sub courseacclog {
                   4515:     my $fnsymb=shift;
1.620     albertel 4516:     unless ($env{'request.course.id'}) { return ''; }
                   4517:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4518:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4519:         $what.=':POST';
1.583     matthew  4520:         # FIXME: Probably ought to escape things....
1.800     albertel 4521: 	foreach my $key (keys(%env)) {
                   4522:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4523:                 my $formitem = $1;
                   4524:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4525:                     $what.=':'.$formitem.'='.$env{$key};
                   4526:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4527:                     $what.=':'.$formitem.'='.$env{$key};
                   4528:                 }
1.158     www      4529:             }
1.191     harris41 4530:         }
1.583     matthew  4531:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4532:         # FIXME: We should not be depending on a form parameter that someone
                   4533:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4534:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4535:             $what.= ':POST';
                   4536:             # FIXME: Probably ought to escape things....
                   4537:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4538:                                  'crsdiscuss') {
1.620     albertel 4539:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4540:             }
                   4541:         }
1.158     www      4542:     }
                   4543:     &courselog($what);
1.149     www      4544: }
                   4545: 
1.185     www      4546: sub countacc {
                   4547:     my $url=&declutter(shift);
1.458     matthew  4548:     return if (! defined($url) || $url eq '');
1.620     albertel 4549:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4550: #
                   4551: # Mark that this url was used in this course
                   4552: #
1.620     albertel 4553:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4554: #
                   4555: # Increase the access count for this resource in this child process
                   4556: #
1.281     www      4557:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4558:     $accesshash{$key}++;
1.185     www      4559: }
1.349     www      4560: 
1.361     www      4561: sub linklog {
                   4562:     my ($from,$to)=@_;
                   4563:     $from=&declutter($from);
                   4564:     $to=&declutter($to);
                   4565:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4566:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4567: }
1.1160    www      4568: 
                   4569: sub statslog {
                   4570:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4571:     if ($users<2) { return; }
                   4572:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4573:             'course'       => $env{'request.course.id'},
                   4574:             'sections'     => '"all"',
                   4575:             'num_students' => $users,
                   4576:             'part'         => $part,
                   4577:             'symb'         => $symb,
                   4578:             'mean_tries'   => $av_attempts,
                   4579:             'deg_of_diff'  => $degdiff});
                   4580:     foreach my $key (keys(%dynstore)) {
                   4581:         $accesshash{$key}=$dynstore{$key};
                   4582:     }
                   4583: }
1.361     www      4584:   
1.349     www      4585: sub userrolelog {
                   4586:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4587:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4588:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4589:        $userrolehash
                   4590:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4591:                     =$tend.':'.$tstart;
1.662     raeburn  4592:     }
1.1169    droeschl 4593:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4594:        $userrolehash
                   4595:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4596:                     =$tend.':'.$tstart;
                   4597:     }
1.1334    raeburn  4598:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4599:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4600:        $domainrolehash
                   4601:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4602:                     = $tend.':'.$tstart;
                   4603:     }
1.351     www      4604: }
                   4605: 
1.957     raeburn  4606: sub courserolelog {
                   4607:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4608:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4609:         my $cdom = $1;
                   4610:         my $cnum = $2;
                   4611:         my $sec = $3;
                   4612:         my $namespace = 'rolelog';
                   4613:         my %storehash = (
                   4614:                            role    => $trole,
                   4615:                            start   => $tstart,
                   4616:                            end     => $tend,
                   4617:                            selfenroll => $selfenroll,
                   4618:                            context    => $context,
                   4619:                         );
                   4620:         if ($trole eq 'gr') {
                   4621:             $namespace = 'groupslog';
                   4622:             $storehash{'group'} = $sec;
                   4623:         } else {
                   4624:             $storehash{'section'} = $sec;
                   4625:         }
1.1188    raeburn  4626:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4627:                    $domain,$cnum,$cdom);
1.1184    raeburn  4628:         if (($trole ne 'st') || ($sec ne '')) {
                   4629:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4630:         }
                   4631:     }
                   4632:     return;
                   4633: }
                   4634: 
1.1184    raeburn  4635: sub domainrolelog {
                   4636:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4637:     if ($area =~ m{^/($match_domain)/$}) {
                   4638:         my $cdom = $1;
                   4639:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4640:         my $namespace = 'rolelog';
                   4641:         my %storehash = (
                   4642:                            role    => $trole,
                   4643:                            start   => $tstart,
                   4644:                            end     => $tend,
                   4645:                            context => $context,
                   4646:                         );
1.1188    raeburn  4647:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4648:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4649:     }
                   4650:     return;
                   4651: 
                   4652: }
                   4653: 
                   4654: sub coauthorrolelog {
                   4655:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4656:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4657:         my $audom = $1;
                   4658:         my $auname = $2;
                   4659:         my $namespace = 'rolelog';
                   4660:         my %storehash = (
                   4661:                            role    => $trole,
                   4662:                            start   => $tstart,
                   4663:                            end     => $tend,
                   4664:                            context => $context,
                   4665:                         );
1.1188    raeburn  4666:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4667:                    $domain,$auname,$audom);
1.1184    raeburn  4668:     }
                   4669:     return;
                   4670: }
                   4671: 
1.351     www      4672: sub get_course_adv_roles {
1.948     raeburn  4673:     my ($cid,$codes) = @_;
1.620     albertel 4674:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4675:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4676:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4677:     my %nothide=();
1.800     albertel 4678:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4679:         if ($user !~ /:/) {
                   4680: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4681:         } else {
                   4682:             $nothide{$user}=1;
                   4683:         }
1.470     www      4684:     }
1.1219    raeburn  4685:     my @possdoms = ($coursehash{'domain'});
                   4686:     if ($coursehash{'checkforpriv'}) {
                   4687:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4688:     }
1.351     www      4689:     my %returnhash=();
                   4690:     my %dumphash=
                   4691:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4692:     my $now=time;
1.997     raeburn  4693:     my %privileged;
1.1000    raeburn  4694:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4695: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4696:         if (($tstart) && ($tstart<0)) { next; }
                   4697:         if (($tend) && ($tend<$now)) { next; }
                   4698:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4699:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4700: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4701:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4702:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4703: 	if ($role eq 'cr') { next; }
1.948     raeburn  4704:         if ($codes) {
                   4705:             if ($section) { $role .= ':'.$section; }
                   4706:             if ($returnhash{$role}) {
                   4707:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4708:             } else {
                   4709:                 $returnhash{$role}=$username.':'.$domain;
                   4710:             }
1.351     www      4711:         } else {
1.988     raeburn  4712:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4713:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4714:             if ($returnhash{$key}) {
                   4715: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4716:             } else {
                   4717:                 $returnhash{$key}=$username.':'.$domain;
                   4718:             }
1.351     www      4719:         }
1.948     raeburn  4720:     }
1.400     www      4721:     return %returnhash;
                   4722: }
                   4723: 
                   4724: sub get_my_roles {
1.937     raeburn  4725:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4726:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4727:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4728:     my (%dumphash,%nothide);
1.1086    raeburn  4729:     if ($context eq 'userroles') {
1.1166    raeburn  4730:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4731:     } else {
1.1219    raeburn  4732:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4733:         if ($hidepriv) {
                   4734:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4735:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4736:                 if ($user !~ /:/) {
                   4737:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4738:                 } else {
                   4739:                     $nothide{$user} = 1;
                   4740:                 }
                   4741:             }
                   4742:         }
1.858     raeburn  4743:     }
1.400     www      4744:     my %returnhash=();
                   4745:     my $now=time;
1.999     raeburn  4746:     my %privileged;
1.800     albertel 4747:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4748:         my ($role,$tend,$tstart);
                   4749:         if ($context eq 'userroles') {
1.1149    raeburn  4750:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4751: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4752:         } else {
                   4753:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4754:         }
1.400     www      4755:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4756:         my $status = 'active';
1.939     raeburn  4757:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4758:             $status = 'previous';
                   4759:         } 
                   4760:         if (($tstart) && ($now<$tstart)) {
                   4761:             $status = 'future';
                   4762:         }
                   4763:         if (ref($types) eq 'ARRAY') {
                   4764:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4765:                 next;
                   4766:             } 
                   4767:         } else {
                   4768:             if ($status ne 'active') {
                   4769:                 next;
                   4770:             }
                   4771:         }
1.867     raeburn  4772:         my ($rolecode,$username,$domain,$section,$area);
                   4773:         if ($context eq 'userroles') {
1.1186    raeburn  4774:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4775:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4776:         } else {
                   4777:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4778:         }
1.832     raeburn  4779:         if (ref($roledoms) eq 'ARRAY') {
                   4780:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4781:                 next;
                   4782:             }
                   4783:         }
                   4784:         if (ref($roles) eq 'ARRAY') {
                   4785:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4786:                 if ($role =~ /^cr\//) {
                   4787:                     if (!grep(/^cr$/,@{$roles})) {
                   4788:                         next;
                   4789:                     }
1.1104    raeburn  4790:                 } elsif ($role =~ /^gr\//) {
                   4791:                     if (!grep(/^gr$/,@{$roles})) {
                   4792:                         next;
                   4793:                     }
1.922     raeburn  4794:                 } else {
                   4795:                     next;
                   4796:                 }
1.832     raeburn  4797:             }
1.867     raeburn  4798:         }
1.937     raeburn  4799:         if ($hidepriv) {
1.1219    raeburn  4800:             my @privroles = ('dc','su');
1.999     raeburn  4801:             if ($context eq 'userroles') {
1.1219    raeburn  4802:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4803:             } else {
1.1219    raeburn  4804:                 my $possdoms = [$domain];
                   4805:                 if (ref($roledoms) eq 'ARRAY') {
                   4806:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4807:                 }
1.1219    raeburn  4808:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4809:                     if (!$nothide{$username.':'.$domain}) {
                   4810:                         next;
                   4811:                     }
                   4812:                 }
1.937     raeburn  4813:             }
                   4814:         }
1.933     raeburn  4815:         if ($withsec) {
                   4816:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4817:                 $tstart.':'.$tend;
                   4818:         } else {
                   4819:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4820:         }
1.832     raeburn  4821:     }
1.373     www      4822:     return %returnhash;
1.399     www      4823: }
                   4824: 
1.1333    raeburn  4825: sub get_all_adhocroles {
                   4826:     my ($dom) = @_;
                   4827:     my @roles_by_num = ();
                   4828:     my %domdefaults = &get_domain_defaults($dom);
                   4829:     my (%description,%access_in_dom,%access_info);
                   4830:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4831:         my $count = 0;
                   4832:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4833:         my %ordered;
                   4834:         foreach my $role (sort(keys(%domcurrent))) {
                   4835:             my ($order,$desc,$access_in_dom);
                   4836:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4837:                 $order = $domcurrent{$role}{'order'};
                   4838:                 $desc = $domcurrent{$role}{'desc'};
                   4839:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4840:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4841:             }
                   4842:             if ($order eq '') {
                   4843:                 $order = $count;
                   4844:             }
                   4845:             $ordered{$order} = $role;
                   4846:             if ($desc ne '') {
                   4847:                 $description{$role} = $desc;
                   4848:             } else {
                   4849:                 $description{$role}= $role;
                   4850:             }
                   4851:             $count++;
                   4852:         }
                   4853:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4854:             push(@roles_by_num,$ordered{$item});
                   4855:         }
                   4856:     }
                   4857:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4858: }
                   4859: 
1.1332    raeburn  4860: sub get_my_adhocroles {
1.1333    raeburn  4861:     my ($cid,$checkreg) = @_;
                   4862:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4863:     if ($env{'request.course.id'} eq $cid) {
                   4864:         $cdom = $env{'course.'.$cid.'.domain'};
                   4865:         $cnum = $env{'course.'.$cid.'.num'};
                   4866:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4867:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4868:         $cdom = $1;
                   4869:         $cnum = $2;
                   4870:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4871:                                      $cdom,$cnum);
                   4872:     }
                   4873:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4874:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4875:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4876:         if ($rosterhash{$user} ne '') {
                   4877:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4878:             return ([],{}) if ($type eq 'auto');
                   4879:         }
                   4880:     }
                   4881:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4882:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4883:             my $then=$env{'user.login.time'};
                   4884:             my $update=$env{'user.update.time'};
1.1335    raeburn  4885:             if (!$update) {
                   4886:                 $update = $then;
                   4887:             }
                   4888:             my @liveroles;
1.1334    raeburn  4889:             foreach my $role ('dh','da') {
                   4890:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4891:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4892:                     my $limit = $update;
                   4893:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4894:                         $limit = $then;
                   4895:                     }
1.1335    raeburn  4896:                     my $activerole = 1;
                   4897:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4898:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4899:                     if ($activerole) {
                   4900:                         push(@liveroles,$role);
                   4901:                     }
1.1334    raeburn  4902:                 }
1.1332    raeburn  4903:             }
1.1335    raeburn  4904:             if (@liveroles) {
1.1332    raeburn  4905:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4906:                     my ($accessref,$accessinfo,%access_in_dom);
                   4907:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4908:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4909:                         if (@{$roles_by_num}) {
1.1332    raeburn  4910:                             my %settings;
                   4911:                             if ($env{'request.course.id'} eq $cid) {
                   4912:                                 foreach my $envkey (keys(%env)) {
                   4913:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4914:                                         $settings{$1} = $env{$envkey};
                   4915:                                     }
                   4916:                                 }
                   4917:                             } else {
                   4918:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4919:                             }
                   4920:                             my %setincrs;
                   4921:                             if ($settings{'internal.adhocaccess'}) {
                   4922:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4923:                             }
                   4924:                             my @statuses;
                   4925:                             if ($env{'environment.inststatus'}) {
                   4926:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4927:                             }
                   4928:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4929:                             if (ref($accessref) eq 'HASH') {
                   4930:                                 %access_in_dom = %{$accessref};
                   4931:                             }
                   4932:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4933:                                 my ($curraccess,@okstatus,@personnel);
                   4934:                                 if ($setincrs{$role}) {
                   4935:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4936:                                     if ($curraccess eq 'status') {
                   4937:                                         @okstatus = split(/\&/,$rest);
                   4938:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4939:                                         @personnel = split(/\&/,$rest);
                   4940:                                     }
                   4941:                                 } else {
                   4942:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4943:                                     if (ref($accessinfo) eq 'HASH') {
                   4944:                                         if ($curraccess eq 'status') {
                   4945:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4946:                                                 @okstatus = @{$accessinfo->{$role}};
                   4947:                                             }
                   4948:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4949:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4950:                                                 @personnel = @{$accessinfo->{$role}};
                   4951:                                             }
1.1332    raeburn  4952:                                         }
                   4953:                                     }
                   4954:                                 }
                   4955:                                 if ($curraccess eq 'none') {
                   4956:                                     next;
                   4957:                                 } elsif ($curraccess eq 'all') {
                   4958:                                     push(@possroles,$role);
1.1336    raeburn  4959:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4960:                                     if (grep(/^dh$/,@liveroles)) {
                   4961:                                         push(@possroles,$role);
                   4962:                                     } else {
                   4963:                                         next;
                   4964:                                     }
1.1336    raeburn  4965:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4966:                                     if (grep(/^da$/,@liveroles)) {
                   4967:                                         push(@possroles,$role);
                   4968:                                     } else {
                   4969:                                         next;
                   4970:                                     }
1.1332    raeburn  4971:                                 } elsif ($curraccess eq 'status') {
                   4972:                                     if (@okstatus) {
                   4973:                                         if (!@statuses) {
                   4974:                                             if (grep(/^default$/,@okstatus)) {
                   4975:                                                 push(@possroles,$role);
                   4976:                                             }
                   4977:                                         } else {
                   4978:                                             foreach my $status (@okstatus) {
                   4979:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4980:                                                     push(@possroles,$role);
                   4981:                                                     last;
                   4982:                                                 }
                   4983:                                             }
                   4984:                                         }
                   4985:                                     }
                   4986:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4987:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4988:                                         if ($curraccess eq 'exc') {
                   4989:                                             push(@possroles,$role);
                   4990:                                         }
                   4991:                                     } elsif ($curraccess eq 'inc') {
                   4992:                                         push(@possroles,$role);
                   4993:                                     }
                   4994:                                 }
                   4995:                             }
                   4996:                         }
                   4997:                     }
                   4998:                 }
                   4999:             }
                   5000:         }
                   5001:     }
1.1333    raeburn  5002:     unless (ref($description) eq 'HASH') {
                   5003:         if (ref($roles_by_num) eq 'ARRAY') {
                   5004:             my %desc;
                   5005:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5006:             $description = \%desc;
                   5007:         } else {
                   5008:             $description = {};
                   5009:         }
                   5010:     }
                   5011:     return (\@possroles,$description);
1.1332    raeburn  5012: }
                   5013: 
1.399     www      5014: # ----------------------------------------------------- Frontpage Announcements
                   5015: #
                   5016: #
                   5017: 
                   5018: sub postannounce {
                   5019:     my ($server,$text)=@_;
1.844     albertel 5020:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5021:     unless ($text=~/\w/) { $text=''; }
                   5022:     return &reply('setannounce:'.&escape($text),$server);
                   5023: }
                   5024: 
                   5025: sub getannounce {
1.448     albertel 5026: 
1.1359    raeburn  5027:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5028: 	my $announcement='';
1.800     albertel 5029: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5030: 	close($fh);
1.399     www      5031: 	if ($announcement=~/\w/) { 
                   5032: 	    return 
                   5033:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5034:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5035: 	} else {
                   5036: 	    return '';
                   5037: 	}
                   5038:     } else {
                   5039: 	return '';
                   5040:     }
1.351     www      5041: }
1.353     www      5042: 
                   5043: # ---------------------------------------------------------- Course ID routines
                   5044: # Deal with domain's nohist_courseid.db files
                   5045: #
                   5046: 
                   5047: sub courseidput {
1.921     raeburn  5048:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5049:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5050:     my $outcome;
                   5051:     if ($caller eq 'timeonly') {
                   5052:         my $cids = '';
                   5053:         foreach my $item (keys(%$storehash)) {
                   5054:             $cids.=&escape($item).'&';
                   5055:         }
                   5056:         $cids=~s/\&$//;
                   5057:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5058:                           $coursehome);       
                   5059:     } else {
                   5060:         my $items = '';
                   5061:         foreach my $item (keys(%$storehash)) {
                   5062:             $items.= &escape($item).'='.
                   5063:                      &freeze_escape($$storehash{$item}).'&';
                   5064:         }
                   5065:         $items=~s/\&$//;
                   5066:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5067:                           $coursehome);
1.918     raeburn  5068:     }
                   5069:     if ($outcome eq 'unknown_cmd') {
                   5070:         my $what;
                   5071:         foreach my $cid (keys(%$storehash)) {
                   5072:             $what .= &escape($cid).'=';
1.921     raeburn  5073:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5074:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5075:             }
                   5076:             $what =~ s/\:$/&/;
                   5077:         }
                   5078:         $what =~ s/\&$//;  
                   5079:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5080:     } else {
                   5081:         return $outcome;
                   5082:     }
1.353     www      5083: }
                   5084: 
                   5085: sub courseiddump {
1.921     raeburn  5086:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5087:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5088:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5089:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5090:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5091:     my $as_hash = 1;
                   5092:     my %returnhash;
                   5093:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5094:     my %libserv = &all_library();
                   5095:     foreach my $tryserver (keys(%libserv)) {
                   5096:         if ( (  $hostidflag == 1 
                   5097: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5098: 	     || (!defined($hostidflag)) ) {
                   5099: 
1.918     raeburn  5100: 	    if (($domfilter eq '') ||
                   5101: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5102:                 my $rep;
                   5103:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5104:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5105:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5106:                                 &escape($descfilter), &escape($instcodefilter), 
                   5107:                                 &escape($ownerfilter), &escape($coursefilter),
                   5108:                                 &escape($typefilter), &escape($regexp_ok), 
                   5109:                                 $as_hash, &escape($selfenrollonly), 
                   5110:                                 &escape($catfilter), $showhidden, $caller, 
                   5111:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5112:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5113:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5114:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5115:                 } else {
                   5116:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5117:                              $sincefilter.':'.&escape($descfilter).':'.
                   5118:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5119:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5120:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5121:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5122:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5123:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5124:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5125:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5126:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5127:                 }
                   5128:                      
1.918     raeburn  5129:                 my @pairs=split(/\&/,$rep);
                   5130:                 foreach my $item (@pairs) {
                   5131:                     my ($key,$value)=split(/\=/,$item,2);
                   5132:                     $key = &unescape($key);
                   5133:                     next if ($key =~ /^error: 2 /);
                   5134:                     my $result = &thaw_unescape($value);
                   5135:                     if (ref($result) eq 'HASH') {
                   5136:                         $returnhash{$key}=$result;
                   5137:                     } else {
1.921     raeburn  5138:                         my @responses = split(/:/,$value);
                   5139:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5140:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5141:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5142:                         }
1.1008    raeburn  5143:                     }
1.353     www      5144:                 }
                   5145:             }
                   5146:         }
                   5147:     }
                   5148:     return %returnhash;
                   5149: }
                   5150: 
1.1055    raeburn  5151: sub courselastaccess {
                   5152:     my ($cdom,$cnum,$hostidref) = @_;
                   5153:     my %returnhash;
                   5154:     if ($cdom && $cnum) {
                   5155:         my $chome = &homeserver($cnum,$cdom);
                   5156:         if ($chome ne 'no_host') {
                   5157:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5158:             &extract_lastaccess(\%returnhash,$rep);
                   5159:         }
                   5160:     } else {
                   5161:         if (!$cdom) { $cdom=''; }
                   5162:         my %libserv = &all_library();
                   5163:         foreach my $tryserver (keys(%libserv)) {
                   5164:             if (ref($hostidref) eq 'ARRAY') {
                   5165:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5166:             } 
                   5167:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5168:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5169:                 &extract_lastaccess(\%returnhash,$rep);
                   5170:             }
                   5171:         }
                   5172:     }
                   5173:     return %returnhash;
                   5174: }
                   5175: 
                   5176: sub extract_lastaccess {
                   5177:     my ($returnhash,$rep) = @_;
                   5178:     if (ref($returnhash) eq 'HASH') {
                   5179:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5180:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5181:                  $rep eq '') {
                   5182:             my @pairs=split(/\&/,$rep);
                   5183:             foreach my $item (@pairs) {
                   5184:                 my ($key,$value)=split(/\=/,$item,2);
                   5185:                 $key = &unescape($key);
                   5186:                 next if ($key =~ /^error: 2 /);
                   5187:                 $returnhash->{$key} = &thaw_unescape($value);
                   5188:             }
                   5189:         }
                   5190:     }
                   5191:     return;
                   5192: }
                   5193: 
1.658     raeburn  5194: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5195: 
                   5196: sub dcmailput {
1.685     raeburn  5197:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5198:     my $status = &Apache::lonnet::critical(
1.740     www      5199:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5200:        &escape($message),$server);
1.662     raeburn  5201:     return $status;
                   5202: }
                   5203: 
1.658     raeburn  5204: sub dcmaildump {
                   5205:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5206:     my %returnhash=();
1.846     albertel 5207: 
                   5208:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5209:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5210:                                                          &escape($enddate).':';
                   5211: 	my @esc_senders=map { &escape($_)} @$senders;
                   5212: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5213: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5214:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5215:             if (($key) && ($value)) {
                   5216:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5217:             }
                   5218:         }
                   5219:     }
                   5220:     return %returnhash;
                   5221: }
1.662     raeburn  5222: # ---------------------------------------------------------- Domain roles
                   5223: 
                   5224: sub get_domain_roles {
                   5225:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5226:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5227:         $startdate = '.';
                   5228:     }
1.1018    raeburn  5229:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5230:         $enddate = '.';
                   5231:     }
1.922     raeburn  5232:     my $rolelist;
                   5233:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5234:         $rolelist = join('&',@{$roles});
1.922     raeburn  5235:     }
1.662     raeburn  5236:     my %personnel = ();
1.841     albertel 5237: 
                   5238:     my %servers = &get_servers($dom,'library');
                   5239:     foreach my $tryserver (keys(%servers)) {
                   5240: 	%{$personnel{$tryserver}}=();
                   5241: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5242: 					    &escape($startdate).':'.
                   5243: 					    &escape($enddate).':'.
                   5244: 					    &escape($rolelist), $tryserver))) {
                   5245: 	    my ($key,$value) = split(/\=/,$line,2);
                   5246: 	    if (($key) && ($value)) {
                   5247: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5248: 	    }
                   5249: 	}
1.662     raeburn  5250:     }
                   5251:     return %personnel;
                   5252: }
1.658     raeburn  5253: 
1.1332    raeburn  5254: sub get_active_domroles {
                   5255:     my ($dom,$roles) = @_;
                   5256:     return () unless (ref($roles) eq 'ARRAY');
                   5257:     my $now = time;
                   5258:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5259:     my %domroles;
                   5260:     foreach my $server (keys(%dompersonnel)) {
                   5261:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5262:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5263:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5264:         }
                   5265:     }
                   5266:     return %domroles;
                   5267: }
                   5268: 
1.1057    www      5269: # ----------------------------------------------------------- Interval timing 
1.149     www      5270: 
1.1153    www      5271: {
                   5272: # Caches needed for speedup of navmaps
                   5273: # We don't want to cache this for very long at all (5 seconds at most)
                   5274: # 
                   5275: # The user for whom we cache
                   5276: my $cachedkey='';
                   5277: # The cached times for this user
                   5278: my %cachedtimes=();
                   5279: # When this was last done
1.1282    raeburn  5280: my $cachedtime='';
1.1153    www      5281: 
                   5282: sub load_all_first_access {
1.1308    raeburn  5283:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5284:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5285:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5286:         (!$ignorecache)) {
1.1154    raeburn  5287:         return;
                   5288:     }
                   5289:     $cachedtime=time;
                   5290:     $cachedkey=$uname.':'.$udom;
                   5291:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5292: }
                   5293: 
1.504     albertel 5294: sub get_first_access {
1.1308    raeburn  5295:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5296:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5297:     if ($argsymb) { $symb=$argsymb; }
                   5298:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5299:     if ($argmap) { $map = $argmap; }
1.926     albertel 5300:     if ($type eq 'course') {
                   5301: 	$res='course';
                   5302:     } elsif ($type eq 'map') {
1.588     albertel 5303: 	$res=&symbread($map);
                   5304:     } else {
                   5305: 	$res=$symb;
                   5306:     }
1.1308    raeburn  5307:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5308:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5309: }
                   5310: 
                   5311: sub set_first_access {
1.1162    raeburn  5312:     my ($type,$interval)=@_;
1.790     albertel 5313:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5314:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5315:     if ($type eq 'course') {
                   5316: 	$res='course';
                   5317:     } elsif ($type eq 'map') {
1.588     albertel 5318: 	$res=&symbread($map);
                   5319:     } else {
                   5320: 	$res=$symb;
                   5321:     }
1.1153    www      5322:     $cachedkey='';
1.1162    raeburn  5323:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5324:     if ($firstaccess) {
                   5325:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5326:                  "to set new value (type: $type, extent: $res) for $uname:$udom ". 
                   5327:                  "in $courseid"); 
                   5328:         return 'already_set';
                   5329:     } else {
1.1162    raeburn  5330:         my $start = time;
                   5331: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5332:                           $udom,$uname);
                   5333:         if ($putres eq 'ok') {
                   5334:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5335:                  $udom,$uname); 
                   5336:             &appenv(
                   5337:                      {
                   5338:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5339:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5340:                      }
                   5341:                   );
1.1365    raeburn  5342:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5343:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5344:             }
1.1386    raeburn  5345:         } elsif ($putres ne 'refused') {
                   5346:             &logthis("Result: $putres when attempting to set first access time ".
                   5347:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5348:         }
                   5349:         return $putres;
1.505     albertel 5350:     }
                   5351:     return 'already_set';
1.504     albertel 5352: }
1.1153    www      5353: }
1.1282    raeburn  5354: 
1.110     www      5355: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5356: 
                   5357: sub expirespread {
                   5358:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5359:     my $cid=$env{'request.course.id'}; 
1.110     www      5360:     if ($cid) {
                   5361:        my $now=time;
                   5362:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5363:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5364:                             $env{'course.'.$cid.'.num'}.
1.110     www      5365: 	        	    ':nohist_expirationdates:'.
                   5366:                             &escape($key).'='.$now,
1.620     albertel 5367:                             $env{'course.'.$cid.'.home'})
1.110     www      5368:     }
                   5369:     return 'ok';
1.14      www      5370: }
                   5371: 
1.109     www      5372: # ----------------------------------------------------- Devalidate Spreadsheets
                   5373: 
                   5374: sub devalidate {
1.325     www      5375:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5376:     my $cid=$env{'request.course.id'}; 
1.109     www      5377:     if ($cid) {
1.391     matthew  5378:         # delete the stored spreadsheets for
                   5379:         # - the student level sheet of this user in course's homespace
                   5380:         # - the assessment level sheet for this resource 
                   5381:         #   for this user in user's homespace
1.553     albertel 5382: 	# - current conditional state info
1.325     www      5383: 	my $key=$uname.':'.$udom.':';
1.109     www      5384:         my $status=
1.299     matthew  5385: 	    &del('nohist_calculatedsheets',
1.391     matthew  5386: 		 [$key.'studentcalc:'],
1.620     albertel 5387: 		 $env{'course.'.$cid.'.domain'},
                   5388: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5389: 		.' '.
                   5390: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5391: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5392:         unless ($status eq 'ok ok') {
                   5393:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5394:                     $uname.' at '.$udom.' for '.
1.109     www      5395: 		    $symb.': '.$status);
1.133     albertel 5396:         }
1.553     albertel 5397: 	&delenv('user.state.'.$cid);
1.109     www      5398:     }
                   5399: }
                   5400: 
1.265     albertel 5401: sub get_scalar {
                   5402:     my ($string,$end) = @_;
                   5403:     my $value;
                   5404:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5405: 	$value = $1;
                   5406:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5407: 	$value = $1;
                   5408:     }
                   5409:     return &unescape($value);
                   5410: }
                   5411: 
                   5412: sub array2str {
                   5413:   my (@array) = @_;
                   5414:   my $result=&arrayref2str(\@array);
                   5415:   $result=~s/^__ARRAY_REF__//;
                   5416:   $result=~s/__END_ARRAY_REF__$//;
                   5417:   return $result;
                   5418: }
                   5419: 
1.204     albertel 5420: sub arrayref2str {
                   5421:   my ($arrayref) = @_;
1.265     albertel 5422:   my $result='__ARRAY_REF__';
1.204     albertel 5423:   foreach my $elem (@$arrayref) {
1.265     albertel 5424:     if(ref($elem) eq 'ARRAY') {
                   5425:       $result.=&arrayref2str($elem).'&';
                   5426:     } elsif(ref($elem) eq 'HASH') {
                   5427:       $result.=&hashref2str($elem).'&';
                   5428:     } elsif(ref($elem)) {
                   5429:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5430:     } else {
                   5431:       $result.=&escape($elem).'&';
                   5432:     }
                   5433:   }
                   5434:   $result=~s/\&$//;
1.265     albertel 5435:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5436:   return $result;
                   5437: }
                   5438: 
1.168     albertel 5439: sub hash2str {
1.204     albertel 5440:   my (%hash) = @_;
                   5441:   my $result=&hashref2str(\%hash);
1.265     albertel 5442:   $result=~s/^__HASH_REF__//;
                   5443:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5444:   return $result;
                   5445: }
                   5446: 
                   5447: sub hashref2str {
                   5448:   my ($hashref)=@_;
1.265     albertel 5449:   my $result='__HASH_REF__';
1.800     albertel 5450:   foreach my $key (sort(keys(%$hashref))) {
                   5451:     if (ref($key) eq 'ARRAY') {
                   5452:       $result.=&arrayref2str($key).'=';
                   5453:     } elsif (ref($key) eq 'HASH') {
                   5454:       $result.=&hashref2str($key).'=';
                   5455:     } elsif (ref($key)) {
1.265     albertel 5456:       $result.='=';
1.800     albertel 5457:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5458:     } else {
1.1132    raeburn  5459: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5460:     }
                   5461: 
1.800     albertel 5462:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5463:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5464:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5465:       $result.=&hashref2str($hashref->{$key}).'&';
                   5466:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5467:        $result.='&';
1.800     albertel 5468:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5469:     } else {
1.800     albertel 5470:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5471:     }
                   5472:   }
1.168     albertel 5473:   $result=~s/\&$//;
1.265     albertel 5474:   $result .= '__END_HASH_REF__';
1.168     albertel 5475:   return $result;
                   5476: }
                   5477: 
                   5478: sub str2hash {
1.265     albertel 5479:     my ($string)=@_;
                   5480:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5481:     return %$hash;
                   5482: }
                   5483: 
                   5484: sub str2hashref {
1.168     albertel 5485:   my ($string) = @_;
1.265     albertel 5486: 
                   5487:   my %hash;
                   5488: 
                   5489:   if($string !~ /^__HASH_REF__/) {
                   5490:       if (! ($string eq '' || !defined($string))) {
                   5491: 	  $hash{'error'}='Not hash reference';
                   5492:       }
                   5493:       return (\%hash, $string);
                   5494:   }
                   5495: 
                   5496:   $string =~ s/^__HASH_REF__//;
                   5497: 
                   5498:   while($string !~ /^__END_HASH_REF__/) {
                   5499:       #key
                   5500:       my $key='';
                   5501:       if($string =~ /^__HASH_REF__/) {
                   5502:           ($key, $string)=&str2hashref($string);
                   5503:           if(defined($key->{'error'})) {
                   5504:               $hash{'error'}='Bad data';
                   5505:               return (\%hash, $string);
                   5506:           }
                   5507:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5508:           ($key, $string)=&str2arrayref($string);
                   5509:           if($key->[0] eq 'Array reference error') {
                   5510:               $hash{'error'}='Bad data';
                   5511:               return (\%hash, $string);
                   5512:           }
                   5513:       } else {
                   5514:           $string =~ s/^(.*?)=//;
1.267     albertel 5515: 	  $key=&unescape($1);
1.265     albertel 5516:       }
                   5517:       $string =~ s/^=//;
                   5518: 
                   5519:       #value
                   5520:       my $value='';
                   5521:       if($string =~ /^__HASH_REF__/) {
                   5522:           ($value, $string)=&str2hashref($string);
                   5523:           if(defined($value->{'error'})) {
                   5524:               $hash{'error'}='Bad data';
                   5525:               return (\%hash, $string);
                   5526:           }
                   5527:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5528:           ($value, $string)=&str2arrayref($string);
                   5529:           if($value->[0] eq 'Array reference error') {
                   5530:               $hash{'error'}='Bad data';
                   5531:               return (\%hash, $string);
                   5532:           }
                   5533:       } else {
                   5534: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5535:       }
                   5536:       $string =~ s/^&//;
                   5537: 
                   5538:       $hash{$key}=$value;
1.204     albertel 5539:   }
1.265     albertel 5540: 
                   5541:   $string =~ s/^__END_HASH_REF__//;
                   5542: 
                   5543:   return (\%hash, $string);
1.204     albertel 5544: }
                   5545: 
                   5546: sub str2array {
1.265     albertel 5547:     my ($string)=@_;
                   5548:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5549:     return @$array;
                   5550: }
                   5551: 
                   5552: sub str2arrayref {
1.204     albertel 5553:   my ($string) = @_;
1.265     albertel 5554:   my @array;
                   5555: 
                   5556:   if($string !~ /^__ARRAY_REF__/) {
                   5557:       if (! ($string eq '' || !defined($string))) {
                   5558: 	  $array[0]='Array reference error';
                   5559:       }
                   5560:       return (\@array, $string);
                   5561:   }
                   5562: 
                   5563:   $string =~ s/^__ARRAY_REF__//;
                   5564: 
                   5565:   while($string !~ /^__END_ARRAY_REF__/) {
                   5566:       my $value='';
                   5567:       if($string =~ /^__HASH_REF__/) {
                   5568:           ($value, $string)=&str2hashref($string);
                   5569:           if(defined($value->{'error'})) {
                   5570:               $array[0] ='Array reference error';
                   5571:               return (\@array, $string);
                   5572:           }
                   5573:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5574:           ($value, $string)=&str2arrayref($string);
                   5575:           if($value->[0] eq 'Array reference error') {
                   5576:               $array[0] ='Array reference error';
                   5577:               return (\@array, $string);
                   5578:           }
                   5579:       } else {
                   5580: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5581:       }
                   5582:       $string =~ s/^&//;
                   5583: 
                   5584:       push(@array, $value);
1.191     harris41 5585:   }
1.265     albertel 5586: 
                   5587:   $string =~ s/^__END_ARRAY_REF__//;
                   5588: 
                   5589:   return (\@array, $string);
1.168     albertel 5590: }
                   5591: 
1.167     albertel 5592: # -------------------------------------------------------------------Temp Store
                   5593: 
1.168     albertel 5594: sub tmpreset {
                   5595:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5596:   if (!$symb) {
                   5597:     $symb=&symbread();
1.620     albertel 5598:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5599:   }
                   5600:   $symb=escape($symb);
                   5601: 
1.620     albertel 5602:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5603:   $namespace=~s/\//\_/g;
                   5604:   $namespace=~s/\W//g;
                   5605: 
1.620     albertel 5606:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5607:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5608:   if ($domain eq 'public' && $stuname eq 'public') {
                   5609:       $stuname=$ENV{'REMOTE_ADDR'};
                   5610:   }
1.1117    foxr     5611:   my $path=LONCAPA::tempdir();
1.168     albertel 5612:   my %hash;
                   5613:   if (tie(%hash,'GDBM_File',
                   5614: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5615: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5616:     foreach my $key (keys(%hash)) {
1.180     albertel 5617:       if ($key=~ /:$symb/) {
1.168     albertel 5618: 	delete($hash{$key});
                   5619:       }
                   5620:     }
                   5621:   }
                   5622: }
                   5623: 
1.167     albertel 5624: sub tmpstore {
1.168     albertel 5625:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5626: 
                   5627:   if (!$symb) {
                   5628:     $symb=&symbread();
1.620     albertel 5629:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5630:   }
                   5631:   $symb=escape($symb);
                   5632: 
                   5633:   if (!$namespace) {
                   5634:     # I don't think we would ever want to store this for a course.
                   5635:     # it seems this will only be used if we don't have a course.
1.620     albertel 5636:     #$namespace=$env{'request.course.id'};
1.168     albertel 5637:     #if (!$namespace) {
1.620     albertel 5638:       $namespace=$env{'request.state'};
1.168     albertel 5639:     #}
                   5640:   }
                   5641:   $namespace=~s/\//\_/g;
                   5642:   $namespace=~s/\W//g;
1.620     albertel 5643:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5644:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5645:   if ($domain eq 'public' && $stuname eq 'public') {
                   5646:       $stuname=$ENV{'REMOTE_ADDR'};
                   5647:   }
1.168     albertel 5648:   my $now=time;
                   5649:   my %hash;
1.1117    foxr     5650:   my $path=LONCAPA::tempdir();
1.168     albertel 5651:   if (tie(%hash,'GDBM_File',
                   5652: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5653: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5654:     $hash{"version:$symb"}++;
                   5655:     my $version=$hash{"version:$symb"};
                   5656:     my $allkeys=''; 
                   5657:     foreach my $key (keys(%$storehash)) {
                   5658:       $allkeys.=$key.':';
1.591     albertel 5659:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5660:     }
                   5661:     $hash{"$version:$symb:timestamp"}=$now;
                   5662:     $allkeys.='timestamp';
                   5663:     $hash{"$version:keys:$symb"}=$allkeys;
                   5664:     if (untie(%hash)) {
                   5665:       return 'ok';
                   5666:     } else {
                   5667:       return "error:$!";
                   5668:     }
                   5669:   } else {
                   5670:     return "error:$!";
                   5671:   }
                   5672: }
1.167     albertel 5673: 
1.168     albertel 5674: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5675: 
1.168     albertel 5676: sub tmprestore {
                   5677:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5678: 
1.168     albertel 5679:   if (!$symb) {
                   5680:     $symb=&symbread();
1.620     albertel 5681:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5682:   }
                   5683:   $symb=escape($symb);
                   5684: 
1.620     albertel 5685:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5686: 
1.620     albertel 5687:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5688:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5689:   if ($domain eq 'public' && $stuname eq 'public') {
                   5690:       $stuname=$ENV{'REMOTE_ADDR'};
                   5691:   }
1.168     albertel 5692:   my %returnhash;
                   5693:   $namespace=~s/\//\_/g;
                   5694:   $namespace=~s/\W//g;
                   5695:   my %hash;
1.1117    foxr     5696:   my $path=LONCAPA::tempdir();
1.168     albertel 5697:   if (tie(%hash,'GDBM_File',
                   5698: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5699: 	  &GDBM_READER(),0640)) {
1.168     albertel 5700:     my $version=$hash{"version:$symb"};
                   5701:     $returnhash{'version'}=$version;
                   5702:     my $scope;
                   5703:     for ($scope=1;$scope<=$version;$scope++) {
                   5704:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5705:       my @keys=split(/:/,$vkeys);
                   5706:       my $key;
                   5707:       $returnhash{"$scope:keys"}=$vkeys;
                   5708:       foreach $key (@keys) {
1.591     albertel 5709: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5710: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5711:       }
                   5712:     }
1.168     albertel 5713:     if (!(untie(%hash))) {
                   5714:       return "error:$!";
                   5715:     }
                   5716:   } else {
                   5717:     return "error:$!";
                   5718:   }
                   5719:   return %returnhash;
1.167     albertel 5720: }
                   5721: 
1.9       www      5722: # ----------------------------------------------------------------------- Store
                   5723: 
                   5724: sub store {
1.1269    raeburn  5725:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5726:     my $home='';
                   5727: 
1.168     albertel 5728:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5729: 
1.213     www      5730:     $symb=&symbclean($symb);
1.122     albertel 5731:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5732: 
1.620     albertel 5733:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5734:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5735: 
                   5736:     &devalidate($symb,$stuname,$domain);
1.109     www      5737: 
                   5738:     $symb=escape($symb);
1.187     www      5739:     if (!$namespace) { 
1.620     albertel 5740:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5741:           return ''; 
                   5742:        } 
                   5743:     }
1.620     albertel 5744:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5745: 
                   5746:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5747:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5748: 
1.12      www      5749:     my $namevalue='';
1.800     albertel 5750:     foreach my $key (keys(%$storehash)) {
                   5751:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5752:     }
1.12      www      5753:     $namevalue=~s/\&$//;
1.187     www      5754:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5755:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5756: }
                   5757: 
1.47      www      5758: # -------------------------------------------------------------- Critical Store
                   5759: 
                   5760: sub cstore {
1.1269    raeburn  5761:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5762:     my $home='';
                   5763: 
1.168     albertel 5764:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5765: 
1.213     www      5766:     $symb=&symbclean($symb);
1.122     albertel 5767:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5768: 
1.620     albertel 5769:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5770:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5771: 
                   5772:     &devalidate($symb,$stuname,$domain);
1.109     www      5773: 
                   5774:     $symb=escape($symb);
1.187     www      5775:     if (!$namespace) { 
1.620     albertel 5776:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5777:           return ''; 
                   5778:        } 
                   5779:     }
1.620     albertel 5780:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5781: 
                   5782:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5783:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5784: 
1.47      www      5785:     my $namevalue='';
1.800     albertel 5786:     foreach my $key (keys(%$storehash)) {
                   5787:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5788:     }
1.47      www      5789:     $namevalue=~s/\&$//;
1.187     www      5790:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5791:     return critical
1.1269    raeburn  5792:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5793: }
                   5794: 
1.9       www      5795: # --------------------------------------------------------------------- Restore
                   5796: 
                   5797: sub restore {
1.124     www      5798:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5799:     my $home='';
                   5800: 
1.168     albertel 5801:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5802: 
1.122     albertel 5803:     if (!$symb) {
1.1224    raeburn  5804:         return if ($namespace eq 'courserequests');
                   5805:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5806:     } else {
1.1224    raeburn  5807:         unless ($namespace eq 'courserequests') {
                   5808:             $symb=&escape(&symbclean($symb));
                   5809:         }
1.122     albertel 5810:     }
1.188     www      5811:     if (!$namespace) { 
1.620     albertel 5812:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5813:           return ''; 
                   5814:        } 
                   5815:     }
1.620     albertel 5816:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5817:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5818:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5819:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5820: 
1.12      www      5821:     my %returnhash=();
1.800     albertel 5822:     foreach my $line (split(/\&/,$answer)) {
                   5823: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5824:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5825:     }
1.75      www      5826:     my $version;
                   5827:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5828:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5829:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5830:        }
1.75      www      5831:     }
1.13      www      5832:     return %returnhash;
1.34      www      5833: }
                   5834: 
                   5835: # ---------------------------------------------------------- Course Description
1.1118    foxr     5836: #
                   5837: #  
1.34      www      5838: 
                   5839: sub coursedescription {
1.731     albertel 5840:     my ($courseid,$args)=@_;
1.34      www      5841:     $courseid=~s/^\///;
1.49      www      5842:     $courseid=~s/\_/\//g;
1.34      www      5843:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5844:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5845:     my $normalid=$cdomain.'_'.$cnum;
                   5846:     # need to always cache even if we get errors otherwise we keep 
                   5847:     # trying and trying and trying to get the course description.
                   5848:     my %envhash=();
                   5849:     my %returnhash=();
1.731     albertel 5850:     
                   5851:     my $expiretime=600;
                   5852:     if ($env{'request.course.id'} eq $normalid) {
                   5853: 	$expiretime=120;
                   5854:     }
                   5855: 
                   5856:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5857:     if (!$args->{'freshen_cache'}
                   5858: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5859: 	foreach my $key (keys(%env)) {
                   5860: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5861: 	    my ($setting) = $1;
                   5862: 	    $returnhash{$setting} = $env{$key};
                   5863: 	}
                   5864: 	return %returnhash;
                   5865:     }
                   5866: 
1.1118    foxr     5867:     # get the data again
                   5868: 
1.731     albertel 5869:     if (!$args->{'one_time'}) {
                   5870: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5871:     }
1.811     albertel 5872: 
1.34      www      5873:     if ($chome ne 'no_host') {
1.302     albertel 5874:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5875:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5876: 	   my $username = $env{'user.name'}; # Defult username
                   5877: 	   if(defined $args->{'user'}) {
                   5878: 	       $username = $args->{'user'};
                   5879: 	   }
1.129     albertel 5880:            $returnhash{'home'}= $chome;
                   5881: 	   $returnhash{'domain'} = $cdomain;
                   5882: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5883:            if (!defined($returnhash{'type'})) {
                   5884:                $returnhash{'type'} = 'Course';
                   5885:            }
1.130     albertel 5886:            while (my ($name,$value) = each %returnhash) {
1.53      www      5887:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5888:            }
1.270     www      5889:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5890:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5891: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5892:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5893:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5894:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5895:        }
                   5896:     }
1.731     albertel 5897:     if (!$args->{'one_time'}) {
1.949     raeburn  5898: 	&appenv(\%envhash);
1.731     albertel 5899:     }
1.302     albertel 5900:     return %returnhash;
1.461     www      5901: }
                   5902: 
1.1080    raeburn  5903: sub update_released_required {
                   5904:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5905:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5906:         $cid = $env{'request.course.id'};
                   5907:         $cdom = $env{'course.'.$cid.'.domain'};
                   5908:         $cnum = $env{'course.'.$cid.'.num'};
                   5909:         $chome = $env{'course.'.$cid.'.home'};
                   5910:     }
                   5911:     if ($needsrelease) {
                   5912:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5913:         my $needsupdate;
                   5914:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5915:             $needsupdate = 1;
                   5916:         } else {
                   5917:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5918:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5919:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5920:                 $needsupdate = 1;
                   5921:             }
                   5922:         }
                   5923:         if ($needsupdate) {
                   5924:             my %needshash = (
                   5925:                              'internal.releaserequired' => $needsrelease,
                   5926:                             );
                   5927:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5928:             if ($putresult eq 'ok') {
                   5929:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5930:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5931:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5932:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5933:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5934:                 }
                   5935:             }
                   5936:         }
                   5937:     }
                   5938:     return;
                   5939: }
                   5940: 
1.461     www      5941: # -------------------------------------------------See if a user is privileged
                   5942: 
                   5943: sub privileged {
1.1219    raeburn  5944:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5945:     my $now = time;
1.1219    raeburn  5946:     my $roles;
                   5947:     if (ref($possroles) eq 'ARRAY') {
                   5948:         $roles = $possroles; 
                   5949:     } else {
                   5950:         $roles = ['dc','su'];
                   5951:     }
                   5952:     if (ref($possdomains) eq 'ARRAY') {
                   5953:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5954:         foreach my $dom (@{$possdomains}) {
                   5955:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5956:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5957:                 foreach my $role (@{$roles}) {
                   5958:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5959:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5960:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5961:                             return 1 unless (($end && $end < $now) ||
                   5962:                                              ($start && $start > $now));
                   5963:                         }
                   5964:                     }
                   5965:                 }
                   5966:             }
                   5967:         }
                   5968:     } else {
                   5969:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5970:         my $now = time;
1.1170    droeschl 5971: 
1.1275    musolffc 5972:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5973:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5974:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5975:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5976:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5977:             }
1.1219    raeburn  5978:         }
                   5979:     }
                   5980:     return 0;
                   5981: }
1.1170    droeschl 5982: 
1.1219    raeburn  5983: sub privileged_by_domain {
                   5984:     my ($domains,$roles) = @_;
                   5985:     my %privileged = ();
                   5986:     my $cachetime = 60*60*24;
                   5987:     my $now = time;
                   5988:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5989:         return %privileged;
                   5990:     }
                   5991:     foreach my $dom (@{$domains}) {
                   5992:         next if (ref($privileged{$dom}) eq 'HASH');
                   5993:         my $needroles;
                   5994:         foreach my $role (@{$roles}) {
                   5995:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5996:             if (defined($cached)) {
                   5997:                 if (ref($result) eq 'HASH') {
                   5998:                     $privileged{$dom}{$role} = $result;
                   5999:                 }
                   6000:             } else {
                   6001:                 $needroles = 1;
                   6002:             }
                   6003:         }
                   6004:         if ($needroles) {
                   6005:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6006:             $privileged{$dom} = {};
                   6007:             foreach my $server (keys(%dompersonnel)) {
                   6008:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6009:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6010:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6011:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6012:                         next if ($end && $end < $now);
                   6013:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6014:                             $dompersonnel{$server}{$item};
                   6015:                     }
                   6016:                 }
                   6017:             }
                   6018:             if (ref($privileged{$dom}) eq 'HASH') {
                   6019:                 foreach my $role (@{$roles}) {
                   6020:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6021:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6022:                     } else {
                   6023:                         my %hash = ();
                   6024:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6025:                     }
                   6026:                 }
                   6027:             }
                   6028:         }
                   6029:     }
                   6030:     return %privileged;
1.9       www      6031: }
1.1       albertel 6032: 
1.103     harris41 6033: # -------------------------------------------------------- Get user privileges
1.11      www      6034: 
                   6035: sub rolesinit {
1.1169    droeschl 6036:     my ($domain, $username) = @_;
                   6037:     my %userroles = ('user.login.time' => time);
                   6038:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6039: 
                   6040:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6041:     # also, blocking can be triggered by an activating timer
                   6042:     # it's saved in the user's %env.
                   6043:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6044:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6045:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6046:         %timerintchk, %timerintenv);
                   6047: 
1.1162    raeburn  6048:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6049:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6050:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6051:     }
1.1169    droeschl 6052: 
1.1162    raeburn  6053:     foreach my $key (keys(%timerinterval)) {
                   6054:         my ($cid,$rest) = split(/\0/,$key);
                   6055:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6056:     }
1.1169    droeschl 6057: 
1.11      www      6058:     my %allroles=();
1.1162    raeburn  6059:     my %allgroups=();
1.11      www      6060: 
1.1274    raeburn  6061:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6062:         my $role = $rolesdump{$area};
                   6063:         $area =~ s/\_\w\w$//;
                   6064: 
                   6065:         my ($trole, $tend, $tstart, $group_privs);
                   6066: 
                   6067:         if ($role =~ /^cr/) {
                   6068:         # Custom role, defined by a user 
                   6069:         # e.g., user.role.cr/msu/smith/mynewrole
                   6070:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6071:                 $trole = $1;
                   6072:                 ($tend, $tstart) = split('_', $2);
                   6073:             } else {
                   6074:                 $trole = $role;
                   6075:             }
                   6076:         } elsif ($role =~ m|^gr/|) {
                   6077:         # Role of member in a group, defined within a course/community
                   6078:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6079:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6080:             next if $tstart eq '-1';
                   6081:             ($trole, $group_privs) = split(/\//, $trole);
                   6082:             $group_privs = &unescape($group_privs);
                   6083:         } else {
                   6084:         # Just a normal role, defined in roles.tab
                   6085:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6086:         }
                   6087: 
                   6088:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6089:                  $username);
                   6090:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6091: 
                   6092:         # role expired or not available yet?
                   6093:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6094:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6095: 
                   6096:         next if $area eq '' or $trole eq '';
                   6097: 
                   6098:         my $spec = "$trole.$area";
                   6099:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6100: 
                   6101:         if ($trole =~ /^cr\//) {
                   6102:         # Custom role, defined by a user
                   6103:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6104:         } elsif ($trole eq 'gr') {
                   6105:         # Role of a member in a group, defined within a course/community
                   6106:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6107:             next;
                   6108:         } else {
                   6109:         # Normal role, defined in roles.tab
                   6110:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6111:         }
                   6112: 
                   6113:         my $cid = $tdomain.'_'.$trest;
                   6114:         unless ($firstaccchk{$cid}) {
                   6115:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6116:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6117:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6118:                         $coursetimerstarts{$cid}{$item}; 
                   6119:                 }
                   6120:             }
                   6121:             $firstaccchk{$cid} = 1;
                   6122:         }
                   6123:         unless ($timerintchk{$cid}) {
                   6124:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6125:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6126:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6127:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6128:                 }
1.12      www      6129:             }
1.1169    droeschl 6130:             $timerintchk{$cid} = 1;
1.191     harris41 6131:         }
1.11      www      6132:     }
1.1169    droeschl 6133: 
1.1341    raeburn  6134:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6135:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6136:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6137:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6138: 
1.1162    raeburn  6139:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6140: }
                   6141: 
1.567     raeburn  6142: sub set_arearole {
1.1215    raeburn  6143:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6144:     unless ($nolog) {
1.567     raeburn  6145: # log the associated role with the area
1.1215    raeburn  6146:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6147:     }
1.743     albertel 6148:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6149: }
                   6150: 
                   6151: sub custom_roleprivs {
                   6152:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6153:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6154:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6155:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6156:         my ($rdummy,$roledef)=
                   6157:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6158:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6159:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6160:             if (defined($syspriv)) {
1.1043    raeburn  6161:                 if ($trest =~ /^$match_community$/) {
                   6162:                     $syspriv =~ s/bre\&S//; 
                   6163:                 }
1.567     raeburn  6164:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6165:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6166:             }
                   6167:             if ($tdomain ne '') {
                   6168:                 if (defined($dompriv)) {
                   6169:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6170:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6171:                 }
                   6172:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6173:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6174:                         my $rolename = $1;
                   6175:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6176:                     }
1.567     raeburn  6177:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6178:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6179:                 }
                   6180:             }
                   6181:         }
                   6182:     }
                   6183: }
                   6184: 
1.1332    raeburn  6185: sub course_adhocrole_privs {
                   6186:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6187:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6188:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6189:         my (%currprivs,%storeprivs);
                   6190:         foreach my $item (split(/:/,$coursepriv)) {
                   6191:             my ($priv,$restrict) = split(/\&/,$item);
                   6192:             $currprivs{$priv} = $restrict;
                   6193:         }
                   6194:         my (%possadd,%possremove,%full);
                   6195:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6196:             my ($priv,$restrict)=split(/\&/,$item);
                   6197:             $full{$priv} = $restrict;
                   6198:         }
                   6199:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6200:              next if ($item eq '');
                   6201:              my ($rule,$rest) = split(/=/,$item);
                   6202:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6203:              foreach my $priv (split(/:/,$rest)) {
                   6204:                  if ($priv ne '') {
                   6205:                      if ($rule eq 'off') {
                   6206:                          $possremove{$priv} = 1;
                   6207:                      } else {
                   6208:                          $possadd{$priv} = 1;
                   6209:                      }
                   6210:                  }
                   6211:              }
                   6212:          }
                   6213:          foreach my $priv (sort(keys(%full))) {
                   6214:              if (exists($currprivs{$priv})) {
                   6215:                  unless (exists($possremove{$priv})) {
                   6216:                      $storeprivs{$priv} = $currprivs{$priv};
                   6217:                  }
                   6218:              } elsif (exists($possadd{$priv})) {
                   6219:                  $storeprivs{$priv} = $full{$priv};
                   6220:              }
                   6221:          }
                   6222:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6223:      }
                   6224:      return $coursepriv;
                   6225: }
                   6226: 
1.678     raeburn  6227: sub group_roleprivs {
                   6228:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6229:     my $access = 1;
                   6230:     my $now = time;
                   6231:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6232:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6233:     if ($access) {
1.811     albertel 6234:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6235:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6236:     }
                   6237: }
1.567     raeburn  6238: 
                   6239: sub standard_roleprivs {
                   6240:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6241:     if (defined($pr{$trole.':s'})) {
                   6242:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6243:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6244:     }
                   6245:     if ($tdomain ne '') {
                   6246:         if (defined($pr{$trole.':d'})) {
                   6247:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6248:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6249:         }
                   6250:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6251:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6252:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6253:         }
                   6254:     }
                   6255: }
                   6256: 
                   6257: sub set_userprivs {
1.1064    raeburn  6258:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6259:     my $author=0;
                   6260:     my $adv=0;
1.1341    raeburn  6261:     my $rar=0;
1.678     raeburn  6262:     my %grouproles = ();
                   6263:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6264:         my @groupkeys; 
1.1000    raeburn  6265:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6266:             push(@groupkeys,$role);
                   6267:         }
                   6268:         if (ref($groups_roles) eq 'HASH') {
                   6269:             foreach my $key (keys(%{$groups_roles})) {
                   6270:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6271:                     push(@groupkeys,$key);
                   6272:                 }
                   6273:             }
                   6274:         }
                   6275:         if (@groupkeys > 0) {
                   6276:             foreach my $role (@groupkeys) {
                   6277:                 my ($trole,$area,$sec,$extendedarea);
                   6278:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6279:                     $trole = $1;
                   6280:                     $area = $2;
                   6281:                     $sec = $3;
                   6282:                     $extendedarea = $area.$sec;
                   6283:                     if (exists($$allgroups{$area})) {
                   6284:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6285:                             my $spec = $trole.'.'.$extendedarea;
                   6286:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6287:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6288:                         }
1.678     raeburn  6289:                     }
                   6290:                 }
                   6291:             }
                   6292:         }
                   6293:     }
1.800     albertel 6294:     foreach my $group (keys(%grouproles)) {
                   6295:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6296:     }
1.800     albertel 6297:     foreach my $role (keys(%{$allroles})) {
                   6298:         my %thesepriv;
1.941     raeburn  6299:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6300:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6301:             if ($item ne '') {
                   6302:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6303:                 if ($restrictions eq '') {
                   6304:                     $thesepriv{$privilege}='F';
                   6305:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6306:                     $thesepriv{$privilege}.=$restrictions;
                   6307:                 }
                   6308:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6309:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6310:             }
                   6311:         }
                   6312:         my $thesestr='';
1.1104    raeburn  6313:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6314: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6315: 	}
                   6316:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6317:     }
1.1341    raeburn  6318:     return ($author,$adv,$rar);
1.567     raeburn  6319: }
                   6320: 
1.994     raeburn  6321: sub role_status {
1.1104    raeburn  6322:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6323:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6324:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6325:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6326:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6327:             $$where = '/'.$two;
1.994     raeburn  6328:             $$trolecode=$$role.'.'.$$where;
                   6329:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6330:             $$tstatus='is';
1.1104    raeburn  6331:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6332:                 $$tstatus='future';
1.1034    raeburn  6333:                 if ($$tstart<$now) {
                   6334:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6335:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6336:                             my (%allroles,%allgroups,$group_privs,
                   6337:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6338:                             my %userroles = (
                   6339:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6340:                             );
1.1064    raeburn  6341:                             @rolecodes = ('cm'); 
1.1002    raeburn  6342:                             my $spec=$$role.'.'.$$where;
                   6343:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6344:                             if ($$role =~ /^cr\//) {
                   6345:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6346:                                 push(@rolecodes,'cr');
1.1002    raeburn  6347:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6348:                                 push(@rolecodes,$$role);
1.1002    raeburn  6349:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6350:                                                     $env{'user.name'});
1.1064    raeburn  6351:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6352:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6353:                                 $group_privs = &unescape($group_privs);
                   6354:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6355:                                 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  6356:                                 &get_groups_roles($tdomain,$trest,
                   6357:                                                   \%course_roles,\@rolecodes,
                   6358:                                                   \%groups_roles);
1.1002    raeburn  6359:                             } else {
1.1064    raeburn  6360:                                 push(@rolecodes,$$role);
1.1002    raeburn  6361:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6362:                             }
1.1341    raeburn  6363:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6364:                                                                    \%groups_roles);
1.1064    raeburn  6365:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6366:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6367:                         }
                   6368:                     }
1.1034    raeburn  6369:                     $$tstatus = 'is';
1.1002    raeburn  6370:                 }
1.994     raeburn  6371:             }
                   6372:             if ($$tend) {
1.1104    raeburn  6373:                 if ($$tend<$update) {
1.994     raeburn  6374:                     $$tstatus='expired';
                   6375:                 } elsif ($$tend<$now) {
                   6376:                     $$tstatus='will_not';
                   6377:                 }
                   6378:             }
                   6379:         }
                   6380:     }
                   6381: }
                   6382: 
1.1104    raeburn  6383: sub get_groups_roles {
                   6384:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6385:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6386:                   (ref($rolecodes) eq 'ARRAY') && 
                   6387:                   (ref($groups_roles) eq 'HASH')); 
                   6388:     if (keys(%{$cdom_courseroles}) > 0) {
                   6389:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6390:         if ($cdom ne '' && $cnum ne '') {
                   6391:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6392:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6393:                     my $crsrole = $1;
                   6394:                     my $crssec = $2;
                   6395:                     if ($crsrole =~ /^cr/) {
                   6396:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6397:                             push(@{$rolecodes},'cr');
                   6398:                         }
                   6399:                     } else {
                   6400:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6401:                             push(@{$rolecodes},$crsrole);
                   6402:                         }
                   6403:                     }
                   6404:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6405:                     if ($crssec ne '') {
                   6406:                         $rolekey .= "/$crssec";
                   6407:                     }
                   6408:                     $rolekey .= './';
                   6409:                     $groups_roles->{$rolekey} = $rolecodes;
                   6410:                 }
                   6411:             }
                   6412:         }
                   6413:     }
                   6414:     return;
                   6415: }
                   6416: 
                   6417: sub delete_env_groupprivs {
                   6418:     my ($where,$courseroles,$possroles) = @_;
                   6419:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6420:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6421:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6422:         %{$courseroles->{$udom}} =
                   6423:             &get_my_roles('','','userroles',['active'],
                   6424:                           $possroles,[$udom],1);
                   6425:     }
                   6426:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6427:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6428:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6429:             my $area = '/'.$cdom.'/'.$cnum;
                   6430:             my $privkey = "user.priv.$crsrole.$area";
                   6431:             if ($crssec ne '') {
                   6432:                 $privkey .= '/'.$crssec;
                   6433:             }
                   6434:             $privkey .= ".$area/$group";
                   6435:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6436:         }
                   6437:     }
                   6438:     return;
                   6439: }
                   6440: 
1.994     raeburn  6441: sub check_adhoc_privs {
1.1329    raeburn  6442:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6443:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6444:     if ($sec) {
                   6445:         $cckey .= '/'.$sec;
                   6446:     } 
1.1185    raeburn  6447:     my $setprivs;
1.994     raeburn  6448:     if ($env{$cckey}) {
                   6449:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6450:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6451:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6452:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6453:             $setprivs = 1;
1.994     raeburn  6454:         }
                   6455:     } else {
1.1330    raeburn  6456:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6457:         $setprivs = 1;
1.994     raeburn  6458:     }
1.1185    raeburn  6459:     return $setprivs;
1.994     raeburn  6460: }
                   6461: 
                   6462: sub set_adhoc_privileges {
1.1326    raeburn  6463: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6464:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6465:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6466:     if ($sec ne '') {
                   6467:         $area .= '/'.$sec;
                   6468:     }
1.994     raeburn  6469:     my $spec = $role.'.'.$area;
                   6470:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6471:                                   $env{'user.name'},1);
1.1326    raeburn  6472:     my %rolehash = ();
1.1332    raeburn  6473:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6474:         my $rolename = $1;
1.1326    raeburn  6475:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6476:         my %domdef = &get_domain_defaults($dcdom);
                   6477:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6478:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6479:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6480:             }
                   6481:         }
1.1326    raeburn  6482:     } else {
                   6483:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6484:     }
1.1341    raeburn  6485:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6486:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6487:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6488:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6489:         &appenv( {'request.role'        => $spec,
                   6490:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6491:                   'request.course.sec'  => $sec,
1.1088    raeburn  6492:                  }
                   6493:                );
                   6494:         my $tadv=0;
                   6495:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6496:         &appenv({'request.role.adv'    => $tadv});
                   6497:     }
1.994     raeburn  6498: }
                   6499: 
1.12      www      6500: # --------------------------------------------------------------- get interface
                   6501: 
                   6502: sub get {
1.131     albertel 6503:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6504:    my $items='';
1.800     albertel 6505:    foreach my $item (@$storearr) {
                   6506:        $items.=&escape($item).'&';
1.191     harris41 6507:    }
1.12      www      6508:    $items=~s/\&$//;
1.620     albertel 6509:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6510:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6511:    my $uhome=&homeserver($uname,$udomain);
                   6512: 
1.133     albertel 6513:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6514:    my @pairs=split(/\&/,$rep);
1.273     albertel 6515:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6516:      return @pairs;
                   6517:    }
1.15      www      6518:    my %returnhash=();
1.42      www      6519:    my $i=0;
1.800     albertel 6520:    foreach my $item (@$storearr) {
                   6521:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6522:       $i++;
1.191     harris41 6523:    }
1.15      www      6524:    return %returnhash;
1.27      www      6525: }
                   6526: 
                   6527: # --------------------------------------------------------------- del interface
                   6528: 
                   6529: sub del {
1.133     albertel 6530:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6531:    my $items='';
1.800     albertel 6532:    foreach my $item (@$storearr) {
                   6533:        $items.=&escape($item).'&';
1.191     harris41 6534:    }
1.984     neumanie 6535: 
1.27      www      6536:    $items=~s/\&$//;
1.620     albertel 6537:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6538:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6539:    my $uhome=&homeserver($uname,$udomain);
                   6540:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6541: }
                   6542: 
                   6543: # -------------------------------------------------------------- dump interface
                   6544: 
1.1180    droeschl 6545: sub unserialize {
                   6546:     my ($rep, $escapedkeys) = @_;
                   6547: 
                   6548:     return {} if $rep =~ /^error/;
                   6549: 
                   6550:     my %returnhash=();
1.1252    raeburn  6551: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6552: 	    my ($key, $value) = split(/=/, $item, 2);
                   6553: 	    $key = unescape($key) unless $escapedkeys;
                   6554: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6555: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6556: 	}
                   6557:     #return %returnhash;
                   6558:     return \%returnhash;
                   6559: }        
                   6560: 
                   6561: # see Lond::dump_with_regexp
                   6562: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6563: sub dump {
1.1180    droeschl 6564:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6565:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6566:     if (!$uname) { $uname=$env{'user.name'}; }
                   6567:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6568: 
1.1266    raeburn  6569:     if ($regexp) {
                   6570:         $regexp=&escape($regexp);
                   6571:     } else {
                   6572:         $regexp='.';
                   6573:     }
1.1180    droeschl 6574:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6575:         # user is hosted on this machine
1.1266    raeburn  6576:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6577:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6578:         return %{unserialize($reply, $escapedkeys)};
                   6579:     }
1.1166    raeburn  6580:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6581:     my @pairs=split(/\&/,$rep);
                   6582:     my %returnhash=();
1.1098    foxr     6583:     if (!($rep =~ /^error/ )) {
                   6584: 	foreach my $item (@pairs) {
                   6585: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6586:         $key = unescape($key) unless $escapedkeys;
                   6587:         #$key = &unescape($key);
1.1098    foxr     6588: 	    next if ($key =~ /^error: 2 /);
                   6589: 	    $returnhash{$key}=&thaw_unescape($value);
                   6590: 	}
1.755     albertel 6591:     }
                   6592:     return %returnhash;
1.407     www      6593: }
                   6594: 
1.1098    foxr     6595: 
1.717     albertel 6596: # --------------------------------------------------------- dumpstore interface
                   6597: 
                   6598: sub dumpstore {
                   6599:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6600:    # same as dump but keys must be escaped. They may contain colon separated
                   6601:    # lists of values that may themself contain colons (e.g. symbs).
                   6602:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6603: }
                   6604: 
1.407     www      6605: # -------------------------------------------------------------- keys interface
                   6606: 
                   6607: sub getkeys {
                   6608:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6609:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6610:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6611:    my $uhome=&homeserver($uname,$udomain);
                   6612:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6613:    my @keyarray=();
1.800     albertel 6614:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6615:       next if ($key =~ /^error: 2 /);
1.800     albertel 6616:       push(@keyarray,&unescape($key));
1.407     www      6617:    }
                   6618:    return @keyarray;
1.318     matthew  6619: }
                   6620: 
1.319     matthew  6621: # --------------------------------------------------------------- currentdump
                   6622: sub currentdump {
1.328     matthew  6623:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6624:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6625:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6626:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6627:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6628:    my $rep;
                   6629: 
                   6630:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6631:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6632:                    $courseid)));
                   6633:    } else {
                   6634:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6635:    }
                   6636: 
1.318     matthew  6637:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6638:    #
1.318     matthew  6639:    my %returnhash=();
1.319     matthew  6640:    #
1.1343    raeburn  6641:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6642:        # an old lond will not know currentdump
                   6643:        # Do a dump and make it look like a currentdump
1.822     albertel 6644:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6645:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6646:        my %hash = @tmp;
                   6647:        @tmp=();
1.424     matthew  6648:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6649:    } else {
                   6650:        my @pairs=split(/\&/,$rep);
1.800     albertel 6651:        foreach my $pair (@pairs) {
                   6652:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6653:            my ($symb,$param) = split(/:/,$key);
                   6654:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6655:                                                         &thaw_unescape($value);
1.319     matthew  6656:        }
1.191     harris41 6657:    }
1.12      www      6658:    return %returnhash;
1.424     matthew  6659: }
                   6660: 
                   6661: sub convert_dump_to_currentdump{
                   6662:     my %hash = %{shift()};
                   6663:     my %returnhash;
                   6664:     # Code ripped from lond, essentially.  The only difference
                   6665:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6666:     # we might run in to problems with parameter names =~ /^v\./
                   6667:     while (my ($key,$value) = each(%hash)) {
                   6668:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6669: 	$symb  = &unescape($symb);
                   6670: 	$param = &unescape($param);
1.424     matthew  6671:         next if ($v eq 'version' || $symb eq 'keys');
                   6672:         next if (exists($returnhash{$symb}) &&
                   6673:                  exists($returnhash{$symb}->{$param}) &&
                   6674:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6675:         $returnhash{$symb}->{$param}=$value;
                   6676:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6677:     }
                   6678:     #
                   6679:     # Remove all of the keys in the hashes which keep track of
                   6680:     # the version of the parameter.
                   6681:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6682:         # use a foreach because we are going to delete from the hash.
                   6683:         foreach my $key (keys(%$param_hash)) {
                   6684:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6685:         }
                   6686:     }
                   6687:     return \%returnhash;
1.12      www      6688: }
                   6689: 
1.627     albertel 6690: # ------------------------------------------------------ critical inc interface
                   6691: 
                   6692: sub cinc {
                   6693:     return &inc(@_,'critical');
                   6694: }
                   6695: 
1.449     matthew  6696: # --------------------------------------------------------------- inc interface
                   6697: 
                   6698: sub inc {
1.627     albertel 6699:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6700:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6701:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6702:     my $uhome=&homeserver($uname,$udomain);
                   6703:     my $items='';
                   6704:     if (! ref($store)) {
                   6705:         # got a single value, so use that instead
                   6706:         $items = &escape($store).'=&';
                   6707:     } elsif (ref($store) eq 'SCALAR') {
                   6708:         $items = &escape($$store).'=&';        
                   6709:     } elsif (ref($store) eq 'ARRAY') {
                   6710:         $items = join('=&',map {&escape($_);} @{$store});
                   6711:     } elsif (ref($store) eq 'HASH') {
                   6712:         while (my($key,$value) = each(%{$store})) {
                   6713:             $items.= &escape($key).'='.&escape($value).'&';
                   6714:         }
                   6715:     }
                   6716:     $items=~s/\&$//;
1.627     albertel 6717:     if ($critical) {
                   6718: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6719:     } else {
                   6720: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6721:     }
1.449     matthew  6722: }
                   6723: 
1.12      www      6724: # --------------------------------------------------------------- put interface
                   6725: 
                   6726: sub put {
1.134     albertel 6727:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6728:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6729:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6730:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6731:    my $items='';
1.800     albertel 6732:    foreach my $item (keys(%$storehash)) {
                   6733:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6734:    }
1.12      www      6735:    $items=~s/\&$//;
1.134     albertel 6736:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6737: }
                   6738: 
1.631     albertel 6739: # ------------------------------------------------------------ newput interface
                   6740: 
                   6741: sub newput {
                   6742:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6743:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6744:    if (!$uname) { $uname=$env{'user.name'}; }
                   6745:    my $uhome=&homeserver($uname,$udomain);
                   6746:    my $items='';
                   6747:    foreach my $key (keys(%$storehash)) {
                   6748:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6749:    }
                   6750:    $items=~s/\&$//;
                   6751:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6752: }
                   6753: 
                   6754: # ---------------------------------------------------------  putstore interface
                   6755: 
1.524     raeburn  6756: sub putstore {
1.1269    raeburn  6757:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6758:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6759:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6760:    my $uhome=&homeserver($uname,$udomain);
                   6761:    my $items='';
1.715     albertel 6762:    foreach my $key (keys(%$storehash)) {
                   6763:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6764:    }
1.715     albertel 6765:    $items=~s/\&$//;
1.716     albertel 6766:    my $esc_symb=&escape($symb);
                   6767:    my $esc_v=&escape($version);
1.715     albertel 6768:    my $reply =
1.716     albertel 6769:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6770: 	      $uhome);
1.1269    raeburn  6771:    if (($tolog) && ($reply eq 'ok')) {
                   6772:        my $namevalue='';
                   6773:        foreach my $key (keys(%{$storehash})) {
                   6774:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6775:        }
                   6776:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6777:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6778:                      '&version='.$esc_v.
                   6779:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6780:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6781:    }
1.715     albertel 6782:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6783:        # gfall back to way things use to be done
1.715     albertel 6784:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6785: 			    $uname);
1.524     raeburn  6786:    }
1.715     albertel 6787:    return $reply;
                   6788: }
                   6789: 
                   6790: sub old_putstore {
1.716     albertel 6791:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6792:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6793:     if (!$uname) { $uname=$env{'user.name'}; }
                   6794:     my $uhome=&homeserver($uname,$udomain);
                   6795:     my %newstorehash;
1.800     albertel 6796:     foreach my $item (keys(%$storehash)) {
                   6797: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6798: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6799:     }
                   6800:     my $items='';
                   6801:     my %allitems = ();
1.800     albertel 6802:     foreach my $item (keys(%newstorehash)) {
                   6803: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6804: 	    my $key = $1.':keys:'.$2;
                   6805: 	    $allitems{$key} .= $3.':';
                   6806: 	}
1.800     albertel 6807: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6808:     }
1.800     albertel 6809:     foreach my $item (keys(%allitems)) {
                   6810: 	$allitems{$item} =~ s/\:$//;
                   6811: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6812:     }
                   6813:     $items=~s/\&$//;
                   6814:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6815: }
                   6816: 
1.47      www      6817: # ------------------------------------------------------ critical put interface
                   6818: 
                   6819: sub cput {
1.134     albertel 6820:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6821:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6822:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6823:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6824:    my $items='';
1.800     albertel 6825:    foreach my $item (keys(%$storehash)) {
                   6826:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6827:    }
1.47      www      6828:    $items=~s/\&$//;
1.134     albertel 6829:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6830: }
                   6831: 
                   6832: # -------------------------------------------------------------- eget interface
                   6833: 
                   6834: sub eget {
1.133     albertel 6835:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6836:    my $items='';
1.800     albertel 6837:    foreach my $item (@$storearr) {
                   6838:        $items.=&escape($item).'&';
1.191     harris41 6839:    }
1.12      www      6840:    $items=~s/\&$//;
1.620     albertel 6841:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6842:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6843:    my $uhome=&homeserver($uname,$udomain);
                   6844:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6845:    my @pairs=split(/\&/,$rep);
                   6846:    my %returnhash=();
1.42      www      6847:    my $i=0;
1.800     albertel 6848:    foreach my $item (@$storearr) {
                   6849:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6850:       $i++;
1.191     harris41 6851:    }
1.12      www      6852:    return %returnhash;
                   6853: }
                   6854: 
1.667     albertel 6855: # ------------------------------------------------------------ tmpput interface
                   6856: sub tmpput {
1.802     raeburn  6857:     my ($storehash,$server,$context)=@_;
1.667     albertel 6858:     my $items='';
1.800     albertel 6859:     foreach my $item (keys(%$storehash)) {
                   6860: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6861:     }
                   6862:     $items=~s/\&$//;
1.802     raeburn  6863:     if (defined($context)) {
                   6864:         $items .= ':'.&escape($context);
                   6865:     }
1.667     albertel 6866:     return &reply("tmpput:$items",$server);
                   6867: }
                   6868: 
                   6869: # ------------------------------------------------------------ tmpget interface
                   6870: sub tmpget {
1.688     albertel 6871:     my ($token,$server)=@_;
                   6872:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6873:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6874:     my %returnhash;
1.1328    raeburn  6875:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6876:         return %returnhash;
                   6877:     }
1.667     albertel 6878:     foreach my $item (split(/\&/,$rep)) {
                   6879: 	my ($key,$value)=split(/=/,$item);
                   6880: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6881:     }
                   6882:     return %returnhash;
                   6883: }
                   6884: 
1.1113    raeburn  6885: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6886: sub tmpdel {
                   6887:     my ($token,$server)=@_;
                   6888:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6889:     return &reply("tmpdel:$token",$server);
                   6890: }
                   6891: 
1.1198    raeburn  6892: # ------------------------------------------------------------ get_timebased_id 
                   6893: 
                   6894: sub get_timebased_id {
                   6895:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6896:         $maxtries) = @_;
                   6897:     my ($newid,$error,$dellock);
                   6898:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6899:         return ('','ok','invalid call to get suffix');
                   6900:     }
                   6901: 
                   6902: # set defaults for any optional args for which values were not supplied
                   6903:     if ($who eq '') {
                   6904:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6905:     }
                   6906:     if (!$locktries) {
                   6907:         $locktries = 3;
                   6908:     }
                   6909:     if (!$maxtries) {
                   6910:         $maxtries = 10;
                   6911:     }
                   6912:     
                   6913:     if (($cdom eq '') || ($cnum eq '')) {
                   6914:         if ($env{'request.course.id'}) {
                   6915:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6916:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6917:         }
                   6918:         if (($cdom eq '') || ($cnum eq '')) {
                   6919:             return ('','ok','call to get suffix not in course context');
                   6920:         }
                   6921:     }
                   6922: 
                   6923: # construct locking item
                   6924:     my $lockhash = {
                   6925:                       $prefix."\0".'locked_'.$keyid => $who,
                   6926:                    };
                   6927:     my $tries = 0;
                   6928: 
                   6929: # attempt to get lock on nohist_$namespace file
                   6930:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6931:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6932:         $tries ++;
                   6933:         sleep 1;
                   6934:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6935:     }
                   6936: 
                   6937: # attempt to get unique identifier, based on current timestamp
                   6938:     if ($gotlock eq 'ok') {
                   6939:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6940:         my $id = time;
                   6941:         $newid = $id;
1.1268    raeburn  6942:         if ($idtype eq 'addcode') {
                   6943:             $newid .= &sixnum_code();
                   6944:         }
1.1198    raeburn  6945:         my $idtries = 0;
                   6946:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6947:             if ($idtype eq 'concat') {
                   6948:                 $newid = $id.$idtries;
1.1268    raeburn  6949:             } elsif ($idtype eq 'addcode') {
                   6950:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6951:             } else {
                   6952:                 $newid ++;
                   6953:             }
                   6954:             $idtries ++;
                   6955:         }
                   6956:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6957:             my %new_item =  (
                   6958:                               $prefix."\0".$newid => $who,
                   6959:                             );
                   6960:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6961:                                                  $cdom,$cnum);
                   6962:             if ($putresult ne 'ok') {
                   6963:                 undef($newid);
                   6964:                 $error = 'error saving new item: '.$putresult;
                   6965:             }
                   6966:         } else {
1.1268    raeburn  6967:              undef($newid);
1.1198    raeburn  6968:              $error = ('error: no unique suffix available for the new item ');
                   6969:         }
                   6970: #  remove lock
                   6971:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6972:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6973:     } else {
                   6974:         $error = "error: could not obtain lockfile\n";
                   6975:         $dellock = 'ok';
1.1276    raeburn  6976:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6977:             $dellock = 'nolock';
                   6978:         }
1.1198    raeburn  6979:     }
                   6980:     return ($newid,$dellock,$error);
                   6981: }
                   6982: 
1.1268    raeburn  6983: sub sixnum_code {
                   6984:     my $code;
                   6985:     for (0..6) {
                   6986:         $code .= int( rand(9) );
                   6987:     }
                   6988:     return $code;
                   6989: }
                   6990: 
1.765     albertel 6991: # -------------------------------------------------- portfolio access checking
                   6992: 
                   6993: sub portfolio_access {
1.1270    raeburn  6994:     my ($requrl,$clientip) = @_;
1.765     albertel 6995:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6996:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6997:     if ($result) {
                   6998:         my %setters;
                   6999:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7000:             my ($startblock,$endblock) =
                   7001:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7002:             if ($startblock && $endblock) {
                   7003:                 return 'B';
                   7004:             }
                   7005:         } else {
                   7006:             my ($startblock,$endblock) =
                   7007:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7008:             if ($startblock && $endblock) {
                   7009:                 return 'B';
                   7010:             }
                   7011:         }
                   7012:     }
1.765     albertel 7013:     if ($result eq 'ok') {
1.766     albertel 7014:        return 'F';
1.765     albertel 7015:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7016:        return 'A';
1.765     albertel 7017:     }
1.766     albertel 7018:     return '';
1.765     albertel 7019: }
                   7020: 
                   7021: sub get_portfolio_access {
1.1270    raeburn  7022:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7023: 
                   7024:     if (!ref($access_hash)) {
                   7025: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7026: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7027: 						   $file_name);
                   7028: 	$access_hash = $access_controls{$file_name};
                   7029:     }
                   7030: 
1.1270    raeburn  7031:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7032:     my $now = time;
                   7033:     if (ref($access_hash) eq 'HASH') {
                   7034:         foreach my $key (keys(%{$access_hash})) {
                   7035:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7036:             if ($start > $now) {
                   7037:                 next;
                   7038:             }
                   7039:             if ($end && $end<$now) {
                   7040:                 next;
                   7041:             }
                   7042:             if ($scope eq 'public') {
                   7043:                 $public = $key;
                   7044:                 last;
                   7045:             } elsif ($scope eq 'guest') {
                   7046:                 $guest = $key;
                   7047:             } elsif ($scope eq 'domains') {
                   7048:                 push(@domains,$key);
                   7049:             } elsif ($scope eq 'users') {
                   7050:                 push(@users,$key);
                   7051:             } elsif ($scope eq 'course') {
                   7052:                 push(@courses,$key);
                   7053:             } elsif ($scope eq 'group') {
                   7054:                 push(@groups,$key);
1.1270    raeburn  7055:             } elsif ($scope eq 'ip') {
                   7056:                 push(@ips,$key);
1.765     albertel 7057:             }
                   7058:         }
                   7059:         if ($public) {
                   7060:             return 'ok';
1.1270    raeburn  7061:         } elsif (@ips > 0) {
                   7062:             my $allowed;
                   7063:             foreach my $ipkey (@ips) {
                   7064:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7065:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7066:                         $allowed = 1;
                   7067:                         last; 
                   7068:                     }
                   7069:                 }
                   7070:             }
                   7071:             if ($allowed) {
                   7072:                 return 'ok';
                   7073:             }
1.765     albertel 7074:         }
                   7075:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7076:             if ($guest) {
                   7077:                 return $guest;
                   7078:             }
                   7079:         } else {
                   7080:             if (@domains > 0) {
                   7081:                 foreach my $domkey (@domains) {
                   7082:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7083:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7084:                             return 'ok';
                   7085:                         }
                   7086:                     }
                   7087:                 }
                   7088:             }
                   7089:             if (@users > 0) {
                   7090:                 foreach my $userkey (@users) {
1.865     raeburn  7091:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7092:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7093:                             if (ref($item) eq 'HASH') {
                   7094:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7095:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7096:                                     return 'ok';
                   7097:                                 }
                   7098:                             }
                   7099:                         }
                   7100:                     } 
1.765     albertel 7101:                 }
                   7102:             }
                   7103:             my %roleshash;
                   7104:             my @courses_and_groups = @courses;
                   7105:             push(@courses_and_groups,@groups); 
                   7106:             if (@courses_and_groups > 0) {
                   7107:                 my (%allgroups,%allroles); 
                   7108:                 my ($start,$end,$role,$sec,$group);
                   7109:                 foreach my $envkey (%env) {
1.1060    raeburn  7110:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7111:                         my $cid = $2.'_'.$3; 
                   7112:                         if ($1 eq 'gr') {
                   7113:                             $group = $4;
                   7114:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7115:                         } else {
                   7116:                             if ($4 eq '') {
                   7117:                                 $sec = 'none';
                   7118:                             } else {
                   7119:                                 $sec = $4;
                   7120:                             }
                   7121:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7122:                         }
1.811     albertel 7123:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7124:                         my $cid = $2.'_'.$3;
                   7125:                         if ($4 eq '') {
                   7126:                             $sec = 'none';
                   7127:                         } else {
                   7128:                             $sec = $4;
                   7129:                         }
                   7130:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7131:                     }
                   7132:                 }
                   7133:                 if (keys(%allroles) == 0) {
                   7134:                     return;
                   7135:                 }
                   7136:                 foreach my $key (@courses_and_groups) {
                   7137:                     my %content = %{$$access_hash{$key}};
                   7138:                     my $cnum = $content{'number'};
                   7139:                     my $cdom = $content{'domain'};
                   7140:                     my $cid = $cdom.'_'.$cnum;
                   7141:                     if (!exists($allroles{$cid})) {
                   7142:                         next;
                   7143:                     }    
                   7144:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7145:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7146:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7147:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7148:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7149:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7150:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7151:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7152:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7153:                                         if (grep/^all$/,@sections) {
                   7154:                                             return 'ok';
                   7155:                                         } else {
                   7156:                                             if (grep/^$sec$/,@sections) {
                   7157:                                                 return 'ok';
                   7158:                                             }
                   7159:                                         }
                   7160:                                     }
                   7161:                                 }
                   7162:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7163:                                     if (grep/^none$/,@groups) {
                   7164:                                         return 'ok';
                   7165:                                     }
                   7166:                                 } else {
                   7167:                                     if (grep/^all$/,@groups) {
                   7168:                                         return 'ok';
                   7169:                                     } 
                   7170:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7171:                                         if (grep/^$group$/,@groups) {
                   7172:                                             return 'ok';
                   7173:                                         }
                   7174:                                     }
                   7175:                                 } 
                   7176:                             }
                   7177:                         }
                   7178:                     }
                   7179:                 }
                   7180:             }
                   7181:             if ($guest) {
                   7182:                 return $guest;
                   7183:             }
                   7184:         }
                   7185:     }
                   7186:     return;
                   7187: }
                   7188: 
                   7189: sub course_group_datechecker {
                   7190:     my ($dates,$now,$status) = @_;
                   7191:     my ($start,$end) = split(/\./,$dates);
                   7192:     if (!$start && !$end) {
                   7193:         return 'ok';
                   7194:     }
                   7195:     if (grep/^active$/,@{$status}) {
                   7196:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7197:             return 'ok';
                   7198:         }
                   7199:     }
                   7200:     if (grep/^previous$/,@{$status}) {
                   7201:         if ($end > $now ) {
                   7202:             return 'ok';
                   7203:         }
                   7204:     }
                   7205:     if (grep/^future$/,@{$status}) {
                   7206:         if ($start > $now) {
                   7207:             return 'ok';
                   7208:         }
                   7209:     }
                   7210:     return; 
                   7211: }
                   7212: 
                   7213: sub parse_portfolio_url {
                   7214:     my ($url) = @_;
                   7215: 
                   7216:     my ($type,$udom,$unum,$group,$file_name);
                   7217:     
1.823     albertel 7218:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7219: 	$type = 1;
                   7220:         $udom = $1;
                   7221:         $unum = $2;
                   7222:         $file_name = $3;
1.823     albertel 7223:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7224: 	$type = 2;
                   7225:         $udom = $1;
                   7226:         $unum = $2;
                   7227:         $group = $3;
                   7228:         $file_name = $3.'/'.$4;
                   7229:     }
                   7230:     if (wantarray) {
                   7231: 	return ($type,$udom,$unum,$file_name,$group);
                   7232:     }
                   7233:     return $type;
                   7234: }
                   7235: 
                   7236: sub is_portfolio_url {
                   7237:     my ($url) = @_;
                   7238:     return scalar(&parse_portfolio_url($url));
                   7239: }
                   7240: 
1.798     raeburn  7241: sub is_portfolio_file {
                   7242:     my ($file) = @_;
1.820     raeburn  7243:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7244:         return 1;
                   7245:     }
                   7246:     return;
                   7247: }
                   7248: 
1.976     raeburn  7249: sub usertools_access {
1.1084    raeburn  7250:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7251:     my ($access,%tools);
                   7252:     if ($context eq '') {
                   7253:         $context = 'tools';
                   7254:     }
                   7255:     if ($context eq 'requestcourses') {
                   7256:         %tools = (
                   7257:                       official   => 1,
                   7258:                       unofficial => 1,
1.1006    raeburn  7259:                       community  => 1,
1.1246    raeburn  7260:                       textbook   => 1,
1.1305    raeburn  7261:                       placement  => 1,
1.1368    raeburn  7262:                       lti        => 1,
1.985     raeburn  7263:                  );
1.1183    raeburn  7264:     } elsif ($context eq 'requestauthor') {
                   7265:         %tools = (
                   7266:                       requestauthor => 1,
                   7267:                  );
1.985     raeburn  7268:     } else {
                   7269:         %tools = (
                   7270:                       aboutme   => 1,
                   7271:                       blog      => 1,
1.1177    raeburn  7272:                       webdav    => 1,
1.985     raeburn  7273:                       portfolio => 1,
                   7274:                  );
                   7275:     }
1.976     raeburn  7276:     return if (!defined($tools{$tool}));
                   7277: 
1.1242    raeburn  7278:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7279:         $udom = $env{'user.domain'};
                   7280:         $uname = $env{'user.name'};
                   7281:     }
                   7282: 
1.978     raeburn  7283:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7284:         if ($action ne 'reload') {
1.985     raeburn  7285:             if ($context eq 'requestcourses') {
                   7286:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7287:             } elsif ($context eq 'requestauthor') {
                   7288:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7289:             } else {
                   7290:                 return $env{'environment.availabletools.'.$tool};
                   7291:             }
                   7292:         }
1.976     raeburn  7293:     }
                   7294: 
1.1183    raeburn  7295:     my ($toolstatus,$inststatus,$envkey);
                   7296:     if ($context eq 'requestauthor') {
                   7297:         $envkey = $context; 
                   7298:     } else {
                   7299:         $envkey = $context.'.'.$tool;
                   7300:     }
1.976     raeburn  7301: 
1.985     raeburn  7302:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7303:          ($action ne 'reload')) {
1.1183    raeburn  7304:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7305:         $inststatus = $env{'environment.inststatus'};
                   7306:     } else {
1.1084    raeburn  7307:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7308:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7309:             $inststatus = $userenvref->{'inststatus'};
                   7310:         } else {
1.1183    raeburn  7311:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7312:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7313:             $inststatus = $userenv{'inststatus'};
                   7314:         }
1.976     raeburn  7315:     }
                   7316: 
                   7317:     if ($toolstatus ne '') {
                   7318:         if ($toolstatus) {
                   7319:             $access = 1;
                   7320:         } else {
                   7321:             $access = 0;
                   7322:         }
                   7323:         return $access;
                   7324:     }
                   7325: 
1.1084    raeburn  7326:     my ($is_adv,%domdef);
                   7327:     if (ref($is_advref) eq 'HASH') {
                   7328:         $is_adv = $is_advref->{'is_adv'};
                   7329:     } else {
                   7330:         $is_adv = &is_advanced_user($udom,$uname);
                   7331:     }
                   7332:     if (ref($domdefref) eq 'HASH') {
                   7333:         %domdef = %{$domdefref};
                   7334:     } else {
                   7335:         %domdef = &get_domain_defaults($udom);
                   7336:     }
1.976     raeburn  7337:     if (ref($domdef{$tool}) eq 'HASH') {
                   7338:         if ($is_adv) {
                   7339:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7340:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7341:                     $access = 1;
                   7342:                 } else {
                   7343:                     $access = 0;
                   7344:                 }
                   7345:                 return $access;
                   7346:             }
                   7347:         }
                   7348:         if ($inststatus ne '') {
                   7349:             my ($hasaccess,$hasnoaccess);
                   7350:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7351:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7352:                     if ($domdef{$tool}{$affiliation}) {
                   7353:                         $hasaccess = 1;
                   7354:                     } else {
                   7355:                         $hasnoaccess = 1;
                   7356:                     }
                   7357:                 }
                   7358:             }
                   7359:             if ($hasaccess || $hasnoaccess) {
                   7360:                 if ($hasaccess) {
                   7361:                     $access = 1;
                   7362:                 } elsif ($hasnoaccess) {
                   7363:                     $access = 0; 
                   7364:                 }
                   7365:                 return $access;
                   7366:             }
                   7367:         } else {
                   7368:             if ($domdef{$tool}{'default'} ne '') {
                   7369:                 if ($domdef{$tool}{'default'}) {
                   7370:                     $access = 1;
                   7371:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7372:                     $access = 0;
                   7373:                 }
                   7374:                 return $access;
                   7375:             }
                   7376:         }
                   7377:     } else {
1.1177    raeburn  7378:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7379:             $access = 1;
                   7380:         } else {
                   7381:             $access = 0;
                   7382:         }
1.976     raeburn  7383:         return $access;
                   7384:     }
                   7385: }
                   7386: 
1.1050    raeburn  7387: sub is_course_owner {
                   7388:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7389:     if (($udom eq '') || ($uname eq '')) {
                   7390:         $udom = $env{'user.domain'};
                   7391:         $uname = $env{'user.name'};
                   7392:     }
                   7393:     unless (($udom eq '') || ($uname eq '')) {
                   7394:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7395:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7396:                 return 1;
                   7397:             } else {
                   7398:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7399:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7400:                     return 1;
                   7401:                 }
                   7402:             }
                   7403:         }
                   7404:     }
                   7405:     return;
                   7406: }
                   7407: 
1.976     raeburn  7408: sub is_advanced_user {
                   7409:     my ($udom,$uname) = @_;
1.1085    raeburn  7410:     if ($udom ne '' && $uname ne '') {
                   7411:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7412:             if (wantarray) {
                   7413:                 return ($env{'user.adv'},$env{'user.author'});
                   7414:             } else {
                   7415:                 return $env{'user.adv'};
                   7416:             }
1.1085    raeburn  7417:         }
                   7418:     }
1.976     raeburn  7419:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7420:     my %allroles;
1.1128    raeburn  7421:     my ($is_adv,$is_author);
1.976     raeburn  7422:     foreach my $role (keys(%roleshash)) {
                   7423:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7424:         my $area = '/'.$tdomain.'/'.$trest;
                   7425:         if ($sec ne '') {
                   7426:             $area .= '/'.$sec;
                   7427:         }
                   7428:         if (($area ne '') && ($trole ne '')) {
                   7429:             my $spec=$trole.'.'.$area;
                   7430:             if ($trole =~ /^cr\//) {
                   7431:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7432:             } elsif ($trole ne 'gr') {
                   7433:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7434:             }
1.1128    raeburn  7435:             if ($trole eq 'au') {
                   7436:                 $is_author = 1;
                   7437:             }
1.976     raeburn  7438:         }
                   7439:     }
                   7440:     foreach my $role (keys(%allroles)) {
                   7441:         last if ($is_adv);
                   7442:         foreach my $item (split(/:/,$allroles{$role})) {
                   7443:             if ($item ne '') {
                   7444:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7445:                 if ($privilege eq 'adv') {
                   7446:                     $is_adv = 1;
                   7447:                     last;
                   7448:                 }
                   7449:             }
                   7450:         }
                   7451:     }
1.1128    raeburn  7452:     if (wantarray) {
                   7453:         return ($is_adv,$is_author);
                   7454:     }
1.976     raeburn  7455:     return $is_adv;
                   7456: }
1.798     raeburn  7457: 
1.1035    raeburn  7458: sub check_can_request {
1.1368    raeburn  7459:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7460:     my $canreq = 0;
1.1368    raeburn  7461:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7462:         $uname = $env{'user.name'};
                   7463:         $udom = $env{'user.domain'};
                   7464:     }
1.1035    raeburn  7465:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7466:     my @options = ('approval','validate','autolimit');
                   7467:     my $optregex = join('|',@options);
                   7468:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7469:         foreach my $type (@{$types}) {
1.1368    raeburn  7470:             if (&usertools_access($uname,$udom,$type,undef,
                   7471:                                   'requestcourses')) {
1.1035    raeburn  7472:                 $canreq ++;
1.1036    raeburn  7473:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7474:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7475:                 }
1.1368    raeburn  7476:                 if ($dom eq $udom) {
1.1035    raeburn  7477:                     $can_request->{$type} = 1;
                   7478:                 }
                   7479:             }
1.1368    raeburn  7480:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7481:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7482:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7483:                 if (@curr > 0) {
1.1036    raeburn  7484:                     foreach my $item (@curr) {
                   7485:                         if (ref($request_domains) eq 'HASH') {
                   7486:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7487:                             if ($otherdom ne '') {
                   7488:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7489:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7490:                                         push(@{$request_domains->{$type}},$otherdom);
                   7491:                                     }
                   7492:                                 } else {
                   7493:                                     push(@{$request_domains->{$type}},$otherdom);
                   7494:                                 }
                   7495:                             }
                   7496:                         }
                   7497:                     }
1.1368    raeburn  7498:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7499:                         $canreq ++;
1.1035    raeburn  7500:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7501:                             $can_request->{$type} = 1;
                   7502:                         }
                   7503:                     }
                   7504:                 }
                   7505:             }
                   7506:         }
                   7507:     }
                   7508:     return $canreq;
                   7509: }
                   7510: 
1.341     www      7511: # ---------------------------------------------- Custom access rule evaluation
                   7512: 
                   7513: sub customaccess {
                   7514:     my ($priv,$uri)=@_;
1.807     albertel 7515:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7516:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7517:     $udom = &LONCAPA::clean_domain($udom);
                   7518:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7519:     my $access=0;
1.800     albertel 7520:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7521: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7522: 	if ($type eq 'user') {
                   7523: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7524: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7525: 		if ($tdom) {
                   7526: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7527: 		}
1.896     albertel 7528: 		if ($tuname) {
                   7529: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7530: 		}
                   7531: 		$access=($effect eq 'allow');
                   7532: 		last;
                   7533: 	    }
                   7534: 	} else {
                   7535: 	    if ($role) {
                   7536: 		if ($role ne $urole) { next; }
                   7537: 	    }
                   7538: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7539: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7540: 		if ($tdom) {
                   7541: 		    if ($tdom ne $udom) { next; }
                   7542: 		}
                   7543: 		if ($tcrs) {
                   7544: 		    if ($tcrs ne $ucrs) { next; }
                   7545: 		}
                   7546: 		if ($tsec) {
                   7547: 		    if ($tsec ne $usec) { next; }
                   7548: 		}
                   7549: 		$access=($effect eq 'allow');
                   7550: 		last;
                   7551: 	    }
                   7552: 	    if ($realm eq '' && $role eq '') {
                   7553: 		$access=($effect eq 'allow');
                   7554: 	    }
1.402     bowersj2 7555: 	}
1.341     www      7556:     }
                   7557:     return $access;
                   7558: }
                   7559: 
1.103     harris41 7560: # ------------------------------------------------- Check for a user privilege
1.12      www      7561: 
                   7562: sub allowed {
1.1281    raeburn  7563:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7564:     my $ver_orguri=$uri;
1.439     www      7565:     $uri=&deversion($uri);
1.152     www      7566:     my $orguri=$uri;
1.52      www      7567:     $uri=&declutter($uri);
1.809     raeburn  7568: 
1.810     raeburn  7569:     if ($priv eq 'evb') {
                   7570: # Evade communication block restrictions for specified role in a course
                   7571:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7572:             return $1;
                   7573:         } else {
                   7574:             return;
                   7575:         }
                   7576:     }
                   7577: 
1.620     albertel 7578:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7579: # Free bre access to adm and meta resources
1.1343    raeburn  7580:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7581: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7582: 	&& ($priv eq 'bre')) {
1.14      www      7583: 	return 'F';
1.159     www      7584:     }
                   7585: 
1.545     banghart 7586: # Free bre access to user's own portfolio contents
1.714     raeburn  7587:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7588:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7589: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7590:         my %setters;
                   7591:         my ($startblock,$endblock) = 
                   7592:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7593:         if ($startblock && $endblock) {
                   7594:             return 'B';
                   7595:         } else {
                   7596:             return 'F';
                   7597:         }
1.545     banghart 7598:     }
                   7599: 
1.762     raeburn  7600: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7601:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7602:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7603:         if (exists($env{'request.course.id'})) {
                   7604:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7605:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7606:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7607:                 my $courseprivid=$env{'request.course.id'};
                   7608:                 $courseprivid=~s/\_/\//;
                   7609:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7610:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7611:                     return $1; 
1.762     raeburn  7612:                 } else {
                   7613:                     if ($env{'request.course.sec'}) {
                   7614:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7615:                     }
                   7616:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7617:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7618:                         return $2;
                   7619:                     }
1.714     raeburn  7620:                 }
                   7621:             }
                   7622:         }
                   7623:     }
                   7624: 
1.159     www      7625: # Free bre to public access
                   7626: 
                   7627:     if ($priv eq 'bre') {
1.1362    raeburn  7628:         my $copyright;
                   7629:         unless ($uri =~ /ext\.tool/) {
                   7630:             $copyright=&metadata($uri,'copyright');
                   7631:         }
1.620     albertel 7632: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7633:            return 'F'; 
                   7634:         }
1.238     www      7635:         if ($copyright eq 'priv') {
                   7636:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7637: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7638: 		return '';
                   7639:             }
                   7640:         }
                   7641:         if ($copyright eq 'domain') {
                   7642:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7643: 	    unless (($env{'user.domain'} eq $1) ||
                   7644:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7645: 		return '';
                   7646:             }
1.262     matthew  7647:         }
1.620     albertel 7648:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7649:             # Library role, so allow browsing of resources in this domain.
                   7650:             return 'F';
1.238     www      7651:         }
1.341     www      7652:         if ($copyright eq 'custom') {
                   7653: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7654:         }
1.14      www      7655:     }
1.264     matthew  7656:     # Domain coordinator is trying to create a course
1.620     albertel 7657:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7658:         # uri is the requested domain in this case.
                   7659:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7660:         # a role of dc for the domain in question.
1.620     albertel 7661:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7662:     }
1.29      www      7663: 
1.52      www      7664:     my $thisallowed='';
                   7665:     my $statecond=0;
                   7666:     my $courseprivid='';
                   7667: 
1.1039    raeburn  7668:     my $ownaccess;
1.1043    raeburn  7669:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7670:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7671:         if ($uri eq '') {
                   7672:             $ownaccess = 1;
                   7673:         } else {
                   7674:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7675:                 my $udom = $env{'user.domain'};
                   7676:                 my $uname = $env{'user.name'};
                   7677:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7678:                     $ownaccess = 1;
1.1040    raeburn  7679:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7680:                     unless ($uri =~ m{\.\./}) {
                   7681:                         $ownaccess = 1;
                   7682:                     }
                   7683:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7684:                     my $now = time;
                   7685:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7686:                         my $adom = $1;
                   7687:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7688:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7689:                                 my ($start,$end) = split('.',$env{$key});
                   7690:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7691:                                     $ownaccess = 1;
                   7692:                                     last;
                   7693:                                 }
                   7694:                             }
                   7695:                         }
                   7696:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7697:                         my $adom = $1;
                   7698:                         my $aname = $2;
1.1042    raeburn  7699:                         foreach my $role ('ca','aa') { 
                   7700:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7701:                                 my ($start,$end) =
                   7702:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7703:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7704:                                     $ownaccess = 1;
                   7705:                                     last;
                   7706:                                 }
1.1039    raeburn  7707:                             }
                   7708:                         }
                   7709:                     }
                   7710:                 }
                   7711:             }
                   7712:         }
                   7713:     }
                   7714: 
1.52      www      7715: # Course
                   7716: 
1.620     albertel 7717:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7718:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7719:             $thisallowed.=$1;
                   7720:         }
1.52      www      7721:     }
1.29      www      7722: 
1.52      www      7723: # Domain
                   7724: 
1.620     albertel 7725:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7726:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7727:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7728:             $thisallowed.=$1;
                   7729:         }
1.12      www      7730:     }
1.52      www      7731: 
1.1141    raeburn  7732: # User who is not author or co-author might still be able to edit
                   7733: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7734:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7735:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7736:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7737:             $thisallowed.=$1;
                   7738:         }
                   7739:     }
                   7740: 
1.52      www      7741: # Course: uri itself is a course
1.66      www      7742:     my $courseuri=$uri;
                   7743:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7744:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7745: 
1.620     albertel 7746:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7747:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7748:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7749:             $thisallowed.=$1;
                   7750:         }
1.12      www      7751:     }
1.29      www      7752: 
1.665     albertel 7753: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7754: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7755:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7756: 	$thisallowed='';
1.671     raeburn  7757:         my ($match)=&is_on_map($uri);
                   7758:         if ($match) {
                   7759:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7760:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7761:                 my $value = $1;
                   7762:                 if ($noblockcheck) {
                   7763:                     $thisallowed.=$value;
1.1162    raeburn  7764:                 } else {
1.1281    raeburn  7765:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7766:                     if (@blockers > 0) {
                   7767:                         $thisallowed = 'B';
                   7768:                     } else {
                   7769:                         $thisallowed.=$value;
                   7770:                     }
1.1162    raeburn  7771:                 }
1.671     raeburn  7772:             }
                   7773:         } else {
1.705     albertel 7774:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7775:             if ($refuri) {
                   7776:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7777:                     $thisallowed='F';
1.671     raeburn  7778:                 } else {
                   7779:                     $refuri=&declutter($refuri);
                   7780:                     my ($match) = &is_on_map($refuri);
                   7781:                     if ($match) {
1.1281    raeburn  7782:                         if ($noblockcheck) {
                   7783:                             $thisallowed='F';
1.1162    raeburn  7784:                         } else {
1.1281    raeburn  7785:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7786:                             if (@blockers > 0) {
                   7787:                                 $thisallowed = 'B';
                   7788:                             } else {
                   7789:                                 $thisallowed='F';
                   7790:                             }
1.1162    raeburn  7791:                         }
1.671     raeburn  7792:                     }
1.669     raeburn  7793:                 }
1.671     raeburn  7794:             }
                   7795:         }
1.314     www      7796:     }
1.492     albertel 7797: 
1.766     albertel 7798:     if ($priv eq 'bre'
                   7799: 	&& $thisallowed ne 'F' 
                   7800: 	&& $thisallowed ne '2'
                   7801: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7802: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7803:     }
1.1250    raeburn  7804: 
1.52      www      7805: # Full access at system, domain or course-wide level? Exit.
1.29      www      7806:     if ($thisallowed=~/F/) {
                   7807: 	return 'F';
                   7808:     }
                   7809: 
1.52      www      7810: # If this is generating or modifying users, exit with special codes
1.29      www      7811: 
1.643     www      7812:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7813: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7814: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7815: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7816: 	    unless ($auname) { return $thisallowed; }
                   7817: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7818: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7819: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7820: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7821: 	}
1.52      www      7822: 	return $thisallowed;
                   7823:     }
                   7824: #
1.103     harris41 7825: # Gathered so far: system, domain and course wide privileges
1.52      www      7826: #
                   7827: # Course: See if uri or referer is an individual resource that is part of 
                   7828: # the course
                   7829: 
1.620     albertel 7830:     if ($env{'request.course.id'}) {
1.232     www      7831: 
1.620     albertel 7832:        $courseprivid=$env{'request.course.id'};
                   7833:        if ($env{'request.course.sec'}) {
                   7834:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7835:        }
                   7836:        $courseprivid=~s/\_/\//;
                   7837:        my $checkreferer=1;
1.232     www      7838:        my ($match,$cond)=&is_on_map($uri);
                   7839:        if ($match) {
                   7840:            $statecond=$cond;
1.620     albertel 7841:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7842:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7843:                my $value = $1;
                   7844:                if ($priv eq 'bre') {
1.1281    raeburn  7845:                    if ($noblockcheck) {
                   7846:                        $thisallowed.=$value;
1.1162    raeburn  7847:                    } else {
1.1281    raeburn  7848:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7849:                        if (@blockers > 0) {
                   7850:                            $thisallowed = 'B';
                   7851:                        } else {
                   7852:                            $thisallowed.=$value;
                   7853:                        }
1.1162    raeburn  7854:                    }
                   7855:                } else {
                   7856:                    $thisallowed.=$value;
                   7857:                }
1.52      www      7858:                $checkreferer=0;
                   7859:            }
1.29      www      7860:        }
1.83      www      7861:        
1.148     www      7862:        if ($checkreferer) {
1.620     albertel 7863: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7864:             unless ($refuri) {
1.800     albertel 7865:                 foreach my $key (keys(%env)) {
                   7866: 		    if ($key=~/^httpref\..*\*/) {
                   7867: 			my $pattern=$key;
1.156     www      7868:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7869:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7870:                         $pattern=~s/\//\\\//g;
1.152     www      7871:                         if ($orguri=~/$pattern/) {
1.800     albertel 7872: 			    $refuri=$env{$key};
1.148     www      7873:                         }
                   7874:                     }
1.191     harris41 7875:                 }
1.148     www      7876:             }
1.232     www      7877: 
1.148     www      7878:          if ($refuri) { 
1.152     www      7879: 	  $refuri=&declutter($refuri);
1.232     www      7880:           my ($match,$cond)=&is_on_map($refuri);
                   7881:             if ($match) {
                   7882:               my $refstatecond=$cond;
1.620     albertel 7883:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7884:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7885:                   my $value = $1;
                   7886:                   if ($priv eq 'bre') {
1.1281    raeburn  7887:                       if ($noblockcheck) {
                   7888:                           $thisallowed.=$value;
1.1162    raeburn  7889:                       } else {
1.1281    raeburn  7890:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7891:                           if (@blockers > 0) {
                   7892:                               $thisallowed = 'B';
                   7893:                           } else {
                   7894:                               $thisallowed.=$value;
                   7895:                           }
1.1162    raeburn  7896:                       }
                   7897:                   } else {
                   7898:                       $thisallowed.=$value;
                   7899:                   }
1.53      www      7900:                   $uri=$refuri;
                   7901:                   $statecond=$refstatecond;
1.52      www      7902:               }
                   7903:           }
1.148     www      7904:         }
1.29      www      7905:        }
1.52      www      7906:    }
1.29      www      7907: 
1.52      www      7908: #
1.103     harris41 7909: # Gathered now: all privileges that could apply, and condition number
1.52      www      7910: # 
                   7911: #
                   7912: # Full or no access?
                   7913: #
1.29      www      7914: 
1.52      www      7915:     if ($thisallowed=~/F/) {
                   7916: 	return 'F';
                   7917:     }
1.29      www      7918: 
1.52      www      7919:     unless ($thisallowed) {
                   7920:         return '';
                   7921:     }
1.29      www      7922: 
1.52      www      7923: # Restrictions exist, deal with them
                   7924: #
                   7925: #   C:according to course preferences
                   7926: #   R:according to resource settings
                   7927: #   L:unless locked
                   7928: #   X:according to user session state
                   7929: #
                   7930: 
                   7931: # Possibly locked functionality, check all courses
1.54      www      7932: # Locks might take effect only after 10 minutes cache expiration for other
                   7933: # courses, and 2 minutes for current course
1.52      www      7934: 
                   7935:     my $envkey;
                   7936:     if ($thisallowed=~/L/) {
1.1000    raeburn  7937:         foreach $envkey (keys(%env)) {
1.54      www      7938:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7939:                my $courseid=$2;
                   7940:                my $roleid=$1.'.'.$2;
1.92      www      7941:                $courseid=~s/^\///;
1.54      www      7942:                my $expiretime=600;
1.620     albertel 7943:                if ($env{'request.role'} eq $roleid) {
1.54      www      7944: 		  $expiretime=120;
                   7945:                }
                   7946: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7947:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7948:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7949: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7950:                }
1.620     albertel 7951:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7952:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7953: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7954:                        &log($env{'user.domain'},$env{'user.name'},
                   7955:                             $env{'user.home'},
1.57      www      7956:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7957:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7958:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7959: 		       return '';
                   7960:                    }
                   7961:                }
1.620     albertel 7962:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7963:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7964: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7965:                        &log($env{'user.domain'},$env{'user.name'},
                   7966:                             $env{'user.home'},
1.57      www      7967:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7968:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7969:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7970: 		       return '';
                   7971:                    }
                   7972:                }
                   7973: 	   }
1.29      www      7974:        }
1.52      www      7975:     }
                   7976:    
                   7977: #
                   7978: # Rest of the restrictions depend on selected course
                   7979: #
                   7980: 
1.620     albertel 7981:     unless ($env{'request.course.id'}) {
1.766     albertel 7982: 	if ($thisallowed eq 'A') {
                   7983: 	    return 'A';
1.814     raeburn  7984:         } elsif ($thisallowed eq 'B') {
                   7985:             return 'B';
1.766     albertel 7986: 	} else {
                   7987: 	    return '1';
                   7988: 	}
1.52      www      7989:     }
1.29      www      7990: 
1.52      www      7991: #
                   7992: # Now user is definitely in a course
                   7993: #
1.53      www      7994: 
                   7995: 
                   7996: # Course preferences
                   7997: 
                   7998:    if ($thisallowed=~/C/) {
1.620     albertel 7999:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8000:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8001:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8002: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8003: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8004: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8005: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8006: 			$env{'request.course.id'});
                   8007: 	   }
1.237     www      8008:            return '';
                   8009:        }
                   8010: 
1.620     albertel 8011:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8012: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8013: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8014: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8015: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8016: 			$env{'request.course.id'});
                   8017: 	   }
1.54      www      8018:            return '';
                   8019:        }
1.53      www      8020:    }
                   8021: 
                   8022: # Resource preferences
                   8023: 
                   8024:    if ($thisallowed=~/R/) {
1.620     albertel 8025:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8026:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8027: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8028: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8029: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8030: 	   }
                   8031: 	   return '';
1.54      www      8032:        }
1.53      www      8033:    }
1.30      www      8034: 
1.246     www      8035: # Restricted by state or randomout?
1.30      www      8036: 
1.52      www      8037:    if ($thisallowed=~/X/) {
1.620     albertel 8038:       if ($env{'acc.randomout'}) {
1.579     albertel 8039: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8040:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8041:             return ''; 
                   8042:          }
1.247     www      8043:       }
                   8044:       if (&condval($statecond)) {
1.52      www      8045: 	 return '2';
                   8046:       } else {
                   8047:          return '';
                   8048:       }
                   8049:    }
1.30      www      8050: 
1.766     albertel 8051:     if ($thisallowed eq 'A') {
                   8052: 	return 'A';
1.814     raeburn  8053:     } elsif ($thisallowed eq 'B') {
                   8054:         return 'B';
1.766     albertel 8055:     }
1.52      www      8056:    return 'F';
1.232     www      8057: }
1.1162    raeburn  8058: 
1.1192    raeburn  8059: # ------------------------------------------- Check construction space access
                   8060: 
                   8061: sub constructaccess {
                   8062:     my ($url,$setpriv)=@_;
                   8063: 
                   8064: # We do not allow editing of previous versions of files
                   8065:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8066: 
                   8067: # Get username and domain from URL
                   8068:     my ($ownername,$ownerdomain,$ownerhome);
                   8069: 
                   8070:     ($ownerdomain,$ownername) =
1.1325    raeburn  8071:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8072: 
                   8073: # The URL does not really point to any authorspace, forget it
                   8074:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8075: 
                   8076: # Now we need to see if the user has access to the authorspace of
                   8077: # $ownername at $ownerdomain
                   8078: 
                   8079:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8080: # Real author for this?
                   8081:        $ownerhome = $env{'user.home'};
                   8082:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8083:           return ($ownername,$ownerdomain,$ownerhome);
                   8084:        }
                   8085:     } else {
                   8086: # Co-author for this?
                   8087:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8088:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8089:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8090:             return ($ownername,$ownerdomain,$ownerhome);
                   8091:         }
1.1312    raeburn  8092:         if ($env{'request.course.id'}) {
                   8093:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8094:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8095:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8096:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8097:                     return ($ownername,$ownerdomain,$ownerhome);
                   8098:                 }
                   8099:             }
                   8100:         }
1.1192    raeburn  8101:     }
                   8102: 
                   8103: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8104: # we might as well leave
                   8105:    unless ($setpriv) { return ''; }
                   8106: 
                   8107: # Backdoor access?
                   8108:     my $allowed=&allowed('eco',$ownerdomain);
                   8109: # Nope
                   8110:     unless ($allowed) { return ''; }
                   8111: # Looks like we may have access, but could be locked by the owner of the construction space
                   8112:     if ($allowed eq 'U') {
                   8113:         my %blocked=&get('environment',['domcoord.author'],
                   8114:                          $ownerdomain,$ownername);
                   8115: # Is blocked by owner
                   8116:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8117:     }
                   8118:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8119: # Grant temporary access
                   8120:         my $then=$env{'user.login.time'};
1.1209    raeburn  8121:         my $update=$env{'user.update.time'};
1.1192    raeburn  8122:         if (!$update) { $update = $then; }
                   8123:         my $refresh=$env{'user.refresh.time'};
                   8124:         if (!$refresh) { $refresh = $update; }
                   8125:         my $now = time;
                   8126:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8127:                            $now,'ca','constructaccess');
                   8128:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8129:         return($ownername,$ownerdomain,$ownerhome);
                   8130:     }
                   8131: # No business here
                   8132:     return '';
                   8133: }
                   8134: 
1.1282    raeburn  8135: # ----------------------------------------------------------- Content Blocking
                   8136: 
                   8137: {
                   8138: # Caches for faster Course Contents display where content blocking
                   8139: # is in operation (i.e., interval param set) for timed quiz.
                   8140: #
                   8141: # User for whom data are being temporarily cached.
                   8142: my $cacheduser='';
                   8143: # Cached blockers for this user (a hash of blocking items). 
                   8144: my %cachedblockers=();
                   8145: # When the data were last cached.
                   8146: my $cachedlast='';
                   8147: 
                   8148: sub load_all_blockers {
                   8149:     my ($uname,$udom,$blocks)=@_;
                   8150:     if (($uname ne '') && ($udom ne '')) { 
                   8151:         if (($cacheduser eq $uname.':'.$udom) &&
                   8152:             (abs($cachedlast-time)<5)) {
                   8153:             return;
                   8154:         }
                   8155:     }
                   8156:     $cachedlast=time;
                   8157:     $cacheduser=$uname.':'.$udom;
                   8158:     %cachedblockers = &get_commblock_resources($blocks);
                   8159: }
                   8160: 
1.1162    raeburn  8161: sub get_comm_blocks {
                   8162:     my ($cdom,$cnum) = @_;
                   8163:     if ($cdom eq '' || $cnum eq '') {
                   8164:         return unless ($env{'request.course.id'});
                   8165:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8166:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8167:     }
                   8168:     my %commblocks;
                   8169:     my $hashid=$cdom.'_'.$cnum;
                   8170:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8171:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8172:         %commblocks = %{$blocksref};
                   8173:     } else {
                   8174:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8175:         my $cachetime = 600;
                   8176:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8177:     }
                   8178:     return %commblocks;
                   8179: }
                   8180: 
1.1282    raeburn  8181: sub get_commblock_resources {
                   8182:     my ($blocks) = @_;
                   8183:     my %blockers = ();
                   8184:     return %blockers unless ($env{'request.course.id'});
                   8185:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8186:     my %commblocks;
                   8187:     if (ref($blocks) eq 'HASH') {
                   8188:         %commblocks = %{$blocks};
                   8189:     } else {
                   8190:         %commblocks = &get_comm_blocks();
                   8191:     }
1.1282    raeburn  8192:     return %blockers unless (keys(%commblocks) > 0); 
                   8193:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8194:     return %blockers unless (ref($navmap));
1.1162    raeburn  8195:     my $now = time;
                   8196:     foreach my $block (keys(%commblocks)) {
                   8197:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8198:             my ($start,$end) = ($1,$2);
                   8199:             if ($start <= $now && $end >= $now) {
                   8200:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8201:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8202:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8203:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8204:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8205:                             }
                   8206:                         }
                   8207:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8208:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8209:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8210:                             }
                   8211:                         }
                   8212:                     }
                   8213:                 }
                   8214:             }
                   8215:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8216:             my $item = $1;
1.1163    raeburn  8217:             my @to_test;
1.1162    raeburn  8218:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8219:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8220:                     my @interval;
                   8221:                     my $type = 'map';
                   8222:                     if ($item eq 'course') {
                   8223:                         $type = 'course';
                   8224:                         @interval=&EXT("resource.0.interval");
                   8225:                     } else {
                   8226:                         if ($item =~ /___\d+___/) {
                   8227:                             $type = 'resource';
                   8228:                             @interval=&EXT("resource.0.interval",$item);
                   8229:                             if (ref($navmap)) {                        
                   8230:                                 my $res = $navmap->getBySymb($item); 
                   8231:                                 push(@to_test,$res);
                   8232:                             }
1.1162    raeburn  8233:                         } else {
1.1282    raeburn  8234:                             my $mapsymb = &symbread($item,1);
                   8235:                             if ($mapsymb) {
                   8236:                                 if (ref($navmap)) {
                   8237:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8238:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8239:                                     foreach my $res (@to_test) {
                   8240:                                         my $symb = $res->symb();
                   8241:                                         next if ($symb eq $mapsymb);
                   8242:                                         if ($symb ne '') {
                   8243:                                             @interval=&EXT("resource.0.interval",$symb);
                   8244:                                             if ($interval[1] eq 'map') {
                   8245:                                                 last;
1.1162    raeburn  8246:                                             }
                   8247:                                         }
                   8248:                                     }
                   8249:                                 }
                   8250:                             }
                   8251:                         }
1.1282    raeburn  8252:                     }
1.1310    raeburn  8253:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8254:                         my $timelimit = $1; 
1.1282    raeburn  8255:                         my $first_access;
                   8256:                         if ($type eq 'resource') {
                   8257:                             $first_access=&get_first_access($interval[1],$item);
                   8258:                         } elsif ($type eq 'map') {
                   8259:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8260:                         } else {
                   8261:                             $first_access=&get_first_access($interval[1]);
                   8262:                         }
                   8263:                         if ($first_access) {
1.1292    raeburn  8264:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8265:                             if ($timesup > $now) {
                   8266:                                 my $activeblock;
                   8267:                                 foreach my $res (@to_test) {
1.1283    raeburn  8268:                                     if ($res->answerable()) {
1.1282    raeburn  8269:                                         $activeblock = 1;
                   8270:                                         last;
                   8271:                                     }
                   8272:                                 }
                   8273:                                 if ($activeblock) {
                   8274:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8275:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8276:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8277:                                          }
                   8278:                                     }
                   8279:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8280:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8281:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8282:                                         }
1.1162    raeburn  8283:                                     }
                   8284:                                 }
                   8285:                             }
                   8286:                         }
                   8287:                     }
                   8288:                 }
                   8289:             }
                   8290:         }
                   8291:     }
1.1282    raeburn  8292:     return %blockers;
1.1162    raeburn  8293: }
                   8294: 
1.1282    raeburn  8295: sub has_comm_blocking {
                   8296:     my ($priv,$symb,$uri,$blocks) = @_;
                   8297:     my @blockers;
                   8298:     return unless ($env{'request.course.id'});
                   8299:     return unless ($priv eq 'bre');
                   8300:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8301:     return if ($env{'request.state'} eq 'construct');
                   8302:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8303:     return unless (keys(%cachedblockers) > 0);
                   8304:     my (%possibles,@symbs);
                   8305:     if (!$symb) {
                   8306:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8307:     }
1.1282    raeburn  8308:     if ($symb) {
                   8309:         @symbs = ($symb);
                   8310:     } elsif (keys(%possibles)) { 
                   8311:         @symbs = keys(%possibles);
                   8312:     }
                   8313:     my $noblock;
                   8314:     foreach my $symb (@symbs) {
                   8315:         last if ($noblock);
                   8316:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8317:         foreach my $block (keys(%cachedblockers)) {
                   8318:             if ($block =~ /^firstaccess____(.+)$/) {
                   8319:                 my $item = $1;
                   8320:                 if (($item eq $map) || ($item eq $symb)) {
                   8321:                     $noblock = 1;
                   8322:                     last;
                   8323:                 }
                   8324:             }
                   8325:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8326:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8327:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8328:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8329:                             push(@blockers,$block);
                   8330:                         }
                   8331:                     }
                   8332:                 }
1.1162    raeburn  8333:             }
1.1282    raeburn  8334:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8335:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8336:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8337:                         push(@blockers,$block);
                   8338:                     }
                   8339:                 }
1.1162    raeburn  8340:             }
                   8341:         }
                   8342:     }
1.1282    raeburn  8343:     return if ($noblock);
                   8344:     return @blockers;
                   8345: }
1.1162    raeburn  8346: }
                   8347: 
1.1282    raeburn  8348: # -------------------------------- Deversion and split uri into path an filename   
                   8349: 
1.1133    foxr     8350: #
1.1282    raeburn  8351: #   Removes the version from a URI and
1.1133    foxr     8352: #   splits it in to its filename and path to the filename.
                   8353: #   Seems like File::Basename could have done this more clearly.
                   8354: #   Parameters:
                   8355: #      $uri   - input URI
                   8356: #   Returns:
                   8357: #     Two element list consisting of 
                   8358: #     $pathname  - the URI up to and excluding the trailing /
                   8359: #     $filename  - The part of the URI following the last /
                   8360: #  NOTE:
                   8361: #    Another realization of this is simply:
                   8362: #    use File::Basename;
                   8363: #    ...
                   8364: #    $uri = shift;
                   8365: #    $filename = basename($uri);
                   8366: #    $path     = dirname($uri);
                   8367: #    return ($filename, $path);
                   8368: #
                   8369: #     The implementation below is probably faster however.
                   8370: #
1.710     albertel 8371: sub split_uri_for_cond {
                   8372:     my $uri=&deversion(&declutter(shift));
                   8373:     my @uriparts=split(/\//,$uri);
                   8374:     my $filename=pop(@uriparts);
                   8375:     my $pathname=join('/',@uriparts);
                   8376:     return ($pathname,$filename);
                   8377: }
1.232     www      8378: # --------------------------------------------------- Is a resource on the map?
                   8379: 
                   8380: sub is_on_map {
1.710     albertel 8381:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8382:     #Trying to find the conditional for the file
1.620     albertel 8383:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8384: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8385:     if ($match) {
1.289     bowersj2 8386: 	return (1,$1);
                   8387:     } else {
1.434     www      8388: 	return (0,0);
1.289     bowersj2 8389:     }
1.12      www      8390: }
                   8391: 
1.427     www      8392: # --------------------------------------------------------- Get symb from alias
                   8393: 
                   8394: sub get_symb_from_alias {
                   8395:     my $symb=shift;
                   8396:     my ($map,$resid,$url)=&decode_symb($symb);
                   8397: # Already is a symb
                   8398:     if ($url) { return $symb; }
                   8399: # Must be an alias
                   8400:     my $aliassymb='';
                   8401:     my %bighash;
1.620     albertel 8402:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8403:                             &GDBM_READER(),0640)) {
                   8404:         my $rid=$bighash{'mapalias_'.$symb};
                   8405: 	if ($rid) {
                   8406: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8407: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8408: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8409: 	}
                   8410:         untie %bighash;
                   8411:     }
                   8412:     return $aliassymb;
                   8413: }
                   8414: 
1.12      www      8415: # ----------------------------------------------------------------- Define Role
                   8416: 
                   8417: sub definerole {
                   8418:   if (allowed('mcr','/')) {
1.1326    raeburn  8419:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8420:     foreach my $role (split(':',$sysrole)) {
                   8421: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8422:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8423:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8424: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8425:                return "refused:s:$crole&$cqual"; 
                   8426:             }
                   8427:         }
1.191     harris41 8428:     }
1.800     albertel 8429:     foreach my $role (split(':',$domrole)) {
                   8430: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8431:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8432:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8433: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8434:                return "refused:d:$crole&$cqual"; 
                   8435:             }
                   8436:         }
1.191     harris41 8437:     }
1.800     albertel 8438:     foreach my $role (split(':',$courole)) {
                   8439: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8440:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8441:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8442: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8443:                return "refused:c:$crole&$cqual"; 
                   8444:             }
                   8445:         }
1.191     harris41 8446:     }
1.1326    raeburn  8447:     my $uhome;
                   8448:     if (($uname ne '') && ($udom ne '')) {
                   8449:         $uhome = &homeserver($uname,$udom);
                   8450:         return $uhome if ($uhome eq 'no_host');
                   8451:     } else {
                   8452:         $uname = $env{'user.name'};
                   8453:         $udom = $env{'user.domain'};
                   8454:         $uhome = $env{'user.home'};
                   8455:     }
1.620     albertel 8456:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8457:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8458:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8459:     return reply($command,$uhome);
1.12      www      8460:   } else {
                   8461:     return 'refused';
                   8462:   }
1.105     harris41 8463: }
                   8464: 
                   8465: # ---------------- Make a metadata query against the network of library servers
                   8466: 
                   8467: sub metadata_query {
1.1237    raeburn  8468:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8469:     my %rhash;
1.845     albertel 8470:     my %libserv = &all_library();
1.244     matthew  8471:     my @server_list = (defined($server_array) ? @$server_array
                   8472:                                               : keys(%libserv) );
                   8473:     for my $server (@server_list) {
1.1237    raeburn  8474:         my $domains = ''; 
                   8475:         if (ref($domains_hash) eq 'HASH') {
                   8476:             $domains = $domains_hash->{$server}; 
                   8477:         }
1.118     harris41 8478: 	unless ($custom or $customshow) {
1.1237    raeburn  8479: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8480: 	    $rhash{$server}=$reply;
                   8481: 	}
                   8482: 	else {
                   8483: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8484: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8485: 			     $server);
                   8486: 	    $rhash{$server}=$reply;
                   8487: 	}
1.112     harris41 8488:     }
1.118     harris41 8489:     return \%rhash;
1.240     www      8490: }
                   8491: 
                   8492: # ----------------------------------------- Send log queries and wait for reply
                   8493: 
                   8494: sub log_query {
                   8495:     my ($uname,$udom,$query,%filters)=@_;
                   8496:     my $uhome=&homeserver($uname,$udom);
                   8497:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8498:     my $uhost=&hostname($uhome);
1.800     albertel 8499:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8500:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8501:                        $uhome);
1.479     albertel 8502:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8503:     return get_query_reply($queryid);
                   8504: }
                   8505: 
1.818     raeburn  8506: # -------------------------- Update MySQL table for portfolio file
                   8507: 
                   8508: sub update_portfolio_table {
1.821     raeburn  8509:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8510:     if ($group ne '') {
                   8511:         $file_name =~s /^\Q$group\E//;
                   8512:     }
1.818     raeburn  8513:     my $homeserver = &homeserver($uname,$udom);
                   8514:     my $queryid=
1.821     raeburn  8515:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8516:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8517:     my $reply = &get_query_reply($queryid);
                   8518:     return $reply;
                   8519: }
                   8520: 
1.899     raeburn  8521: # -------------------------- Update MySQL allusers table
                   8522: 
                   8523: sub update_allusers_table {
                   8524:     my ($uname,$udom,$names) = @_;
                   8525:     my $homeserver = &homeserver($uname,$udom);
                   8526:     my $queryid=
                   8527:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8528:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8529:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8530:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8531:                'generation='.&escape($names->{'generation'}).'%%'.
                   8532:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8533:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8534:     return;
1.899     raeburn  8535: }
                   8536: 
1.508     raeburn  8537: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8538: 
                   8539: sub fetch_enrollment_query {
1.511     raeburn  8540:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8541:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8542:     my $maxtries = 1;
1.508     raeburn  8543:     if ($context eq 'automated') {
                   8544:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8545:         $sleep = 2;
                   8546:         $loopmax = 100;
1.547     raeburn  8547:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8548:     } else {
                   8549:         $homeserver = &homeserver($cnum,$dom);
                   8550:     }
1.838     albertel 8551:     my $host=&hostname($homeserver);
1.506     raeburn  8552:     my $cmd = '';
1.1000    raeburn  8553:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8554:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8555:     }
                   8556:     $cmd =~ s/%%$//;
                   8557:     $cmd = &escape($cmd);
                   8558:     my $query = 'fetchenrollment';
1.620     albertel 8559:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8560:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8561:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8562:         return 'error: '.$queryid;
                   8563:     }
1.1317    raeburn  8564:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8565:     my $tries = 1;
                   8566:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8567:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8568:         $tries ++;
                   8569:     }
1.526     raeburn  8570:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8571:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8572:     } else {
1.901     albertel 8573:         my @responses = split(/:/,$reply);
1.1322    raeburn  8574:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8575:             foreach my $line (@responses) {
                   8576:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8577:                 $$replyref{$key} = $value;
                   8578:             }
                   8579:         } else {
1.1117    foxr     8580:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8581:             foreach my $line (@responses) {
                   8582:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8583:                 $$replyref{$key} = $value;
                   8584:                 if ($value > 0) {
1.800     albertel 8585:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8586:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8587:                         my $destname = $pathname.'/'.$filename;
                   8588:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8589:                         if ($xml_classlist =~ /^error/) {
                   8590:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8591:                         } else {
1.1359    raeburn  8592:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8593:                                 print FILE &unescape($xml_classlist);
                   8594:                                 close(FILE);
1.526     raeburn  8595:                             } else {
                   8596:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8597:                             }
                   8598:                         }
                   8599:                     }
                   8600:                 }
                   8601:             }
                   8602:         }
                   8603:         return 'ok';
                   8604:     }
                   8605:     return 'error';
                   8606: }
                   8607: 
1.242     www      8608: sub get_query_reply {
1.1317    raeburn  8609:     my ($queryid,$sleep,$loopmax) = @_;;
                   8610:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8611:         $sleep = 0.2;
                   8612:     }
                   8613:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8614:         $loopmax = 100;
                   8615:     }
1.1117    foxr     8616:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8617:     my $reply='';
1.1317    raeburn  8618:     for (1..$loopmax) {
                   8619: 	sleep($sleep);
1.240     www      8620:         if (-e $replyfile.'.end') {
1.1359    raeburn  8621: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8622: 		$reply = join('',<$fh>);
                   8623: 		close($fh);
1.240     www      8624: 	   } else { return 'error: reply_file_error'; }
1.242     www      8625:            return &unescape($reply);
                   8626: 	}
1.240     www      8627:     }
1.242     www      8628:     return 'timeout:'.$queryid;
1.240     www      8629: }
                   8630: 
                   8631: sub courselog_query {
1.241     www      8632: #
                   8633: # possible filters:
                   8634: # url: url or symb
                   8635: # username
                   8636: # domain
                   8637: # action: view, submit, grade
                   8638: # start: timestamp
                   8639: # end: timestamp
                   8640: #
1.240     www      8641:     my (%filters)=@_;
1.620     albertel 8642:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8643:     if ($filters{'url'}) {
                   8644: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8645:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8646:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8647:     }
1.620     albertel 8648:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8649:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8650:     return &log_query($cname,$cdom,'courselog',%filters);
                   8651: }
                   8652: 
                   8653: sub userlog_query {
1.858     raeburn  8654: #
                   8655: # possible filters:
                   8656: # action: log check role
                   8657: # start: timestamp
                   8658: # end: timestamp
                   8659: #
1.240     www      8660:     my ($uname,$udom,%filters)=@_;
                   8661:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8662: }
                   8663: 
1.506     raeburn  8664: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8665: 
                   8666: sub auto_run {
1.508     raeburn  8667:     my ($cnum,$cdom) = @_;
1.876     raeburn  8668:     my $response = 0;
                   8669:     my $settings;
                   8670:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8671:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8672:         $settings = $domconfig{'autoenroll'};
                   8673:         if ($settings->{'run'} eq '1') {
                   8674:             $response = 1;
                   8675:         }
                   8676:     } else {
1.934     raeburn  8677:         my $homeserver;
                   8678:         if (&is_course($cdom,$cnum)) {
                   8679:             $homeserver = &homeserver($cnum,$cdom);
                   8680:         } else {
                   8681:             $homeserver = &domain($cdom,'primary');
                   8682:         }
                   8683:         if ($homeserver ne 'no_host') {
                   8684:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8685:         }
1.876     raeburn  8686:     }
1.506     raeburn  8687:     return $response;
                   8688: }
1.776     albertel 8689: 
1.506     raeburn  8690: sub auto_get_sections {
1.508     raeburn  8691:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8692:     my $homeserver;
                   8693:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8694:         $homeserver = &homeserver($cnum,$cdom);
                   8695:     }
                   8696:     if (!defined($homeserver)) { 
                   8697:         if ($cdom =~ /^$match_domain$/) {
                   8698:             $homeserver = &domain($cdom,'primary');
                   8699:         }
                   8700:     }
                   8701:     my @secs;
                   8702:     if (defined($homeserver)) {
                   8703:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8704:         unless ($response eq 'refused') {
                   8705:             @secs = split(/:/,$response);
                   8706:         }
1.506     raeburn  8707:     }
                   8708:     return @secs;
                   8709: }
1.776     albertel 8710: 
1.506     raeburn  8711: sub auto_new_course {
1.1099    raeburn  8712:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8713:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8714:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8715:     return $response;
                   8716: }
1.776     albertel 8717: 
1.506     raeburn  8718: sub auto_validate_courseID {
1.508     raeburn  8719:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8720:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8721:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8722:     return $response;
                   8723: }
1.776     albertel 8724: 
1.1007    raeburn  8725: sub auto_validate_instcode {
1.1020    raeburn  8726:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8727:     my ($homeserver,$response);
                   8728:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8729:         $homeserver = &homeserver($cnum,$cdom);
                   8730:     }
                   8731:     if (!defined($homeserver)) {
                   8732:         if ($cdom =~ /^$match_domain$/) {
                   8733:             $homeserver = &domain($cdom,'primary');
                   8734:         }
                   8735:     }
1.1065    raeburn  8736:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8737:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8738:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8739:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8740: }
                   8741: 
1.506     raeburn  8742: sub auto_create_password {
1.873     raeburn  8743:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8744:     my ($homeserver,$response);
1.506     raeburn  8745:     my $create_passwd = 0;
                   8746:     my $authchk = '';
1.873     raeburn  8747:     if ($udom =~ /^$match_domain$/) {
                   8748:         $homeserver = &domain($udom,'primary');
                   8749:     }
                   8750:     if ($homeserver eq '') {
                   8751:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8752:             $homeserver = &homeserver($cnum,$cdom);
                   8753:         }
                   8754:     }
                   8755:     if ($homeserver eq '') {
                   8756:         $authchk = 'nodomain';
1.506     raeburn  8757:     } else {
1.873     raeburn  8758:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8759:         if ($response eq 'refused') {
                   8760:             $authchk = 'refused';
                   8761:         } else {
1.901     albertel 8762:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8763:         }
1.506     raeburn  8764:     }
                   8765:     return ($authparam,$create_passwd,$authchk);
                   8766: }
                   8767: 
1.706     raeburn  8768: sub auto_photo_permission {
                   8769:     my ($cnum,$cdom,$students) = @_;
                   8770:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8771:     my ($outcome,$perm_reqd,$conditions) = 
                   8772: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8773:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8774: 	return (undef,undef);
                   8775:     }
1.706     raeburn  8776:     return ($outcome,$perm_reqd,$conditions);
                   8777: }
                   8778: 
                   8779: sub auto_checkphotos {
                   8780:     my ($uname,$udom,$pid) = @_;
                   8781:     my $homeserver = &homeserver($uname,$udom);
                   8782:     my ($result,$resulttype);
                   8783:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8784: 				   &escape($uname).':'.&escape($pid),
                   8785: 				   $homeserver));
1.709     albertel 8786:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8787: 	return (undef,undef);
                   8788:     }
1.706     raeburn  8789:     if ($outcome) {
                   8790:         ($result,$resulttype) = split(/:/,$outcome);
                   8791:     } 
                   8792:     return ($result,$resulttype);
                   8793: }
                   8794: 
                   8795: sub auto_photochoice {
                   8796:     my ($cnum,$cdom) = @_;
                   8797:     my $homeserver = &homeserver($cnum,$cdom);
                   8798:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8799: 						       &escape($cdom),
                   8800: 						       $homeserver)));
1.709     albertel 8801:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8802: 	return (undef,undef);
                   8803:     }
1.706     raeburn  8804:     return ($update,$comment);
                   8805: }
                   8806: 
                   8807: sub auto_photoupdate {
                   8808:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8809:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8810:     my $host=&hostname($homeserver);
1.706     raeburn  8811:     my $cmd = '';
                   8812:     my $maxtries = 1;
1.800     albertel 8813:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8814:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8815:     }
                   8816:     $cmd =~ s/%%$//;
                   8817:     $cmd = &escape($cmd);
                   8818:     my $query = 'institutionalphotos';
                   8819:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8820:     unless ($queryid=~/^\Q$host\E\_/) {
                   8821:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8822:         return 'error: '.$queryid;
                   8823:     }
                   8824:     my $reply = &get_query_reply($queryid);
                   8825:     my $tries = 1;
                   8826:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8827:         $reply = &get_query_reply($queryid);
                   8828:         $tries ++;
                   8829:     }
                   8830:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8831:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8832:     } else {
                   8833:         my @responses = split(/:/,$reply);
                   8834:         my $outcome = shift(@responses); 
                   8835:         foreach my $item (@responses) {
                   8836:             my ($key,$value) = split(/=/,$item);
                   8837:             $$photo{$key} = $value;
                   8838:         }
                   8839:         return $outcome;
                   8840:     }
                   8841:     return 'error';
                   8842: }
                   8843: 
1.521     raeburn  8844: sub auto_instcode_format {
1.793     albertel 8845:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8846: 	$cat_order) = @_;
1.521     raeburn  8847:     my $courses = '';
1.772     raeburn  8848:     my @homeservers;
1.521     raeburn  8849:     if ($caller eq 'global') {
1.841     albertel 8850: 	my %servers = &get_servers($codedom,'library');
                   8851: 	foreach my $tryserver (keys(%servers)) {
                   8852: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8853: 		push(@homeservers,$tryserver);
                   8854: 	    }
1.584     raeburn  8855:         }
1.1022    raeburn  8856:     } elsif ($caller eq 'requests') {
                   8857:         if ($codedom =~ /^$match_domain$/) {
                   8858:             my $chome = &domain($codedom,'primary');
                   8859:             unless ($chome eq 'no_host') {
                   8860:                 push(@homeservers,$chome);
                   8861:             }
                   8862:         }
1.521     raeburn  8863:     } else {
1.772     raeburn  8864:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8865:     }
1.793     albertel 8866:     foreach my $code (keys(%{$instcodes})) {
                   8867:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8868:     }
                   8869:     chop($courses);
1.772     raeburn  8870:     my $ok_response = 0;
                   8871:     my $response;
                   8872:     while (@homeservers > 0 && $ok_response == 0) {
                   8873:         my $server = shift(@homeservers); 
                   8874:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8875:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8876:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8877: 		split(/:/,$response);
1.772     raeburn  8878:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8879:             push(@{$codetitles},&str2array($codetitles_str));
                   8880:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8881:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8882:             $ok_response = 1;
                   8883:         }
                   8884:     }
                   8885:     if ($ok_response) {
1.521     raeburn  8886:         return 'ok';
1.772     raeburn  8887:     } else {
                   8888:         return $response;
1.521     raeburn  8889:     }
                   8890: }
                   8891: 
1.792     raeburn  8892: sub auto_instcode_defaults {
                   8893:     my ($domain,$returnhash,$code_order) = @_;
                   8894:     my @homeservers;
1.841     albertel 8895: 
                   8896:     my %servers = &get_servers($domain,'library');
                   8897:     foreach my $tryserver (keys(%servers)) {
                   8898: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8899: 	    push(@homeservers,$tryserver);
                   8900: 	}
1.792     raeburn  8901:     }
1.841     albertel 8902: 
1.792     raeburn  8903:     my $response;
1.841     albertel 8904:     foreach my $server (@homeservers) {
1.792     raeburn  8905:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8906:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8907: 	
                   8908: 	foreach my $pair (split(/\&/,$response)) {
                   8909: 	    my ($name,$value)=split(/\=/,$pair);
                   8910: 	    if ($name eq 'code_order') {
                   8911: 		@{$code_order} = split(/\&/,&unescape($value));
                   8912: 	    } else {
                   8913: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8914: 	    }
                   8915: 	}
                   8916: 	return 'ok';
1.792     raeburn  8917:     }
1.841     albertel 8918: 
                   8919:     return $response;
1.1003    raeburn  8920: }
                   8921: 
                   8922: sub auto_possible_instcodes {
1.1007    raeburn  8923:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8924:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8925:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8926:         return;
                   8927:     }
1.1003    raeburn  8928:     my (@homeservers,$uhome);
                   8929:     if (defined(&domain($domain,'primary'))) {
                   8930:         $uhome=&domain($domain,'primary');
                   8931:         push(@homeservers,&domain($domain,'primary'));
                   8932:     } else {
                   8933:         my %servers = &get_servers($domain,'library');
                   8934:         foreach my $tryserver (keys(%servers)) {
                   8935:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8936:                 push(@homeservers,$tryserver);
                   8937:             }
                   8938:         }
                   8939:     }
                   8940:     my $response;
                   8941:     foreach my $server (@homeservers) {
                   8942:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8943:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8944:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8945:             split(':',$response);
                   8946:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8947:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8948:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8949:             my ($name,$value)=split('=',$item);
                   8950:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8951:         }
                   8952:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8953:             my ($name,$value)=split('=',$item);
                   8954:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8955:         }
                   8956:         return 'ok';
                   8957:     }
                   8958:     return $response;
                   8959: }
1.792     raeburn  8960: 
1.1010    raeburn  8961: sub auto_courserequest_checks {
                   8962:     my ($dom) = @_;
1.1020    raeburn  8963:     my ($homeserver,%validations);
                   8964:     if ($dom =~ /^$match_domain$/) {
                   8965:         $homeserver = &domain($dom,'primary');
                   8966:     }
                   8967:     unless ($homeserver eq 'no_host') {
                   8968:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8969:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8970:             my @items = split(/&/,$response);
                   8971:             foreach my $item (@items) {
                   8972:                 my ($key,$value) = split('=',$item);
                   8973:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8974:             }
                   8975:         }
                   8976:     }
1.1010    raeburn  8977:     return %validations; 
                   8978: }
                   8979: 
1.1020    raeburn  8980: sub auto_courserequest_validation {
1.1255    raeburn  8981:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8982:     my ($homeserver,$response);
                   8983:     if ($dom =~ /^$match_domain$/) {
                   8984:         $homeserver = &domain($dom,'primary');
                   8985:     }
1.1255    raeburn  8986:     unless ($homeserver eq 'no_host') {
                   8987:         my $customdata;
                   8988:         if (ref($custominfo) eq 'HASH') {
                   8989:             $customdata = &freeze_escape($custominfo);
                   8990:         }
1.1020    raeburn  8991:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8992:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8993:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8994:                                     $customdata,$homeserver));
1.1020    raeburn  8995:     }
                   8996:     return $response;
                   8997: }
                   8998: 
1.777     albertel 8999: sub auto_validate_class_sec {
1.918     raeburn  9000:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9001:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9002:     my $ownerlist;
                   9003:     if (ref($owners) eq 'ARRAY') {
                   9004:         $ownerlist = join(',',@{$owners});
                   9005:     } else {
                   9006:         $ownerlist = $owners;
                   9007:     }
1.773     raeburn  9008:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9009:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9010:     return $response;
                   9011: }
                   9012: 
1.1367    raeburn  9013: sub auto_validate_instclasses {
                   9014:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9015:     my ($homeserver,%validations);
                   9016:     $homeserver = &homeserver($cnum,$cdom);
                   9017:     unless ($homeserver eq 'no_host') {
                   9018:         my $ownerlist;
                   9019:         if (ref($owners) eq 'ARRAY') {
                   9020:             $ownerlist = join(',',@{$owners});
                   9021:         } else {
                   9022:             $ownerlist = $owners;
                   9023:         }
                   9024:         if (ref($classesref) eq 'HASH') {
                   9025:             my $classes = &freeze_escape($classesref);
                   9026:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9027:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9028:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9029:                 my @items = split(/&/,$response);
                   9030:                 foreach my $item (@items) {
                   9031:                     my ($key,$value) = split('=',$item);
                   9032:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9033:                 }
                   9034:             }
                   9035:         }
                   9036:     }
                   9037:     return %validations;
                   9038: }
                   9039: 
1.1248    raeburn  9040: sub auto_crsreq_update {
                   9041:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9042:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9043:     my ($homeserver,%crsreqresponse);
                   9044:     if ($cdom =~ /^$match_domain$/) {
                   9045:         $homeserver = &domain($cdom,'primary');
                   9046:     }
                   9047:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9048:         my $info;
                   9049:         if (ref($inbound) eq 'HASH') {
                   9050:             $info = &freeze_escape($inbound);
                   9051:         }
                   9052:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9053:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9054:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9055:                             &escape($title).':'.&escape($code).':'.
                   9056:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9057:                             $homeserver);
1.1248    raeburn  9058:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9059:             my @items = split(/&/,$response);
                   9060:             foreach my $item (@items) {
                   9061:                 my ($key,$value) = split('=',$item);
                   9062:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9063:             }
                   9064:         }
                   9065:     }
                   9066:     return \%crsreqresponse;
                   9067: }
                   9068: 
1.1305    raeburn  9069: sub auto_export_grades {
1.1309    raeburn  9070:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9071:     my ($homeserver,%exportresponse);
                   9072:     if ($cdom =~ /^$match_domain$/) {
                   9073:         $homeserver = &domain($cdom,'primary');
                   9074:     }
                   9075:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9076:         my $info;
                   9077:         if (ref($inforef) eq 'HASH') {
                   9078:             $info = &freeze_escape($inforef);
                   9079:         }
                   9080:         if (ref($gradesref) eq 'HASH') {
                   9081:             my $grades = &freeze_escape($gradesref);
                   9082:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9083:                                 $info.':'.$grades,$homeserver);
                   9084:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9085:                 my @items = split(/&/,$response);
                   9086:                 foreach my $item (@items) {
                   9087:                     my ($key,$value) = split('=',$item);
                   9088:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9089:                 }
                   9090:             }
                   9091:         }
                   9092:     }
                   9093:     return \%exportresponse;
1.1305    raeburn  9094: }
                   9095: 
1.1287    raeburn  9096: sub check_instcode_cloning {
                   9097:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9098:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9099:         return;
                   9100:     }
                   9101:     my $canclone;
                   9102:     if (@{$code_order} > 0) {
                   9103:         my $instcoderegexp ='^';
                   9104:         my @clonecodes = split(/\&/,$cloner);
                   9105:         foreach my $item (@{$code_order}) {
                   9106:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9107:                 foreach my $pair (@clonecodes) {
                   9108:                     my ($key,$val) = split(/\=/,$pair,2);
                   9109:                     $val = &unescape($val);
                   9110:                     if ($key eq $item) {
                   9111:                         $instcoderegexp .= '('.$val.')';
                   9112:                         last;
                   9113:                     }
                   9114:                 }
                   9115:             } else {
                   9116:                 $instcoderegexp .= $codedefaults->{$item};
                   9117:             }
                   9118:         }
                   9119:         $instcoderegexp .= '$';
                   9120:         my (@from,@to);
                   9121:         eval {
                   9122:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9123:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9124:         };
                   9125:         if ((@from > 0) && (@to > 0)) {
                   9126:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9127:             if (!@diffs) {
                   9128:                 $canclone = 1;
                   9129:             }
                   9130:         }
                   9131:     }
                   9132:     return $canclone;
                   9133: }
                   9134: 
                   9135: sub default_instcode_cloning {
                   9136:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9137:     my (%codedefaults,@code_order,$canclone);
                   9138:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9139:         %codedefaults = %{$codedefaultsref};
                   9140:         @code_order = @{$codeorderref};
                   9141:     } elsif ($clonedom) {
                   9142:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9143:     }
                   9144:     if (($domdefclone) && (@code_order)) {
                   9145:         my @clonecodes = split(/\+/,$domdefclone);
                   9146:         my $instcoderegexp ='^';
                   9147:         foreach my $item (@code_order) {
                   9148:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9149:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9150:             } else {
                   9151:                 $instcoderegexp .= $codedefaults{$item};
                   9152:             }
                   9153:         }
                   9154:         $instcoderegexp .= '$';
                   9155:         my (@from,@to);
                   9156:         eval {
                   9157:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9158:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9159:         };
                   9160:         if ((@from > 0) && (@to > 0)) {
                   9161:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9162:             if (!@diffs) {
                   9163:                 $canclone = 1;
                   9164:             }
                   9165:         }
                   9166:     }
                   9167:     return $canclone;
                   9168: }
                   9169: 
1.679     raeburn  9170: # ------------------------------------------------------- Course Group routines
                   9171: 
                   9172: sub get_coursegroups {
1.809     raeburn  9173:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9174:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9175: }
                   9176: 
1.679     raeburn  9177: sub modify_coursegroup {
                   9178:     my ($cdom,$cnum,$groupsettings) = @_;
                   9179:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9180: }
                   9181: 
1.809     raeburn  9182: sub toggle_coursegroup_status {
                   9183:     my ($cdom,$cnum,$group,$action) = @_;
                   9184:     my ($from_namespace,$to_namespace);
                   9185:     if ($action eq 'delete') {
                   9186:         $from_namespace = 'coursegroups';
                   9187:         $to_namespace = 'deleted_groups';
                   9188:     } else {
                   9189:         $from_namespace = 'deleted_groups';
                   9190:         $to_namespace = 'coursegroups';
                   9191:     }
                   9192:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9193:     if (my $tmp = &error(%curr_group)) {
                   9194:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9195:         return ('read error',$tmp);
                   9196:     } else {
                   9197:         my %savedsettings = %curr_group; 
1.809     raeburn  9198:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9199:         my $deloutcome;
                   9200:         if ($result eq 'ok') {
1.809     raeburn  9201:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9202:         } else {
                   9203:             return ('write error',$result);
                   9204:         }
                   9205:         if ($deloutcome eq 'ok') {
                   9206:             return 'ok';
                   9207:         } else {
                   9208:             return ('delete error',$deloutcome);
                   9209:         }
                   9210:     }
                   9211: }
                   9212: 
1.679     raeburn  9213: sub modify_group_roles {
1.957     raeburn  9214:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9215:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9216:     my $role = 'gr/'.&escape($userprivs);
                   9217:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9218:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9219:     if ($result eq 'ok') {
                   9220:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9221:     }
1.679     raeburn  9222:     return $result;
                   9223: }
                   9224: 
                   9225: sub modify_coursegroup_membership {
                   9226:     my ($cdom,$cnum,$membership) = @_;
                   9227:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9228:     return $result;
                   9229: }
                   9230: 
1.682     raeburn  9231: sub get_active_groups {
                   9232:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9233:     my $now = time;
                   9234:     my %groups = ();
                   9235:     foreach my $key (keys(%env)) {
1.811     albertel 9236:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9237:             my ($start,$end) = split(/\./,$env{$key});
                   9238:             if (($end!=0) && ($end<$now)) { next; }
                   9239:             if (($start!=0) && ($start>$now)) { next; }
                   9240:             if ($1 eq $cdom && $2 eq $cnum) {
                   9241:                 $groups{$3} = $env{$key} ;
                   9242:             }
                   9243:         }
                   9244:     }
                   9245:     return %groups;
                   9246: }
                   9247: 
1.683     raeburn  9248: sub get_group_membership {
                   9249:     my ($cdom,$cnum,$group) = @_;
                   9250:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9251: }
                   9252: 
                   9253: sub get_users_groups {
                   9254:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9255:     my @usersgroups;
1.683     raeburn  9256:     my $cachetime=1800;
                   9257: 
                   9258:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9259:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9260:     if (defined($cached)) {
1.734     albertel 9261:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9262:     } else {  
                   9263:         $grouplist = '';
1.816     raeburn  9264:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9265:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9266:         my $access_end = $env{'course.'.$courseid.
                   9267:                               '.default_enrollment_end_date'};
                   9268:         my $now = time;
                   9269:         foreach my $key (keys(%roleshash)) {
                   9270:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9271:                 my $group = $1;
                   9272:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9273:                     my $start = $2;
                   9274:                     my $end = $1;
                   9275:                     if ($start == -1) { next; } # deleted from group
                   9276:                     if (($start!=0) && ($start>$now)) { next; }
                   9277:                     if (($end!=0) && ($end<$now)) {
                   9278:                         if ($access_end && $access_end < $now) {
                   9279:                             if ($access_end - $end < 86400) {
                   9280:                                 push(@usersgroups,$group);
1.733     raeburn  9281:                             }
                   9282:                         }
1.817     raeburn  9283:                         next;
1.733     raeburn  9284:                     }
1.817     raeburn  9285:                     push(@usersgroups,$group);
1.683     raeburn  9286:                 }
                   9287:             }
                   9288:         }
1.817     raeburn  9289:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9290:         $grouplist = join(':',@usersgroups);
                   9291:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9292:     }
1.733     raeburn  9293:     return @usersgroups;
1.683     raeburn  9294: }
                   9295: 
                   9296: sub devalidate_getgroups_cache {
                   9297:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9298:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9299: 
1.683     raeburn  9300:     my $hashid="$udom:$uname:$courseid";
                   9301:     &devalidate_cache_new('getgroups',$hashid);
                   9302: }
                   9303: 
1.12      www      9304: # ------------------------------------------------------------------ Plain Text
                   9305: 
                   9306: sub plaintext {
1.988     raeburn  9307:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9308:     if ($short =~ m{^cr/}) {
1.758     albertel 9309: 	return (split('/',$short))[-1];
                   9310:     }
1.742     raeburn  9311:     if (!defined($cid)) {
                   9312:         $cid = $env{'request.course.id'};
                   9313:     }
                   9314:     my %rolenames = (
1.1008    raeburn  9315:                       Course    => 'std',
                   9316:                       Community => 'alt1',
1.1305    raeburn  9317:                       Placement => 'std',
1.742     raeburn  9318:                     );
1.1037    raeburn  9319:     if ($cid ne '') {
                   9320:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9321:             unless ($forcedefault) {
                   9322:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9323:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9324:                 return &Apache::lonlocal::mt($roletext);
                   9325:             }
                   9326:         }
                   9327:     }
                   9328:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9329:         (defined($rolenames{$type})) && 
                   9330:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9331:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9332:     } elsif ($cid ne '') {
                   9333:         my $crstype = $env{'course.'.$cid.'.type'};
                   9334:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9335:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9336:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9337:         }
1.742     raeburn  9338:     }
1.1037    raeburn  9339:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9340: }
                   9341: 
                   9342: # ----------------------------------------------------------------- Assign Role
                   9343: 
                   9344: sub assignrole {
1.957     raeburn  9345:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9346:         $context)=@_;
1.21      www      9347:     my $mrole;
                   9348:     if ($role =~ /^cr\//) {
1.393     www      9349:         my $cwosec=$url;
1.811     albertel 9350:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9351: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9352:            my $refused = 1;
                   9353:            if ($context eq 'requestcourses') {
                   9354:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9355:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9356:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9357:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9358:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9359:                            if ($crsenv{'internal.courseowner'} eq
                   9360:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9361:                                $refused = '';
                   9362:                            }
                   9363:                        }
                   9364:                    }
                   9365:                }
                   9366:            }
                   9367:            if ($refused) {
                   9368:                &logthis('Refused custom assignrole: '.
                   9369:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9370:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9371:                return 'refused';
                   9372:            }
1.104     www      9373:         }
1.21      www      9374:         $mrole='cr';
1.678     raeburn  9375:     } elsif ($role =~ /^gr\//) {
                   9376:         my $cwogrp=$url;
1.811     albertel 9377:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9378:         unless (&allowed('mdg',$cwogrp)) {
                   9379:             &logthis('Refused group assignrole: '.
                   9380:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9381:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9382:             return 'refused';
                   9383:         }
                   9384:         $mrole='gr';
1.21      www      9385:     } else {
1.82      www      9386:         my $cwosec=$url;
1.811     albertel 9387:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9388:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9389:             my $refused;
                   9390:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9391:                 if (!(&allowed('c'.$role,$url))) {
                   9392:                     $refused = 1;
                   9393:                 }
                   9394:             } else {
                   9395:                 $refused = 1;
                   9396:             }
1.947     raeburn  9397:             if ($refused) {
1.1045    raeburn  9398:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9399:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9400:                     my %crsenv;
                   9401:                     if ($role eq 'cc' || $role eq 'co') {
                   9402:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9403:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9404:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9405:                                 if ($crsenv{'internal.courseowner'} eq 
                   9406:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9407:                                     $refused = '';
                   9408:                                 }
                   9409:                             }
                   9410:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9411:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9412:                                 if ($crsenv{'internal.courseowner'} eq 
                   9413:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9414:                                     $refused = '';
                   9415:                                 }
                   9416:                             }
                   9417:                         }
                   9418:                     }
1.1368    raeburn  9419:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9420:                     if ($role eq 'st') {
                   9421:                         $refused = '';
1.1377    raeburn  9422:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9423:                         $refused = '';
                   9424:                     }
1.1017    raeburn  9425:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9426:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9427:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9428:                         my $wrongcc;
                   9429:                         if ($cnum =~ /^$match_community$/) {
                   9430:                             $wrongcc = 1 if ($role eq 'cc');
                   9431:                         } else {
                   9432:                             $wrongcc = 1 if ($role eq 'co');
                   9433:                         }
                   9434:                         unless ($wrongcc) {
                   9435:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9436:                             if ($crsenv{'internal.courseowner'} eq 
                   9437:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9438:                                 $refused = '';
                   9439:                             }
1.1017    raeburn  9440:                         }
                   9441:                     }
1.1183    raeburn  9442:                 } elsif ($context eq 'requestauthor') {
                   9443:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9444:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9445:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9446:                             $refused = '';
                   9447:                         } else {
                   9448:                             my %domdefaults = &get_domain_defaults($udom);
                   9449:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9450:                                 my $checkbystatus;
                   9451:                                 if ($env{'user.adv'}) { 
                   9452:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9453:                                     if ($disposition eq 'automatic') {
                   9454:                                         $refused = '';
                   9455:                                     } elsif ($disposition eq '') {
                   9456:                                         $checkbystatus = 1;
                   9457:                                     } 
                   9458:                                 } else {
                   9459:                                     $checkbystatus = 1;
                   9460:                                 }
                   9461:                                 if ($checkbystatus) {
                   9462:                                     if ($env{'environment.inststatus'}) {
                   9463:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9464:                                         foreach my $type (@inststatuses) {
                   9465:                                             if (($type ne '') &&
                   9466:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9467:                                                 $refused = '';
                   9468:                                             }
                   9469:                                         }
                   9470:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9471:                                         $refused = '';
                   9472:                                     }
                   9473:                                 }
                   9474:                             }
                   9475:                         }
                   9476:                     }
1.1017    raeburn  9477:                 }
                   9478:                 if ($refused) {
1.947     raeburn  9479:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9480:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9481: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9482:                     return 'refused';
                   9483:                 }
1.932     raeburn  9484:             }
1.1131    raeburn  9485:         } elsif ($role eq 'au') {
                   9486:             if ($url ne '/'.$udom.'/') {
                   9487:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9488:                          ' to assign author role for '.$uname.':'.$udom.
                   9489:                          ' in domain: '.$url.' refused (wrong domain).');
                   9490:                 return 'refused';
                   9491:             }
1.104     www      9492:         }
1.21      www      9493:         $mrole=$role;
                   9494:     }
1.620     albertel 9495:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9496:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9497:     if ($end) { $command.='_'.$end; }
1.21      www      9498:     if ($start) {
                   9499: 	if ($end) { 
1.81      www      9500:            $command.='_'.$start; 
1.21      www      9501:         } else {
1.81      www      9502:            $command.='_0_'.$start;
1.21      www      9503:         }
                   9504:     }
1.739     raeburn  9505:     my $origstart = $start;
                   9506:     my $origend = $end;
1.957     raeburn  9507:     my $delflag;
1.357     www      9508: # actually delete
                   9509:     if ($deleteflag) {
1.373     www      9510: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9511: # modify command to delete the role
1.620     albertel 9512:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9513:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9514: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9515: # set start and finish to negative values for userrolelog
                   9516:            $start=-1;
                   9517:            $end=-1;
1.957     raeburn  9518:            $delflag = 1;
1.357     www      9519:         }
                   9520:     }
                   9521: # send command
1.349     www      9522:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9523: # log new user role if status is ok
1.349     www      9524:     if ($answer eq 'ok') {
1.663     raeburn  9525: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9526:         if (($role eq 'cc') || ($role eq 'in') ||
                   9527:             ($role eq 'ep') || ($role eq 'ad') ||
                   9528:             ($role eq 'ta') || ($role eq 'st') ||
                   9529:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9530:             ($role eq 'co')) {
1.1200    raeburn  9531: # for course roles, perform group memberships changes triggered by role change.
                   9532:             unless ($role =~ /^gr/) {
                   9533:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9534:                                                  $origstart,$selfenroll,$context);
                   9535:             }
1.1184    raeburn  9536:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9537:                            $selfenroll,$context);
                   9538:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9539:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9540:                  ($role eq 'da')) {
1.1184    raeburn  9541:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9542:                            $context);
                   9543:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9544:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9545:                              $context); 
                   9546:         }
1.1053    raeburn  9547:         if ($role eq 'cc') {
                   9548:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9549:         }
1.349     www      9550:     }
                   9551:     return $answer;
1.169     harris41 9552: }
                   9553: 
1.1053    raeburn  9554: sub autoupdate_coowners {
                   9555:     my ($url,$end,$start,$uname,$udom) = @_;
                   9556:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9557:     if (($cdom ne '') && ($cnum ne '')) {
                   9558:         my $now = time;
                   9559:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9560:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9561:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9562:             my $instcode = $coursehash{'internal.coursecode'};
                   9563:             if ($instcode ne '') {
1.1056    raeburn  9564:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9565:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9566:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9567:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9568:                         if ($result eq 'valid') {
                   9569:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9570:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9571:                                     push(@newcoowners,$coowner);
                   9572:                                 }
                   9573:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9574:                                     push(@newcoowners,$uname.':'.$udom);
                   9575:                                 }
                   9576:                                 @newcoowners = sort(@newcoowners);
                   9577:                             } else {
                   9578:                                 push(@newcoowners,$uname.':'.$udom);
                   9579:                             }
                   9580:                         } else {
                   9581:                             if ($coursehash{'internal.co-owners'}) {
                   9582:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9583:                                     unless ($coowner eq $uname.':'.$udom) {
                   9584:                                         push(@newcoowners,$coowner);
                   9585:                                     }
                   9586:                                 }
                   9587:                                 unless (@newcoowners > 0) {
                   9588:                                     $delcoowners = 1;
                   9589:                                     $coowners = '';
                   9590:                                 }
                   9591:                             }
                   9592:                         }
                   9593:                         if (@newcoowners || $delcoowners) {
                   9594:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9595:                                             $delcoowners,@newcoowners);
                   9596:                         }
                   9597:                     }
                   9598:                 }
                   9599:             }
                   9600:         }
                   9601:     }
                   9602: }
                   9603: 
                   9604: sub store_coowners {
                   9605:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9606:     my $cid = $cdom.'_'.$cnum;
                   9607:     my ($coowners,$delresult,$putresult);
                   9608:     if (@newcoowners) {
                   9609:         $coowners = join(',',@newcoowners);
                   9610:         my %coownershash = (
                   9611:                             'internal.co-owners' => $coowners,
                   9612:                            );
                   9613:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9614:         if ($putresult eq 'ok') {
                   9615:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9616:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9617:             }
                   9618:         }
                   9619:     }
                   9620:     if ($delcoowners) {
                   9621:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9622:         if ($delresult eq 'ok') {
                   9623:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9624:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9625:             }
                   9626:         }
                   9627:     }
                   9628:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9629:         my %crsinfo =
                   9630:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9631:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9632:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9633:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9634:         }
                   9635:     }
                   9636: }
                   9637: 
1.169     harris41 9638: # -------------------------------------------------- Modify user authentication
1.197     www      9639: # Overrides without validation
                   9640: 
1.169     harris41 9641: sub modifyuserauth {
                   9642:     my ($udom,$uname,$umode,$upass)=@_;
                   9643:     my $uhome=&homeserver($uname,$udom);
1.197     www      9644:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9645:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9646:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9647:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9648:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9649: 		     &escape($upass),$uhome);
1.620     albertel 9650:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9651:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9652:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9653:     &log($udom,,$uname,$uhome,
1.620     albertel 9654:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9655:                                      $env{'user.name'}.', '.$umode.
1.197     www      9656:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9657:     unless ($reply eq 'ok') {
1.197     www      9658:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9659: 	return 'error: '.$reply;
                   9660:     }   
1.170     harris41 9661:     return 'ok';
1.80      www      9662: }
                   9663: 
1.81      www      9664: # --------------------------------------------------------------- Modify a user
1.80      www      9665: 
1.81      www      9666: sub modifyuser {
1.206     matthew  9667:     my ($udom,    $uname, $uid,
                   9668:         $umode,   $upass, $first,
                   9669:         $middle,  $last,  $gene,
1.1058    raeburn  9670:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9671:     $udom= &LONCAPA::clean_domain($udom);
                   9672:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9673:     my $showcandelete = 'none';
                   9674:     if (ref($candelete) eq 'ARRAY') {
                   9675:         if (@{$candelete} > 0) {
                   9676:             $showcandelete = join(', ',@{$candelete});
                   9677:         }
                   9678:     }
1.81      www      9679:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9680:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9681: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9682:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9683:                                      ' desiredhome not specified'). 
1.620     albertel 9684:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9685:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9686:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9687:     my $newuser;
                   9688:     if ($uhome eq 'no_host') {
                   9689:         $newuser = 1;
1.1368    raeburn  9690:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9691:                 ($umode eq 'lti')) {
                   9692:             return 'error: more information needed to create new user';
                   9693:         }
1.1075    raeburn  9694:     }
1.80      www      9695: # ----------------------------------------------------------------- Create User
1.406     albertel 9696:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9697: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9698:         my $unhome='';
1.844     albertel 9699:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9700:             $unhome = $desiredhome;
1.620     albertel 9701: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9702: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9703:         } else { # load balancing routine for determining $unhome
1.81      www      9704:             my $loadm=10000000;
1.841     albertel 9705: 	    my %servers = &get_servers($udom,'library');
                   9706: 	    foreach my $tryserver (keys(%servers)) {
                   9707: 		my $answer=reply('load',$tryserver);
                   9708: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9709: 		    $loadm=$answer;
                   9710: 		    $unhome=$tryserver;
                   9711: 		}
1.80      www      9712: 	    }
                   9713:         }
                   9714:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9715: 	    return 'error: unable to find a home server for '.$uname.
                   9716:                    ' in domain '.$udom;
1.80      www      9717:         }
                   9718:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9719:                          &escape($upass),$unhome);
                   9720: 	unless ($reply eq 'ok') {
                   9721:             return 'error: '.$reply;
                   9722:         }   
1.230     stredwic 9723:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9724:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9725: 	    return 'error: unable verify users home machine.';
1.80      www      9726:         }
1.209     matthew  9727:     }   # End of creation of new user
1.80      www      9728: # ---------------------------------------------------------------------- Add ID
                   9729:     if ($uid) {
                   9730:        $uid=~tr/A-Z/a-z/;
                   9731:        my %uidhash=&idrget($udom,$uname);
1.196     www      9732:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9733:          && (!$forceid)) {
1.80      www      9734: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9735: 	      return 'error: user id "'.$uid.'" does not match '.
                   9736:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9737:           }
                   9738:        } else {
1.1300    raeburn  9739: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9740:        }
                   9741:     }
                   9742: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9743:     my @tmp=&get('environment',
1.899     raeburn  9744: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9745:                     'permanentemail','inststatus'],
1.134     albertel 9746: 		   $udom,$uname);
1.1075    raeburn  9747:     my (%names,%oldnames);
1.313     matthew  9748:     if ($tmp[0] =~ m/^error:.*/) { 
                   9749:         %names=(); 
                   9750:     } else {
                   9751:         %names = @tmp;
1.1075    raeburn  9752:         %oldnames = %names;
1.313     matthew  9753:     }
1.388     www      9754: #
1.1058    raeburn  9755: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9756: # of users did not contain them), do not overwrite existing values
                   9757: # unless field is in $candelete array ref.  
                   9758: #
                   9759: 
                   9760:     my @fields = ('firstname','middlename','lastname','generation',
                   9761:                   'permanentemail','id');
                   9762:     my %newvalues;
                   9763:     if (ref($candelete) eq 'ARRAY') {
                   9764:         foreach my $field (@fields) {
                   9765:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9766:                 if ($field eq 'firstname') {
                   9767:                     $names{$field} = $first;
                   9768:                 } elsif ($field eq 'middlename') {
                   9769:                     $names{$field} = $middle;
                   9770:                 } elsif ($field eq 'lastname') {
                   9771:                     $names{$field} = $last;
                   9772:                 } elsif ($field eq 'generation') { 
                   9773:                     $names{$field} = $gene;
                   9774:                 } elsif ($field eq 'permanentemail') {
                   9775:                     $names{$field} = $email;
                   9776:                 } elsif ($field eq 'id') {
                   9777:                     $names{$field}  = $uid;
                   9778:                 }
                   9779:             }
                   9780:         }
                   9781:     }
1.388     www      9782:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9783:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9784:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9785:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9786:     if ($email) {
                   9787:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9788:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9789:     }
1.899     raeburn  9790:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9791:     if (defined($inststatus)) {
                   9792:         $names{'inststatus'} = '';
                   9793:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9794:         if (ref($usertypes) eq 'HASH') {
                   9795:             my @okstatuses; 
                   9796:             foreach my $item (split(/:/,$inststatus)) {
                   9797:                 if (defined($usertypes->{$item})) {
                   9798:                     push(@okstatuses,$item);  
                   9799:                 }
                   9800:             }
                   9801:             if (@okstatuses) {
                   9802:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9803:             }
                   9804:         }
                   9805:     }
1.1075    raeburn  9806:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9807:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9808:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9809:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9810:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9811:     } else {
                   9812:         $logmsg .= ' during self creation';
                   9813:     }
1.1075    raeburn  9814:     my $changed;
                   9815:     if ($newuser) {
                   9816:         $changed = 1;
                   9817:     } else {
                   9818:         foreach my $field (@fields) {
                   9819:             if ($names{$field} ne $oldnames{$field}) {
                   9820:                 $changed = 1;
                   9821:                 last;
                   9822:             }
                   9823:         }
                   9824:     }
                   9825:     unless ($changed) {
                   9826:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9827:         &logthis($logmsg);
                   9828:         return 'ok';
                   9829:     }
                   9830:     my $reply = &put('environment', \%names, $udom,$uname);
                   9831:     if ($reply ne 'ok') { 
                   9832:         return 'error: '.$reply;
                   9833:     }
1.1087    raeburn  9834:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9835:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9836:     }
1.1075    raeburn  9837:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9838:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9839:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9840:     &logthis($logmsg);
1.134     albertel 9841:     return 'ok';
1.80      www      9842: }
                   9843: 
1.81      www      9844: # -------------------------------------------------------------- Modify student
1.80      www      9845: 
1.81      www      9846: sub modifystudent {
                   9847:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9848:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9849:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9850:     if (!$cid) {
1.620     albertel 9851: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9852: 	    return 'not_in_class';
                   9853: 	}
1.80      www      9854:     }
                   9855: # --------------------------------------------------------------- Make the user
1.81      www      9856:     my $reply=&modifyuser
1.209     matthew  9857: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9858:          $desiredhome,$email,$inststatus);
1.80      www      9859:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9860:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9861:     # student's environment
1.297     matthew  9862:     $uid = undef if (!$forceid);
1.455     albertel 9863:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9864:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9865:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9866:     return $reply;
                   9867: }
                   9868: 
                   9869: sub modify_student_enrollment {
1.1216    raeburn  9870:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9871:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9872:     my ($cdom,$cnum,$chome);
                   9873:     if (!$cid) {
1.620     albertel 9874: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9875: 	    return 'not_in_class';
                   9876: 	}
1.620     albertel 9877: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9878: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9879:     } else {
                   9880: 	($cdom,$cnum)=split(/_/,$cid);
                   9881:     }
1.620     albertel 9882:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9883:     if (!$chome) {
1.457     raeburn  9884: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9885:     }
1.455     albertel 9886:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9887:     # Make sure the user exists
1.81      www      9888:     my $uhome=&homeserver($uname,$udom);
                   9889:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9890: 	return 'error: no such user';
                   9891:     }
1.297     matthew  9892:     # Get student data if we were not given enough information
                   9893:     if (!defined($first)  || $first  eq '' || 
                   9894:         !defined($last)   || $last   eq '' || 
                   9895:         !defined($uid)    || $uid    eq '' || 
                   9896:         !defined($middle) || $middle eq '' || 
                   9897:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9898:         # They did not supply us with enough data to enroll the student, so
                   9899:         # we need to pick up more information.
1.297     matthew  9900:         my %tmp = &get('environment',
1.294     matthew  9901:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9902:                        ,$udom,$uname);
                   9903: 
1.800     albertel 9904:         #foreach my $key (keys(%tmp)) {
                   9905:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9906:         #}
1.294     matthew  9907:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9908:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9909:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9910:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9911:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9912:     }
1.556     albertel 9913:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9914:     my $user = "$uname:$udom";
                   9915:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9916:     my $reply=cput('classlist',
1.1148    raeburn  9917: 		   {$user => 
1.1314    raeburn  9918: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9919: 		   $cdom,$cnum);
1.1148    raeburn  9920:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9921:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9922:     } else { 
1.81      www      9923: 	return 'error: '.$reply;
                   9924:     }
1.297     matthew  9925:     # Add student role to user
1.83      www      9926:     my $uurl='/'.$cid;
1.81      www      9927:     $uurl=~s/\_/\//g;
                   9928:     if ($usec) {
                   9929: 	$uurl.='/'.$usec;
                   9930:     }
1.1148    raeburn  9931:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9932:                              $selfenroll,$context);
                   9933:     if ($result ne 'ok') {
                   9934:         if ($old_entry{$user} ne '') {
                   9935:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9936:         } else {
                   9937:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9938:         }
                   9939:     }
                   9940:     return $result; 
1.21      www      9941: }
                   9942: 
1.556     albertel 9943: sub format_name {
                   9944:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9945:     my $name;
                   9946:     if ($first ne 'lastname') {
                   9947: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9948:     } else {
                   9949: 	if ($lastname=~/\S/) {
                   9950: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9951: 	    $name=~s/\s+,/,/;
                   9952: 	} else {
                   9953: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9954: 	}
                   9955:     }
                   9956:     $name=~s/^\s+//;
                   9957:     $name=~s/\s+$//;
                   9958:     $name=~s/\s+/ /g;
                   9959:     return $name;
                   9960: }
                   9961: 
1.84      www      9962: # ------------------------------------------------- Write to course preferences
                   9963: 
                   9964: sub writecoursepref {
                   9965:     my ($courseid,%prefs)=@_;
                   9966:     $courseid=~s/^\///;
                   9967:     $courseid=~s/\_/\//g;
                   9968:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9969:     my $chome=homeserver($cnum,$cdomain);
                   9970:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9971: 	return 'error: no such course';
                   9972:     }
                   9973:     my $cstring='';
1.800     albertel 9974:     foreach my $pref (keys(%prefs)) {
                   9975: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9976:     }
1.84      www      9977:     $cstring=~s/\&$//;
                   9978:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9979: }
                   9980: 
                   9981: # ---------------------------------------------------------- Make/modify course
                   9982: 
                   9983: sub createcourse {
1.741     raeburn  9984:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9985:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9986:     $url=&declutter($url);
                   9987:     my $cid='';
1.1028    raeburn  9988:     if ($context eq 'requestcourses') {
                   9989:         my $can_create = 0;
                   9990:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9991:         if ($udom eq $ownerdom) {
                   9992:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9993:                                   $context)) {
                   9994:                 $can_create = 1;
                   9995:             }
                   9996:         } else {
                   9997:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9998:                                            $category);
                   9999:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10000:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10001:                 if (@curr > 0) {
                   10002:                     my @options = qw(approval validate autolimit);
                   10003:                     my $optregex = join('|',@options);
                   10004:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10005:                         $can_create = 1;
                   10006:                     }
                   10007:                 }
                   10008:             }
                   10009:         }
                   10010:         if ($can_create) {
                   10011:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10012:                 unless (&allowed('ccc',$udom)) {
                   10013:                     return 'refused'; 
                   10014:                 }
1.1017    raeburn  10015:             }
                   10016:         } else {
                   10017:             return 'refused';
                   10018:         }
1.1028    raeburn  10019:     } elsif (!&allowed('ccc',$udom)) {
                   10020:         return 'refused';
1.84      www      10021:     }
1.1011    raeburn  10022: # --------------------------------------------------------------- Get Unique ID
                   10023:     my $uname;
                   10024:     if ($cnum =~ /^$match_courseid$/) {
                   10025:         my $chome=&homeserver($cnum,$udom,'true');
                   10026:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10027:             $uname = $cnum;
                   10028:         } else {
1.1038    raeburn  10029:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10030:         }
                   10031:     } else {
1.1038    raeburn  10032:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10033:     }
                   10034:     return $uname if ($uname =~ /^error/);
                   10035: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10036:     if (!defined($course_server)) {
                   10037:         if (defined(&domain($udom,'primary'))) {
                   10038:             $course_server = &domain($udom,'primary');
                   10039:         } else {
                   10040:             $course_server = $env{'user.home'}; 
                   10041:         }
                   10042:     }
                   10043:     my %host_servers =
                   10044:         &Apache::lonnet::get_servers($udom,'library');
                   10045:     unless ($host_servers{$course_server}) {
                   10046:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10047:     }
1.84      www      10048: # ------------------------------------------------------------- Make the course
                   10049:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10050:                       $course_server);
1.84      www      10051:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10052:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10053:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10054: 	return 'error: no such course';
                   10055:     }
1.271     www      10056: # ----------------------------------------------------------------- Course made
1.516     raeburn  10057: # log existence
1.1029    raeburn  10058:     my $now = time;
1.918     raeburn  10059:     my $newcourse = {
                   10060:                     $udom.'_'.$uname => {
1.921     raeburn  10061:                                      description => $description,
                   10062:                                      inst_code   => $inst_code,
                   10063:                                      owner       => $course_owner,
                   10064:                                      type        => $crstype,
1.1029    raeburn  10065:                                      creator     => $env{'user.name'}.':'.
                   10066:                                                     $env{'user.domain'},
                   10067:                                      created     => $now,
                   10068:                                      context     => $context,
1.918     raeburn  10069:                                                 },
                   10070:                     };
1.921     raeburn  10071:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10072: # set toplevel url
1.271     www      10073:     my $topurl=$url;
                   10074:     unless ($nonstandard) {
                   10075: # ------------------------------------------ For standard courses, make top url
                   10076:         my $mapurl=&clutter($url);
1.278     www      10077:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10078:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10079: <map>
                   10080: <resource id="1" type="start"></resource>
                   10081: <resource id="2" src="$mapurl"></resource>
                   10082: <resource id="3" type="finish"></resource>
                   10083: <link index="1" from="1" to="2"></link>
                   10084: <link index="2" from="2" to="3"></link>
                   10085: </map>
                   10086: ENDINITMAP
                   10087:         $topurl=&declutter(
1.638     albertel 10088:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10089:                           );
                   10090:     }
                   10091: # ----------------------------------------------------------- Write preferences
1.84      www      10092:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10093:                      ('description'              => $description,
                   10094:                       'url'                      => $topurl,
                   10095:                       'internal.creator'         => $env{'user.name'}.':'.
                   10096:                                                     $env{'user.domain'},
                   10097:                       'internal.created'         => $now,
                   10098:                       'internal.creationcontext' => $context)
                   10099:                     );
1.84      www      10100:     return '/'.$udom.'/'.$uname;
                   10101: }
                   10102: 
1.1011    raeburn  10103: # ------------------------------------------------------------------- Create ID
                   10104: sub generate_coursenum {
1.1038    raeburn  10105:     my ($udom,$crstype) = @_;
1.1011    raeburn  10106:     my $domdesc = &domain($udom);
                   10107:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10108:     my $first;
                   10109:     if ($crstype eq 'Community') {
                   10110:         $first = '0';
                   10111:     } else {
                   10112:         $first = int(1+rand(9)); 
                   10113:     } 
                   10114:     my $uname=$first.
1.1011    raeburn  10115:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10116:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10117:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10118: # ----------------------------------------------- Make sure that does not exist
                   10119:     my $uhome=&homeserver($uname,$udom,'true');
                   10120:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10121:         if ($crstype eq 'Community') {
                   10122:             $first = '0';
                   10123:         } else {
                   10124:             $first = int(1+rand(9));
                   10125:         }
                   10126:         $uname=$first.
1.1011    raeburn  10127:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10128:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10129:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10130:         $uhome=&homeserver($uname,$udom,'true');
                   10131:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10132:             return 'error: unable to generate unique course-ID';
                   10133:         }
                   10134:     }
                   10135:     return $uname;
                   10136: }
                   10137: 
1.813     albertel 10138: sub is_course {
1.1167    droeschl 10139:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10140:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10141: 
1.1381    raeburn  10142:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10143:     my $uhome=&homeserver($cnum,$cdom);
                   10144:     my $iscourse;
                   10145:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10146:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10147:     } else {
                   10148:         my $hashid = $cdom.':'.$cnum;
                   10149:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10150:         unless (defined($cached)) {
                   10151:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10152:                                         $cnum,undef,undef,'.');
                   10153:             $iscourse = 0;
                   10154:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10155:                 $iscourse = 1;
                   10156:             }
                   10157:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10158:         }
                   10159:     }
                   10160:     return unless ($iscourse);
1.1167    droeschl 10161:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10162: }
                   10163: 
1.1015    raeburn  10164: sub store_userdata {
                   10165:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10166:     my $result;
1.1016    raeburn  10167:     if ($datakey ne '') {
1.1013    raeburn  10168:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10169:             if ($udom eq '' || $uname eq '') {
                   10170:                 $udom = $env{'user.domain'};
                   10171:                 $uname = $env{'user.name'};
                   10172:             }
                   10173:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10174:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10175:                 $result = 'error: no_host';
                   10176:             } else {
                   10177:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10178:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10179: 
                   10180:                 my $namevalue='';
                   10181:                 foreach my $key (keys(%{$storehash})) {
                   10182:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10183:                 }
                   10184:                 $namevalue=~s/\&$//;
1.1224    raeburn  10185:                 unless ($namespace eq 'courserequests') {
                   10186:                     $datakey = &escape($datakey);
                   10187:                 }
1.1105    raeburn  10188:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10189:                                   $namevalue,$uhome);
1.1013    raeburn  10190:             }
                   10191:         } else {
                   10192:             $result = 'error: data to store was not a hash reference'; 
                   10193:         }
                   10194:     } else {
                   10195:         $result= 'error: invalid requestkey'; 
                   10196:     }
                   10197:     return $result;
                   10198: }
                   10199: 
1.21      www      10200: # ---------------------------------------------------------- Assign Custom Role
                   10201: 
                   10202: sub assigncustomrole {
1.957     raeburn  10203:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10204:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10205:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10206: }
                   10207: 
                   10208: # ----------------------------------------------------------------- Revoke Role
                   10209: 
                   10210: sub revokerole {
1.957     raeburn  10211:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10212:     my $now=time;
1.965     raeburn  10213:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10214: }
                   10215: 
                   10216: # ---------------------------------------------------------- Revoke Custom Role
                   10217: 
                   10218: sub revokecustomrole {
1.957     raeburn  10219:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10220:     my $now=time;
1.357     www      10221:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10222:            $deleteflag,$selfenroll,$context);
1.17      www      10223: }
                   10224: 
1.533     banghart 10225: # ------------------------------------------------------------ Disk usage
1.535     albertel 10226: sub diskusage {
1.955     raeburn  10227:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10228:     $directorypath =~ s/\/$//;
                   10229:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10230:                        .&escape($getpropath).':'.&escape($uname).':'
                   10231:                        .&escape($udom),homeserver($uname,$udom));
                   10232:     if ($listing eq 'unknown_cmd') {
                   10233:         if ($getpropath) {
                   10234:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10235:         }
                   10236:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10237:     }
1.514     albertel 10238:     return $listing;
1.512     banghart 10239: }
                   10240: 
1.566     banghart 10241: sub is_locked {
1.1096    raeburn  10242:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10243:     my @check;
                   10244:     my $is_locked;
1.1093    raeburn  10245:     push (@check,$file_name);
1.613     albertel 10246:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10247: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10248:     my ($tmp)=keys(%locked);
                   10249:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10250:     
1.566     banghart 10251:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10252:         $is_locked = 'false';
                   10253:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10254:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10255:                $is_locked = 'true';
1.1096    raeburn  10256:                if (ref($which) eq 'ARRAY') {
                   10257:                    push(@{$which},$entry);
                   10258:                } else {
                   10259:                    last;
                   10260:                }
1.745     raeburn  10261:            }
                   10262:        }
1.566     banghart 10263:     } else {
                   10264:         $is_locked = 'false';
                   10265:     }
1.1093    raeburn  10266:     return $is_locked;
1.566     banghart 10267: }
                   10268: 
1.759     albertel 10269: sub declutter_portfile {
                   10270:     my ($file) = @_;
1.833     albertel 10271:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10272:     return $file;
                   10273: }
                   10274: 
1.559     banghart 10275: # ------------------------------------------------------------- Mark as Read Only
                   10276: 
                   10277: sub mark_as_readonly {
                   10278:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10279:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10280:     my ($tmp)=keys(%current_permissions);
                   10281:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10282:     foreach my $file (@{$files}) {
1.759     albertel 10283: 	$file = &declutter_portfile($file);
1.561     banghart 10284:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10285:     }
1.613     albertel 10286:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10287:     return;
                   10288: }
                   10289: 
1.572     banghart 10290: # ------------------------------------------------------------Save Selected Files
                   10291: 
                   10292: sub save_selected_files {
                   10293:     my ($user, $path, @files) = @_;
                   10294:     my $filename = $user."savedfiles";
1.573     banghart 10295:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10296:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10297:     foreach my $file (@files) {
1.620     albertel 10298:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10299:     }
                   10300:     foreach my $file (@other_files) {
1.574     banghart 10301:         print (OUT $file."\n");
1.572     banghart 10302:     }
1.574     banghart 10303:     close (OUT);
1.572     banghart 10304:     return 'ok';
                   10305: }
                   10306: 
1.574     banghart 10307: sub clear_selected_files {
                   10308:     my ($user) = @_;
                   10309:     my $filename = $user."savedfiles";
1.1359    raeburn  10310:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10311:     print (OUT undef);
                   10312:     close (OUT);
                   10313:     return ("ok");    
                   10314: }
                   10315: 
1.572     banghart 10316: sub files_in_path {
                   10317:     my ($user, $path) = @_;
                   10318:     my $filename = $user."savedfiles";
                   10319:     my %return_files;
1.1359    raeburn  10320:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10321:     while (my $line_in = <IN>) {
1.574     banghart 10322:         chomp ($line_in);
                   10323:         my @paths_and_file = split (m!/!, $line_in);
                   10324:         my $file_part = pop (@paths_and_file);
                   10325:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10326:         $path_part.='/';
                   10327:         my $path_and_file = $path_part.$file_part;
                   10328:         if ($path_part eq $path) {
                   10329:             $return_files{$file_part}= 'selected';
                   10330:         }
                   10331:     }
1.574     banghart 10332:     close (IN);
                   10333:     return (\%return_files);
1.572     banghart 10334: }
                   10335: 
                   10336: # called in portfolio select mode, to show files selected NOT in current directory
                   10337: sub files_not_in_path {
                   10338:     my ($user, $path) = @_;
                   10339:     my $filename = $user."savedfiles";
                   10340:     my @return_files;
                   10341:     my $path_part;
1.1359    raeburn  10342:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10343:     while (my $line = <IN>) {
1.572     banghart 10344:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10345:         my @paths_and_file = split(m|/|, $line);
                   10346:         my $file_part = pop(@paths_and_file);
                   10347:         chomp($file_part);
                   10348:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10349:         $path_part .= '/';
                   10350:         my $path_and_file = $path_part.$file_part;
                   10351:         if ($path_part ne $path) {
1.800     albertel 10352:             push(@return_files, ($path_and_file));
1.572     banghart 10353:         }
                   10354:     }
1.800     albertel 10355:     close(OUT);
1.574     banghart 10356:     return (@return_files);
1.572     banghart 10357: }
                   10358: 
1.1273    raeburn  10359: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10360:  
                   10361: sub portfiles_versioning {
                   10362:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10363:     my $portfolio_root = '/userfiles/portfolio';
                   10364:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10365:     foreach my $file (@{$portfiles}) {
                   10366:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10367:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10368:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10369:         my $getpropath = 1;
                   10370:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10371:                                              $stu_name,$getpropath);
                   10372:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10373:         my $new_answer = 
                   10374:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10375:         if ($new_answer ne 'problem getting file') {
                   10376:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10377:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10378:                               [$symb,$env{'request.course.id'},'graded']);
                   10379:         }
                   10380:     }
                   10381: }
                   10382: 
                   10383: sub get_next_version {
                   10384:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10385:     my $version;
                   10386:     if (ref($dir_list) eq 'ARRAY') {
                   10387:         foreach my $row (@{$dir_list}) {
                   10388:             my ($file) = split(/\&/,$row,2);
                   10389:             my ($file_name,$file_version,$file_ext) =
                   10390:                 &file_name_version_ext($file);
                   10391:             if (($file_name eq $answer_name) &&
                   10392:                 ($file_ext eq $answer_ext)) {
                   10393:                      # gets here if filename and extension match,
                   10394:                      # regardless of version
                   10395:                 if ($file_version ne '') {
                   10396:                     # a versioned file is found  so save it for later
                   10397:                     if ($file_version > $version) {
                   10398:                         $version = $file_version;
                   10399:                     }
                   10400:                 }
                   10401:             }
                   10402:         }
                   10403:     }
                   10404:     $version ++;
                   10405:     return($version);
                   10406: }
                   10407: 
                   10408: sub version_selected_portfile {
                   10409:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10410:     my ($answer_name,$answer_ver,$answer_ext) =
                   10411:         &file_name_version_ext($file_name);
                   10412:     my $new_answer;
                   10413:     $env{'form.copy'} =
                   10414:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10415:     if($env{'form.copy'} eq '-1') {
                   10416:         $new_answer = 'problem getting file';
                   10417:     } else {
                   10418:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10419:         my $copy_result = 
                   10420:             &finishuserfileupload($stu_name,$domain,'copy',
                   10421:                                   '/portfolio'.$directory.$new_answer);
                   10422:     }
                   10423:     undef($env{'form.copy'});
                   10424:     return ($new_answer);
                   10425: }
                   10426: 
                   10427: sub file_name_version_ext {
                   10428:     my ($file)=@_;
                   10429:     my @file_parts = split(/\./, $file);
                   10430:     my ($name,$version,$ext);
                   10431:     if (@file_parts > 1) {
                   10432:         $ext=pop(@file_parts);
                   10433:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10434:             $version=pop(@file_parts);
                   10435:         }
                   10436:         $name=join('.',@file_parts);
                   10437:     } else {
                   10438:         $name=join('.',@file_parts);
                   10439:     }
                   10440:     return($name,$version,$ext);
                   10441: }
                   10442: 
1.745     raeburn  10443: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10444: 
1.745     raeburn  10445: sub get_portfile_permissions {
                   10446:     my ($domain,$user) = @_;
1.613     albertel 10447:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10448:     my ($tmp)=keys(%current_permissions);
                   10449:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10450:     return \%current_permissions;
                   10451: }
                   10452: 
                   10453: #---------------------------------------------Get portfolio file access controls
                   10454: 
1.749     raeburn  10455: sub get_access_controls {
1.745     raeburn  10456:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10457:     my %access;
                   10458:     my $real_file = $file;
                   10459:     $file =~ s/\.meta$//;
1.745     raeburn  10460:     if (defined($file)) {
1.749     raeburn  10461:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10462:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10463:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10464:             }
                   10465:         }
1.745     raeburn  10466:     } else {
1.749     raeburn  10467:         foreach my $key (keys(%{$current_permissions})) {
                   10468:             if ($key =~ /\0accesscontrol$/) {
                   10469:                 if (defined($group)) {
                   10470:                     if ($key !~ m-^\Q$group\E/-) {
                   10471:                         next;
                   10472:                     }
                   10473:                 }
                   10474:                 my ($fullpath) = split(/\0/,$key);
                   10475:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10476:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10477:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10478:                     }
                   10479:                 }
                   10480:             }
                   10481:         }
                   10482:     }
                   10483:     return %access;
                   10484: }
                   10485: 
                   10486: sub modify_access_controls {
                   10487:     my ($file_name,$changes,$domain,$user)=@_;
                   10488:     my ($outcome,$deloutcome);
                   10489:     my %store_permissions;
                   10490:     my %new_values;
                   10491:     my %new_control;
                   10492:     my %translation;
                   10493:     my @deletions = ();
                   10494:     my $now = time;
                   10495:     if (exists($$changes{'activate'})) {
                   10496:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10497:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10498:             my $numnew = scalar(@newitems);
                   10499:             for (my $i=0; $i<$numnew; $i++) {
                   10500:                 my $newkey = $newitems[$i];
                   10501:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10502:                 if ($newkey =~ /^\d+:/) { 
                   10503:                     $newkey =~ s/^(\d+)/$newid/;
                   10504:                     $translation{$1} = $newid;
                   10505:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10506:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10507:                     $translation{$1} = $newid;
                   10508:                 }
1.749     raeburn  10509:                 $new_values{$file_name."\0".$newkey} = 
                   10510:                                           $$changes{'activate'}{$newitems[$i]};
                   10511:                 $new_control{$newkey} = $now;
                   10512:             }
                   10513:         }
                   10514:     }
                   10515:     my %todelete;
                   10516:     my %changed_items;
                   10517:     foreach my $action ('delete','update') {
                   10518:         if (exists($$changes{$action})) {
                   10519:             if (ref($$changes{$action}) eq 'HASH') {
                   10520:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10521:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10522:                     if ($action eq 'delete') { 
                   10523:                         $todelete{$itemnum} = 1;
                   10524:                     } else {
                   10525:                         $changed_items{$itemnum} = $key;
                   10526:                     }
                   10527:                 }
1.745     raeburn  10528:             }
                   10529:         }
1.749     raeburn  10530:     }
                   10531:     # get lock on access controls for file.
                   10532:     my $lockhash = {
                   10533:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10534:                                                        ':'.$env{'user.domain'},
                   10535:                    }; 
                   10536:     my $tries = 0;
                   10537:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10538:    
1.1288    damieng  10539:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10540:         $tries ++;
1.1289    damieng  10541:         sleep(0.1);
1.749     raeburn  10542:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10543:     }
                   10544:     if ($gotlock eq 'ok') {
                   10545:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10546:         my ($tmp)=keys(%curr_permissions);
                   10547:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10548:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10549:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10550:             if (ref($curr_controls) eq 'HASH') {
                   10551:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10552:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10553:                     if (defined($todelete{$itemnum})) {
                   10554:                         push(@deletions,$file_name."\0".$control_item);
                   10555:                     } else {
                   10556:                         if (defined($changed_items{$itemnum})) {
                   10557:                             $new_control{$changed_items{$itemnum}} = $now;
                   10558:                             push(@deletions,$file_name."\0".$control_item);
                   10559:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10560:                         } else {
                   10561:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10562:                         }
                   10563:                     }
1.745     raeburn  10564:                 }
                   10565:             }
                   10566:         }
1.970     raeburn  10567:         my ($group);
                   10568:         if (&is_course($domain,$user)) {
                   10569:             ($group,my $file) = split(/\//,$file_name,2);
                   10570:         }
1.749     raeburn  10571:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10572:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10573:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10574:         #  remove lock
                   10575:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10576:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10577:         my $sqlresult =
1.970     raeburn  10578:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10579:                                     $group);
1.749     raeburn  10580:     } else {
                   10581:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10582:     }
1.749     raeburn  10583:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10584: }
                   10585: 
1.827     raeburn  10586: sub make_public_indefinitely {
1.1271    raeburn  10587:     my (@requrl) = @_;
                   10588:     return &automated_portfile_access('public',\@requrl);
                   10589: }
                   10590: 
                   10591: sub automated_portfile_access {
                   10592:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10593:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10594:         return 'invalid';
                   10595:     }
1.1271    raeburn  10596:     my %urls;
                   10597:     if (ref($addsref) eq 'ARRAY') {
                   10598:         foreach my $requrl (@{$addsref}) {
                   10599:             if (&is_portfolio_url($requrl)) {
                   10600:                 unless (exists($urls{$requrl})) {
                   10601:                     $urls{$requrl} = 'add';
                   10602:                 }
                   10603:             }
                   10604:         }
                   10605:     }
                   10606:     if (ref($delsref) eq 'ARRAY') {
                   10607:         foreach my $requrl (@{$delsref}) { 
                   10608:             if (&is_portfolio_url($requrl)) {
                   10609:                 unless (exists($urls{$requrl})) {
                   10610:                     $urls{$requrl} = 'delete'; 
                   10611:                 }
                   10612:             }
                   10613:         }
                   10614:     }
                   10615:     unless (keys(%urls)) {
                   10616:         return 'invalid';
                   10617:     }
                   10618:     my $ip;
                   10619:     if ($accesstype eq 'ip') {
                   10620:         if (ref($info) eq 'HASH') {
                   10621:             if ($info->{'ip'} ne '') {
                   10622:                 $ip = $info->{'ip'};
                   10623:             }
                   10624:         }
                   10625:         if ($ip eq '') {
                   10626:             return 'invalid';
                   10627:         }
                   10628:     }
                   10629:     my $errors;
1.827     raeburn  10630:     my $now = time;
1.1271    raeburn  10631:     my %current_perms;
                   10632:     foreach my $requrl (sort(keys(%urls))) {
                   10633:         my $action;
                   10634:         if ($urls{$requrl} eq 'add') {
                   10635:             $action = 'activate';
                   10636:         } else {
                   10637:             $action = 'none';
                   10638:         }
                   10639:         my $aclnum = 0;
1.827     raeburn  10640:         my (undef,$udom,$unum,$file_name,$group) =
                   10641:             &parse_portfolio_url($requrl);
1.1271    raeburn  10642:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10643:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10644:         }
                   10645:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10646:                                                    $group,$file_name);
                   10647:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10648:             my ($num,$scope,$end,$start) = 
                   10649:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10650:             if ($scope eq $accesstype) {
                   10651:                 if (($start <= $now) && ($end == 0)) {
                   10652:                     if ($accesstype eq 'ip') {
                   10653:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10654:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10655:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10656:                                     if ($urls{$requrl} eq 'add') {
                   10657:                                         $action = 'none';
                   10658:                                         last;
                   10659:                                     } else {
                   10660:                                         $action = 'delete';
                   10661:                                         $aclnum = $num;
                   10662:                                         last;
                   10663:                                     }
                   10664:                                 }
                   10665:                             }
                   10666:                         }
                   10667:                     } elsif ($accesstype eq 'public') {
                   10668:                         if ($urls{$requrl} eq 'add') {
                   10669:                             $action = 'none';
                   10670:                             last;
                   10671:                         } else {
                   10672:                             $action = 'delete';
                   10673:                             $aclnum = $num;
                   10674:                             last;
                   10675:                         }
                   10676:                     }
                   10677:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10678:                     $action = 'update';
                   10679:                     $aclnum = $num;
1.1271    raeburn  10680:                     last;
1.827     raeburn  10681:                 }
                   10682:             }
                   10683:         }
                   10684:         if ($action eq 'none') {
1.1271    raeburn  10685:             next;
1.827     raeburn  10686:         } else {
                   10687:             my %changes;
                   10688:             my $newend = 0;
                   10689:             my $newstart = $now;
1.1271    raeburn  10690:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10691:             $changes{$action}{$newkey} = {
1.1271    raeburn  10692:                 type => $accesstype,
1.827     raeburn  10693:                 time => {
                   10694:                     start => $newstart,
                   10695:                     end   => $newend,
                   10696:                 },
                   10697:             };
1.1271    raeburn  10698:             if ($accesstype eq 'ip') {
                   10699:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10700:             }
1.827     raeburn  10701:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10702:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10703:             unless ($outcome eq 'ok') {
                   10704:                 $errors .= $outcome.' ';
                   10705:             }
1.827     raeburn  10706:         }
1.1271    raeburn  10707:     }
                   10708:     if ($errors) {
                   10709:         $errors =~ s/\s$//;
                   10710:         return $errors;
1.827     raeburn  10711:     } else {
1.1271    raeburn  10712:         return 'ok';
1.827     raeburn  10713:     }
                   10714: }
                   10715: 
1.745     raeburn  10716: #------------------------------------------------------Get Marked as Read Only
                   10717: 
                   10718: sub get_marked_as_readonly {
                   10719:     my ($domain,$user,$what,$group) = @_;
                   10720:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10721:     my @readonly_files;
1.629     banghart 10722:     my $cmp1=$what;
                   10723:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10724:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10725:         if (defined($group)) {
                   10726:             if ($file_name !~ m-^\Q$group\E/-) {
                   10727:                 next;
                   10728:             }
                   10729:         }
1.561     banghart 10730:         if (ref($value) eq "ARRAY"){
                   10731:             foreach my $stored_what (@{$value}) {
1.629     banghart 10732:                 my $cmp2=$stored_what;
1.759     albertel 10733:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10734:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10735:                 }
1.629     banghart 10736:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10737:                     push(@readonly_files, $file_name);
1.745     raeburn  10738:                     last;
1.563     banghart 10739:                 } elsif (!defined($what)) {
                   10740:                     push(@readonly_files, $file_name);
1.745     raeburn  10741:                     last;
1.561     banghart 10742:                 }
                   10743:             }
1.745     raeburn  10744:         }
1.561     banghart 10745:     }
                   10746:     return @readonly_files;
                   10747: }
1.577     banghart 10748: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10749: 
1.577     banghart 10750: sub get_marked_as_readonly_hash {
1.745     raeburn  10751:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10752:     my %readonly_files;
1.745     raeburn  10753:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10754:         if (defined($group)) {
                   10755:             if ($file_name !~ m-^\Q$group\E/-) {
                   10756:                 next;
                   10757:             }
                   10758:         }
1.577     banghart 10759:         if (ref($value) eq "ARRAY"){
                   10760:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10761:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10762:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10763:                         if ($lock_descriptor eq 'graded') {
                   10764:                             $readonly_files{$file_name} = 'graded';
                   10765:                         } elsif ($lock_descriptor eq 'handback') {
                   10766:                             $readonly_files{$file_name} = 'handback';
                   10767:                         } else {
                   10768:                             if (!exists($readonly_files{$file_name})) {
                   10769:                                 $readonly_files{$file_name} = 'locked';
                   10770:                             }
                   10771:                         }
1.745     raeburn  10772:                     }
1.750     banghart 10773:                 } 
1.577     banghart 10774:             }
                   10775:         } 
                   10776:     }
                   10777:     return %readonly_files;
                   10778: }
1.559     banghart 10779: # ------------------------------------------------------------ Unmark as Read Only
                   10780: 
                   10781: sub unmark_as_readonly {
1.629     banghart 10782:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10783:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10784:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10785:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10786:     my $symb_crs = $what;
                   10787:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10788:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10789:     my ($tmp)=keys(%current_permissions);
                   10790:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10791:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10792:     foreach my $file (@readonly_files) {
1.759     albertel 10793: 	my $clean_file = &declutter_portfile($file);
                   10794: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10795: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10796:         my @new_locks;
                   10797:         my @del_keys;
                   10798:         if (ref($current_locks) eq "ARRAY"){
                   10799:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10800:                 my $compare=$locker;
1.749     raeburn  10801:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10802:                     $compare=join('',@{$locker});
1.746     raeburn  10803:                     if ($compare ne $symb_crs) {
                   10804:                         push(@new_locks, $locker);
                   10805:                     }
1.563     banghart 10806:                 }
                   10807:             }
1.650     albertel 10808:             if (scalar(@new_locks) > 0) {
1.563     banghart 10809:                 $current_permissions{$file} = \@new_locks;
                   10810:             } else {
                   10811:                 push(@del_keys, $file);
1.613     albertel 10812:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10813:                 delete($current_permissions{$file});
1.563     banghart 10814:             }
                   10815:         }
1.561     banghart 10816:     }
1.613     albertel 10817:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10818:     return;
                   10819: }
1.512     banghart 10820: 
1.17      www      10821: # ------------------------------------------------------------ Directory lister
                   10822: 
                   10823: sub dirlist {
1.955     raeburn  10824:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10825:     $uri=~s/^\///;
                   10826:     $uri=~s/\/$//;
1.253     stredwic 10827:     my ($udom, $uname);
1.955     raeburn  10828:     if ($getuserdir) {
1.253     stredwic 10829:         $udom = $userdomain;
                   10830:         $uname = $username;
1.955     raeburn  10831:     } else {
                   10832:         (undef,$udom,$uname)=split(/\//,$uri);
                   10833:         if(defined($userdomain)) {
                   10834:             $udom = $userdomain;
                   10835:         }
                   10836:         if(defined($username)) {
                   10837:             $uname = $username;
                   10838:         }
1.253     stredwic 10839:     }
1.955     raeburn  10840:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10841: 
1.955     raeburn  10842:     $dirRoot = $perlvar{'lonDocRoot'};
                   10843:     if (defined($getpropath)) {
                   10844:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10845:         $dirRoot =~ s/\/$//;
1.955     raeburn  10846:     } elsif (defined($getuserdir)) {
                   10847:         my $subdir=$uname.'__';
                   10848:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10849:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10850:                    ."/$udom/$subdir/$uname";
                   10851:     } elsif (defined($alternateRoot)) {
                   10852:         $dirRoot = $alternateRoot;
1.751     banghart 10853:     }
1.253     stredwic 10854: 
                   10855:     if($udom) {
                   10856:         if($uname) {
1.1135    raeburn  10857:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10858:             if ($uhome eq 'no_host') {
                   10859:                 return ([],'no_host');
                   10860:             }
1.955     raeburn  10861:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10862:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10863:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10864:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10865:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10866:             } else {
                   10867:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10868:             }
1.605     matthew  10869:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10870:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10871:                 @listing_results = split(/:/,$listing);
                   10872:             } else {
                   10873:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10874:             }
1.1135    raeburn  10875:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10876:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10877:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10878:                 return ([],$listing);
                   10879:             } else {
                   10880:                 return (\@listing_results);
1.1135    raeburn  10881:             }
1.955     raeburn  10882:         } elsif(!$alternateRoot) {
1.1136    raeburn  10883:             my (%allusers,%listerror);
1.841     albertel 10884: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10885:  	    foreach my $tryserver (keys(%servers)) {
                   10886:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10887:                                   &escape($udom),$tryserver);
                   10888:                 if ($listing eq 'unknown_cmd') {
                   10889: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10890: 				      $udom, $tryserver);
                   10891:                 } else {
                   10892:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10893:                 }
1.841     albertel 10894: 		if ($listing eq 'unknown_cmd') {
                   10895: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10896: 				      $udom, $tryserver);
                   10897: 		    @listing_results = split(/:/,$listing);
                   10898: 		} else {
                   10899: 		    @listing_results =
                   10900: 			map { &unescape($_); } split(/:/,$listing);
                   10901: 		}
1.1136    raeburn  10902:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10903:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10904:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10905:                     $listerror{$tryserver} = $listing;
                   10906:                 } else {
1.841     albertel 10907: 		    foreach my $line (@listing_results) {
                   10908: 			my ($entry) = split(/&/,$line,2);
                   10909: 			$allusers{$entry} = 1;
                   10910: 		    }
                   10911: 		}
1.253     stredwic 10912:             }
1.1136    raeburn  10913:             my @alluserslist=();
1.800     albertel 10914:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10915:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10916:             }
1.1318    droeschl 10917: 
                   10918:             if (!%listerror) {
                   10919:                 # no errors
                   10920:                 return (\@alluserslist);
                   10921:             } elsif (scalar(keys(%servers)) == 1) {
                   10922:                 # one library server, one error 
                   10923:                 my ($key) = keys(%listerror);
                   10924:                 return (\@alluserslist, $listerror{$key});
                   10925:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10926:                 # con_lost indicates that we might miss data from at least one
                   10927:                 # library server
                   10928:                 return (\@alluserslist, 'con_lost');
                   10929:             } else {
                   10930:                 # multiple library servers and no con_lost -> data should be
                   10931:                 # complete. 
                   10932:                 return (\@alluserslist);
                   10933:             }
                   10934: 
1.253     stredwic 10935:         } else {
1.1136    raeburn  10936:             return ([],'missing username');
1.253     stredwic 10937:         }
1.955     raeburn  10938:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10939:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10940:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10941:         return (\@all_domains);
1.955     raeburn  10942:     } else {
1.1136    raeburn  10943:         return ([],'missing domain');
1.275     stredwic 10944:     }
                   10945: }
                   10946: 
                   10947: # --------------------------------------------- GetFileTimestamp
                   10948: # This function utilizes dirlist and returns the date stamp for
                   10949: # when it was last modified.  It will also return an error of -1
                   10950: # if an error occurs
                   10951: 
                   10952: sub GetFileTimestamp {
1.955     raeburn  10953:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10954:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10955:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10956:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10957:                                     undef,$getuserdir);
                   10958:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10959:         return -1;
                   10960:     }
                   10961:     if (ref($fileref) eq 'ARRAY') {
                   10962:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10963:         # @stats contains first the filename, then the stat output
                   10964:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10965:     } else {
                   10966:         return -1;
1.253     stredwic 10967:     }
1.26      www      10968: }
                   10969: 
1.712     albertel 10970: sub stat_file {
                   10971:     my ($uri) = @_;
1.787     albertel 10972:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10973: 
1.955     raeburn  10974:     my ($udom,$uname,$file);
1.712     albertel 10975:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10976: 	($udom,$uname,$file) =
1.811     albertel 10977: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10978: 	$file = 'userfiles/'.$file;
                   10979:     }
                   10980:     if ($uri =~ m-^/res/-) {
                   10981: 	($udom,$uname) = 
1.807     albertel 10982: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10983: 	$file = $uri;
                   10984:     }
                   10985: 
                   10986:     if (!$udom || !$uname || !$file) {
                   10987: 	# unable to handle the uri
                   10988: 	return ();
                   10989:     }
1.956     raeburn  10990:     my $getpropath;
                   10991:     if ($file =~ /^userfiles\//) {
                   10992:         $getpropath = 1;
                   10993:     }
1.1136    raeburn  10994:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10995:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10996:         return ();
                   10997:     } else {
                   10998:         if (ref($listref) eq 'ARRAY') {
                   10999:             my @stats = split('&',$listref->[0]);
                   11000: 	    shift(@stats); #filename is first
                   11001: 	    return @stats;
                   11002:         }
1.712     albertel 11003:     }
                   11004:     return ();
                   11005: }
                   11006: 
1.1313    raeburn  11007: # --------------------------------------------------------- recursedirs
                   11008: # Recursive function to traverse either a specific user's Authoring Space
                   11009: # or corresponding Published Resource Space, and populate the hash ref:
                   11010: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11011: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11012: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11013: # files in Authoring Space.
                   11014: #
                   11015: # Inputs:
                   11016: #
                   11017: # $is_home - true if current server is home server for user's space
                   11018: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11019: # $docroot - Document root (i.e., /home/httpd/html
                   11020: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11021: # $relpath - Current path (relative to top level).
                   11022: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11023: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11024: #
                   11025: # Returns: nothing
                   11026: #
                   11027: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11028: #
                   11029: # Currently used by interface/londocs.pm to create linked select boxes for
                   11030: # directory and filename to import a Course "Author" resource into a course, and
                   11031: # also to create linked select boxes for Authoring Space and Directory to choose
                   11032: # save location for creation of a new "standard" problem from the Course Editor.
                   11033: #
                   11034: 
                   11035: sub recursedirs {
                   11036:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11037:     return unless (ref($dirhashref) eq 'HASH');
                   11038:     my $currpath = $docroot.$toppath;
                   11039:     if ($relpath) {
                   11040:         $currpath .= "/$relpath";
                   11041:     }
                   11042:     my $savefile;
                   11043:     if (ref($filehashref)) {
                   11044:         $savefile = 1;
                   11045:     }
                   11046:     if ($is_home) {
                   11047:         if (opendir(my $dirh,$currpath)) {
                   11048:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11049:                 next if ($item eq '');
                   11050:                 if (-d "$currpath/$item") {
                   11051:                     my $newpath;
                   11052:                     if ($relpath) {
                   11053:                         $newpath = "$relpath/$item";
                   11054:                     } else {
                   11055:                         $newpath = $item;
                   11056:                     }
                   11057:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11058:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11059:                 } elsif ($savefile) {
                   11060:                     if ($context eq 'priv') {
                   11061:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11062:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11063:                         }
                   11064:                     } else {
                   11065:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11066:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11067:                         }
                   11068:                     }
                   11069:                 }
                   11070:             }
                   11071:             closedir($dirh);
                   11072:         }
                   11073:     } else {
                   11074:         my ($dirlistref,$listerror) =
                   11075:             &dirlist($toppath.$relpath);
                   11076:         my @dir_lines;
                   11077:         my $dirptr=16384;
                   11078:         if (ref($dirlistref) eq 'ARRAY') {
                   11079:             foreach my $dir_line (sort
                   11080:                               {
                   11081:                                   my ($afile)=split('&',$a,2);
                   11082:                                   my ($bfile)=split('&',$b,2);
                   11083:                                   return (lc($afile) cmp lc($bfile));
                   11084:                               } (@{$dirlistref})) {
                   11085:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11086:                     split(/\&/,$dir_line,16);
                   11087:                 $item =~ s/\s+$//;
                   11088:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11089:                 if ($dirptr&$testdir) {
                   11090:                     my $newpath;
                   11091:                     if ($relpath) {
                   11092:                         $newpath = "$relpath/$item";
                   11093:                     } else {
                   11094:                         $relpath = '/';
                   11095:                         $newpath = $item;
                   11096:                     }
                   11097:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11098:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11099:                 } elsif ($savefile) {
                   11100:                     if ($context eq 'priv') {
                   11101:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11102:                             $filehashref->{$relpath}{$item} = 1;
                   11103:                         }
                   11104:                     } else {
                   11105:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11106:                             $filehashref->{$relpath}{$item} = 1;
                   11107:                         }
                   11108:                     }
                   11109:                 }
                   11110:             }
                   11111:         }
                   11112:     }
                   11113:     return;
                   11114: }
                   11115: 
1.26      www      11116: # -------------------------------------------------------- Value of a Condition
                   11117: 
1.713     albertel 11118: # gets the value of a specific preevaluated condition
                   11119: #    stored in the string  $env{user.state.<cid>}
                   11120: # or looks up a condition reference in the bighash and if if hasn't
                   11121: # already been evaluated recurses into docondval to get the value of
                   11122: # the condition, then memoizing it to 
                   11123: #   $env{user.state.<cid>.<condition>}
1.40      www      11124: sub directcondval {
                   11125:     my $number=shift;
1.620     albertel 11126:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11127: 	&Apache::lonuserstate::evalstate();
                   11128:     }
1.713     albertel 11129:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11130: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11131:     } elsif ($number =~ /^_/) {
                   11132: 	my $sub_condition;
                   11133: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11134: 		&GDBM_READER(),0640)) {
                   11135: 	    $sub_condition=$bighash{'conditions'.$number};
                   11136: 	    untie(%bighash);
                   11137: 	}
                   11138: 	my $value = &docondval($sub_condition);
1.949     raeburn  11139: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11140: 	return $value;
                   11141:     }
1.620     albertel 11142:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11143:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11144:     } else {
                   11145:        return 2;
                   11146:     }
                   11147: }
                   11148: 
1.713     albertel 11149: # get the collection of conditions for this resource
1.26      www      11150: sub condval {
                   11151:     my $condidx=shift;
1.54      www      11152:     my $allpathcond='';
1.713     albertel 11153:     foreach my $cond (split(/\|/,$condidx)) {
                   11154: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11155: 	    $allpathcond.=
                   11156: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11157: 	}
1.191     harris41 11158:     }
1.54      www      11159:     $allpathcond=~s/\|$//;
1.713     albertel 11160:     return &docondval($allpathcond);
                   11161: }
                   11162: 
                   11163: #evaluates an expression of conditions
                   11164: sub docondval {
                   11165:     my ($allpathcond) = @_;
                   11166:     my $result=0;
                   11167:     if ($env{'request.course.id'}
                   11168: 	&& defined($allpathcond)) {
                   11169: 	my $operand='|';
                   11170: 	my @stack;
                   11171: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11172: 	    if ($chunk eq '(') {
                   11173: 		push @stack,($operand,$result);
                   11174: 	    } elsif ($chunk eq ')') {
                   11175: 		my $before=pop @stack;
                   11176: 		if (pop @stack eq '&') {
                   11177: 		    $result=$result>$before?$before:$result;
                   11178: 		} else {
                   11179: 		    $result=$result>$before?$result:$before;
                   11180: 		}
                   11181: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11182: 		$operand=$chunk;
                   11183: 	    } else {
                   11184: 		my $new=directcondval($chunk);
                   11185: 		if ($operand eq '&') {
                   11186: 		    $result=$result>$new?$new:$result;
                   11187: 		} else {
                   11188: 		    $result=$result>$new?$result:$new;
                   11189: 		}
                   11190: 	    }
                   11191: 	}
1.26      www      11192:     }
                   11193:     return $result;
1.421     albertel 11194: }
                   11195: 
                   11196: # ---------------------------------------------------- Devalidate courseresdata
                   11197: 
                   11198: sub devalidatecourseresdata {
                   11199:     my ($coursenum,$coursedomain)=@_;
                   11200:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11201:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11202: }
                   11203: 
1.763     www      11204: 
1.200     www      11205: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11206: #
                   11207: #  Parameters:
                   11208: #      $coursenum    - Number of the course.
                   11209: #      $coursedomain - Domain at which the course was created.
                   11210: #  Returns:
                   11211: #     A hash of the course parameters along (I think) with timestamps
                   11212: #     and version info.
1.877     foxr     11213: 
1.624     albertel 11214: sub get_courseresdata {
                   11215:     my ($coursenum,$coursedomain)=@_;
1.200     www      11216:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11217:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11218:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11219:     my %dumpreply;
1.417     albertel 11220:     unless (defined($cached)) {
1.624     albertel 11221: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11222: 	$result=\%dumpreply;
1.251     albertel 11223: 	my ($tmp) = keys(%dumpreply);
                   11224: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11225: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11226: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11227: 	    return $tmp;
1.416     albertel 11228: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11229: 	    $result=undef;
1.599     albertel 11230: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11231: 	}
                   11232:     }
1.624     albertel 11233:     return $result;
                   11234: }
                   11235: 
1.633     albertel 11236: sub devalidateuserresdata {
                   11237:     my ($uname,$udom)=@_;
                   11238:     my $hashid="$udom:$uname";
                   11239:     &devalidate_cache_new('userres',$hashid);
                   11240: }
                   11241: 
1.624     albertel 11242: sub get_userresdata {
                   11243:     my ($uname,$udom)=@_;
                   11244:     #most student don\'t have any data set, check if there is some data
                   11245:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11246: 
                   11247:     my $hashid="$udom:$uname";
                   11248:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11249:     if (!defined($cached)) {
                   11250: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11251: 	$result=\%resourcedata;
                   11252: 	&do_cache_new('userres',$hashid,$result,600);
                   11253:     }
                   11254:     my ($tmp)=keys(%$result);
                   11255:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11256: 	return $result;
                   11257:     }
                   11258:     #error 2 occurs when the .db doesn't exist
                   11259:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11260:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11261: 	    &logthis("<font color=\"blue\">WARNING:".
                   11262: 		     " Trying to get resource data for ".
                   11263: 		     $uname." at ".$udom.": ".
                   11264: 		     $tmp."</font>");
                   11265:         }
1.624     albertel 11266:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11267: 	#&EXT_cache_set($udom,$uname);
                   11268: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11269: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11270:     }
                   11271:     return $tmp;
                   11272: }
1.879     foxr     11273: #----------------------------------------------- resdata - return resource data
                   11274: #  Purpose:
                   11275: #    Return resource data for either users or for a course.
                   11276: #  Parameters:
                   11277: #     $name      - Course/user name.
                   11278: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11279: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11280: #     $mapp      - decluttered URL of enclosing map  
                   11281: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11282: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11283: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11284: #     $courseid  - CourseID (first part of param identifier).
                   11285: #     $modifier  - Middle part of param identifier.
                   11286: #     $what      - Last part of param identifier.
1.879     foxr     11287: #     @which     - Array of names of resources desired.
                   11288: #  Returns:
                   11289: #     The value of the first reasource in @which that is found in the
                   11290: #     resource hash.
                   11291: #  Exceptional Conditions:
                   11292: #     If the $type passed in is not valid (not the string 'course' or 
                   11293: #     'user', an undefined  reference is returned.
                   11294: #     If none of the resources are found, an undef is returned
1.624     albertel 11295: sub resdata {
1.1301    raeburn  11296:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11297:         $modifier,$what,@which)=@_;
1.624     albertel 11298:     my $result;
                   11299:     if ($type eq 'course') {
                   11300: 	$result=&get_courseresdata($name,$domain);
                   11301:     } elsif ($type eq 'user') {
                   11302: 	$result=&get_userresdata($name,$domain);
                   11303:     }
                   11304:     if (!ref($result)) { return $result; }    
1.251     albertel 11305:     foreach my $item (@which) {
1.1301    raeburn  11306:         if ($item->[1] eq 'course') {
                   11307:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11308:                 unless ($$recursed) {
1.1302    raeburn  11309:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11310:                     $$recursed = 1;
                   11311:                 }
                   11312:                 foreach my $item (@${recurseup}) {
                   11313:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11314:                     last if (defined($result->{$norecursechk}));
                   11315:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11316:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11317:                 }
                   11318:             }
                   11319:         }
                   11320:         if (defined($result->{$item->[0]})) {
1.927     albertel 11321: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11322: 	}
1.250     albertel 11323:     }
1.291     albertel 11324:     return undef;
1.200     www      11325: }
                   11326: 
1.1360    raeburn  11327: sub get_domain_lti {
                   11328:     my ($cdom,$context) = @_;
                   11329:     my ($name,%lti);
                   11330:     if ($context eq 'consumer') {
                   11331:         $name = 'ltitools';
                   11332:     } elsif ($context eq 'provider') {
                   11333:         $name = 'lti';
                   11334:     } else {
                   11335:         return %lti;
                   11336:     }
                   11337:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11338:     if (defined($cached)) {
                   11339:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11340:             %lti = %{$result};
1.1298    raeburn  11341:         }
                   11342:     } else {
1.1360    raeburn  11343:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11344:         if (ref($domconfig{$name}) eq 'HASH') {
                   11345:             %lti = %{$domconfig{$name}};
                   11346:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11347:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11348:                 foreach my $id (keys(%lti)) {
                   11349:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11350:                         foreach my $item ('key','secret') {
1.1360    raeburn  11351:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11352:                         }
                   11353:                     }
                   11354:                 }
                   11355:             }
1.1298    raeburn  11356:         }
                   11357:         my $cachetime = 24*60*60;
1.1360    raeburn  11358:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11359:     }
1.1360    raeburn  11360:     return %lti;
1.1298    raeburn  11361: }
                   11362: 
1.1236    raeburn  11363: sub get_numsuppfiles {
                   11364:     my ($cnum,$cdom,$ignorecache)=@_;
                   11365:     my $hashid=$cnum.':'.$cdom;
                   11366:     my ($suppcount,$cached);
                   11367:     unless ($ignorecache) {
                   11368:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11369:     }
                   11370:     unless (defined($cached)) {
                   11371:         my $chome=&homeserver($cnum,$cdom);
                   11372:         unless ($chome eq 'no_host') {
1.1366    raeburn  11373:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11374:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11375:             ($suppcount,$supptools,$errors) =
                   11376:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11377:                                                          $supptools,$errors);
1.1236    raeburn  11378:         }
                   11379:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11380:     }
                   11381:     return $suppcount;
                   11382: }
                   11383: 
1.379     matthew  11384: #
                   11385: # EXT resource caching routines
                   11386: #
                   11387: 
1.1302    raeburn  11388: {
                   11389: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11390: #
                   11391: # The course for which we cache
                   11392: my $cachedmapkey='';
                   11393: # The cached recursive maps for this course
                   11394: my %cachedmaps=();
                   11395: # When this was last done
                   11396: my $cachedmaptime='';
                   11397: 
1.379     matthew  11398: sub clear_EXT_cache_status {
1.383     albertel 11399:     &delenv('cache.EXT.');
1.379     matthew  11400: }
                   11401: 
                   11402: sub EXT_cache_status {
                   11403:     my ($target_domain,$target_user) = @_;
1.383     albertel 11404:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11405:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11406:         # We know already the user has no data
                   11407:         return 1;
                   11408:     } else {
                   11409:         return 0;
                   11410:     }
                   11411: }
                   11412: 
                   11413: sub EXT_cache_set {
                   11414:     my ($target_domain,$target_user) = @_;
1.383     albertel 11415:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11416:     #&appenv({$cachename => time});
1.379     matthew  11417: }
                   11418: 
1.28      www      11419: # --------------------------------------------------------- Value of a Variable
1.58      www      11420: sub EXT {
1.715     albertel 11421: 
1.1228    raeburn  11422:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11423:     unless ($varname) { return ''; }
1.218     albertel 11424:     #get real user name/domain, courseid and symb
                   11425:     my $courseid;
1.359     albertel 11426:     my $publicuser;
1.427     www      11427:     if ($symbparm) {
                   11428: 	$symbparm=&get_symb_from_alias($symbparm);
                   11429:     }
1.218     albertel 11430:     if (!($uname && $udom)) {
1.790     albertel 11431:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11432:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11433:     } else {
1.620     albertel 11434: 	$courseid=$env{'request.course.id'};
1.218     albertel 11435:     }
1.48      www      11436:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11437:     my $rest;
1.320     albertel 11438:     if (defined($therest[0])) {
1.48      www      11439:        $rest=join('.',@therest);
                   11440:     } else {
                   11441:        $rest='';
                   11442:     }
1.320     albertel 11443: 
1.57      www      11444:     my $qualifierrest=$qualifier;
                   11445:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11446:     my $spacequalifierrest=$space;
                   11447:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11448:     if ($realm eq 'user') {
1.48      www      11449: # --------------------------------------------------------------- user.resource
                   11450: 	if ($space eq 'resource') {
1.651     albertel 11451: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11452: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11453: 		 &&
1.744     albertel 11454: 		 ($symbparm eq &symbread()) ) {	
                   11455: 		# if we are in the middle of processing the resource the
                   11456: 		# get the value we are planning on committing
                   11457:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11458:                     return $Apache::lonhomework::results{$qualifierrest};
                   11459:                 } else {
                   11460:                     return $Apache::lonhomework::history{$qualifierrest};
                   11461:                 }
1.335     albertel 11462: 	    } else {
1.359     albertel 11463: 		my %restored;
1.620     albertel 11464: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11465: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11466: 		} else {
                   11467: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11468: 		}
1.335     albertel 11469: 		return $restored{$qualifierrest};
                   11470: 	    }
1.48      www      11471: # ----------------------------------------------------------------- user.access
                   11472:         } elsif ($space eq 'access') {
1.218     albertel 11473: 	    # FIXME - not supporting calls for a specific user
1.48      www      11474:             return &allowed($qualifier,$rest);
                   11475: # ------------------------------------------ user.preferences, user.environment
                   11476:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11477: 	    if (($uname eq $env{'user.name'}) &&
                   11478: 		($udom eq $env{'user.domain'})) {
                   11479: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11480: 	    } else {
1.359     albertel 11481: 		my %returnhash;
                   11482: 		if (!$publicuser) {
                   11483: 		    %returnhash=&userenvironment($udom,$uname,
                   11484: 						 $qualifierrest);
                   11485: 		}
1.218     albertel 11486: 		return $returnhash{$qualifierrest};
                   11487: 	    }
1.48      www      11488: # ----------------------------------------------------------------- user.course
                   11489:         } elsif ($space eq 'course') {
1.218     albertel 11490: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11491:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11492: # ------------------------------------------------------------------- user.role
                   11493:         } elsif ($space eq 'role') {
1.218     albertel 11494: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11495:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11496:             if ($qualifier eq 'value') {
                   11497: 		return $role;
                   11498:             } elsif ($qualifier eq 'extent') {
                   11499:                 return $where;
                   11500:             }
                   11501: # ----------------------------------------------------------------- user.domain
                   11502:         } elsif ($space eq 'domain') {
1.218     albertel 11503:             return $udom;
1.48      www      11504: # ------------------------------------------------------------------- user.name
                   11505:         } elsif ($space eq 'name') {
1.218     albertel 11506:             return $uname;
1.48      www      11507: # ---------------------------------------------------- Any other user namespace
1.29      www      11508:         } else {
1.359     albertel 11509: 	    my %reply;
                   11510: 	    if (!$publicuser) {
                   11511: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11512: 	    }
                   11513: 	    return $reply{$qualifierrest};
1.48      www      11514:         }
1.236     www      11515:     } elsif ($realm eq 'query') {
                   11516: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11517:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11518: 						[$spacequalifierrest]);
1.620     albertel 11519: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11520:    } elsif ($realm eq 'request') {
1.48      www      11521: # ------------------------------------------------------------- request.browser
                   11522:         if ($space eq 'browser') {
1.1145    bisitz   11523:             return $env{'browser.'.$qualifier};
1.57      www      11524: # ------------------------------------------------------------ request.filename
                   11525:         } else {
1.620     albertel 11526:             return $env{'request.'.$spacequalifierrest};
1.29      www      11527:         }
1.28      www      11528:     } elsif ($realm eq 'course') {
1.48      www      11529: # ---------------------------------------------------------- course.description
1.620     albertel 11530:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11531:     } elsif ($realm eq 'resource') {
1.165     www      11532: 
1.620     albertel 11533: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11534: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11535: 	}
1.693     albertel 11536: 
1.1232    raeburn  11537:         if ($qualifier eq '') {
                   11538: 	    if ($space eq 'title') {
                   11539: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11540: 	        return &gettitle($symbparm);
                   11541: 	    }
1.693     albertel 11542: 	
1.1232    raeburn  11543: 	    if ($space eq 'map') {
                   11544: 	        my ($map) = &decode_symb($symbparm);
                   11545: 	        return &symbread($map);
                   11546: 	    }
                   11547:             if ($space eq 'maptitle') {
                   11548:                 my ($map) = &decode_symb($symbparm);
                   11549:                 return &gettitle($map);
                   11550:             }
                   11551: 	    if ($space eq 'filename') {
                   11552: 	        if ($symbparm) {
                   11553: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11554: 	        }
                   11555: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11556: 	    }
1.1232    raeburn  11557: 
1.1233    raeburn  11558:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11559:                 if ($space eq 'visibleparts') {
                   11560:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11561:                     my $item;
                   11562:                     if (ref($navmap)) {
                   11563:                         my $res = $navmap->getBySymb($symbparm);
                   11564:                         my $parts = $res->parts();
                   11565:                         if (ref($parts) eq 'ARRAY') {
                   11566:                             $item = join(',',@{$parts});
                   11567:                         }
                   11568:                         undef($navmap);
1.1232    raeburn  11569:                     }
1.1233    raeburn  11570:                     return $item;
1.1232    raeburn  11571:                 }
                   11572:             }
                   11573:         }
1.693     albertel 11574: 
1.1301    raeburn  11575: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11576: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11577:         if (($courseid eq '') && ($cid)) {
                   11578:             $courseid = $cid;
                   11579:         }
                   11580: 	if (($symbparm && $courseid) && 
                   11581: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11582: 
1.218     albertel 11583: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11584: 
1.60      www      11585: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11586: 	    my $symbp=$symbparm;
1.1301    raeburn  11587: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11588: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11589:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11590: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11591: 	    if (($env{'user.name'} eq $uname) &&
                   11592: 		($env{'user.domain'} eq $udom)) {
                   11593: 		$section=$env{'request.course.sec'};
1.733     raeburn  11594:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11595:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11596: 	    } else {
1.539     albertel 11597: 		if (! defined($usection)) {
1.551     albertel 11598: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11599: 		} else {
                   11600: 		    $section = $usection;
                   11601: 		}
1.733     raeburn  11602:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11603: 	    }
                   11604: 
                   11605: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11606: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11607:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11608: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11609: 
1.593     albertel 11610: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11611: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11612:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11613: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11614: 
1.60      www      11615: # ----------------------------------------------------------- first, check user
1.624     albertel 11616: 
1.1301    raeburn  11617: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11618:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11619: 				       ([$courselevelr,'resource'],
                   11620: 					[$courselevelm,'map'     ],
1.1301    raeburn  11621:                                         [$courseleveli,'map'     ],
1.927     albertel 11622: 					[$courselevel, 'course'  ]));
1.931     albertel 11623: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11624: 
1.594     albertel 11625: # ------------------------------------------------ second, check some of course
1.684     raeburn  11626:             my $coursereply;
1.691     raeburn  11627:             if (@groups > 0) {
                   11628:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11629:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11630:                                        $mapp,\$recursed,\@recurseup);
                   11631:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11632:             }
1.96      www      11633: 
1.684     raeburn  11634: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11635: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11636: 				  'course',$mapp,\$recursed,\@recurseup,
                   11637:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11638: 				  ([$seclevelr,   'resource'],
                   11639: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11640:                                    [$secleveli,   'map'     ],
1.927     albertel 11641: 				   [$seclevel,    'course'  ],
                   11642: 				   [$courselevelr,'resource']));
                   11643: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11644: 
1.60      www      11645: # ------------------------------------------------------ third, check map parms
1.218     albertel 11646: 	    my %parmhash=();
                   11647: 	    my $thisparm='';
                   11648: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11649: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11650: 		    &GDBM_READER(),0640)) {
1.218     albertel 11651: 		$thisparm=$parmhash{$symbparm};
                   11652: 		untie(%parmhash);
                   11653: 	    }
1.927     albertel 11654: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11655: 	}
1.594     albertel 11656: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11657:  
                   11658:         my $what = $spacequalifierrest;
                   11659: 	$what=~s/\./\_/;
1.282     albertel 11660: 	my $filename;
                   11661: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11662: 	if ($symbparm) {
1.409     www      11663: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11664: 	} else {
1.620     albertel 11665: 	    $filename=$env{'request.filename'};
1.282     albertel 11666: 	}
1.1362    raeburn  11667:         my $toolsymb;
                   11668:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11669:             $toolsymb = $symbparm;
                   11670:         }
                   11671: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11672: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11673: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11674: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11675: 
1.1301    raeburn  11676: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11677: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11678: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11679: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11680: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11681: 				     'course',$mapp,\$recursed,\@recurseup,
                   11682:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11683: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11684:                                       [$courseleveli,'map'   ],
1.927     albertel 11685: 				      [$courselevel, 'course']));
                   11686: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11687: 	}
1.145     www      11688: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11689: 	unless ($space eq '0') {
1.336     albertel 11690: 	    my @parts=split(/_/,$space);
                   11691: 	    my $id=pop(@parts);
                   11692: 	    my $part=join('_',@parts);
                   11693: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11694: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11695: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11696: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11697: 	}
1.395     albertel 11698: 	if ($recurse) { return undef; }
1.1362    raeburn  11699: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11700: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11701: # ---------------------------------------------------- Any other user namespace
                   11702:     } elsif ($realm eq 'environment') {
                   11703: # ----------------------------------------------------------------- environment
1.620     albertel 11704: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11705: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11706: 	} else {
1.770     albertel 11707: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11708: 		return '';
                   11709: 	    }
1.219     albertel 11710: 	    my %returnhash=&userenvironment($udom,$uname,
                   11711: 					    $spacequalifierrest);
                   11712: 	    return $returnhash{$spacequalifierrest};
                   11713: 	}
1.28      www      11714:     } elsif ($realm eq 'system') {
1.48      www      11715: # ----------------------------------------------------------------- system.time
                   11716: 	if ($space eq 'time') {
                   11717: 	    return time;
                   11718:         }
1.696     albertel 11719:     } elsif ($realm eq 'server') {
                   11720: # ----------------------------------------------------------------- system.time
                   11721: 	if ($space eq 'name') {
                   11722: 	    return $ENV{'SERVER_NAME'};
                   11723:         }
1.28      www      11724:     }
1.48      www      11725:     return '';
1.61      www      11726: }
                   11727: 
1.927     albertel 11728: sub get_reply {
                   11729:     my ($reply_value) = @_;
1.940     raeburn  11730:     if (ref($reply_value) eq 'ARRAY') {
                   11731:         if (wantarray) {
                   11732: 	    return @$reply_value;
                   11733:         }
                   11734:         return $reply_value->[0];
                   11735:     } else {
                   11736:         return $reply_value;
1.927     albertel 11737:     }
                   11738: }
                   11739: 
1.691     raeburn  11740: sub check_group_parms {
1.1301    raeburn  11741:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11742:         $recursed,$recurseupref) = @_;
                   11743:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11744:                   [$what,'course']);
                   11745:     my $coursereply;
1.691     raeburn  11746:     foreach my $group (@{$groups}) {
1.1301    raeburn  11747:         my @groupitems = ();
1.691     raeburn  11748:         foreach my $level (@levels) {
1.927     albertel 11749:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11750:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11751:         }
1.1301    raeburn  11752:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11753:                                    $env{'course.'.$courseid.'.domain'},
                   11754:                                    'course',$mapp,$recursed,$recurseupref,
                   11755:                                    $courseid,'.['.$group.'].',$what,
                   11756:                                    @groupitems);
                   11757:         last if (defined($coursereply));
1.691     raeburn  11758:     }
                   11759:     return $coursereply;
                   11760: }
                   11761: 
1.1301    raeburn  11762: sub get_map_hierarchy {
1.1302    raeburn  11763:     my ($mapname,$courseid) = @_;
                   11764:     my @recurseup = ();
1.1301    raeburn  11765:     if ($mapname) {
1.1302    raeburn  11766:         if (($cachedmapkey eq $courseid) &&
                   11767:             (abs($cachedmaptime-time)<5)) {
                   11768:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11769:                 return @{$cachedmaps{$mapname}};
                   11770:             }
                   11771:         }
1.1301    raeburn  11772:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11773:         if (ref($navmap)) {
                   11774:             @recurseup = $navmap->recurseup_maps($mapname);
                   11775:             undef($navmap);
1.1302    raeburn  11776:             $cachedmaps{$mapname} = \@recurseup;
                   11777:             $cachedmaptime=time;
                   11778:             $cachedmapkey=$courseid;
1.1301    raeburn  11779:         }
                   11780:     }
                   11781:     return @recurseup;
                   11782: }
                   11783: 
1.1302    raeburn  11784: }
                   11785: 
1.691     raeburn  11786: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11787:     my ($courseid,@groups) = @_;
                   11788:     @groups = sort(@groups);
1.691     raeburn  11789:     return @groups;
                   11790: }
                   11791: 
1.395     albertel 11792: sub packages_tab_default {
1.1362    raeburn  11793:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11794:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11795: 
                   11796:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11797:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11798: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11799: 	if ($pack_type eq 'default') {
                   11800: 	    $do_default=1;
                   11801: 	} elsif ($pack_type eq 'extension') {
                   11802: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11803: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11804: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11805: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11806: 	}
                   11807:     }
                   11808:     # first look for a package that matches the requested part id
                   11809:     foreach my $package (@specifics) {
                   11810: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11811: 	next if ($pack_part ne $part);
                   11812: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11813: 	    return $packagetab{"$pack_type&$name&default"};
                   11814: 	}
                   11815:     }
                   11816:     # look for any possible matching non extension_ package
                   11817:     foreach my $package (@specifics) {
                   11818: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11819: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11820: 	    return $packagetab{"$pack_type&$name&default"};
                   11821: 	}
1.585     albertel 11822: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11823: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11824: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11825: 	}
                   11826:     }
1.738     albertel 11827:     # look for any posible extension_ match
                   11828:     foreach my $package (@extension) {
                   11829: 	my ($package,$pack_type)=@{$package};
                   11830: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11831: 	    return $packagetab{"$pack_type&$name&default"};
                   11832: 	}
                   11833: 	if (defined($packagetab{$package."&$name&default"})) {
                   11834: 	    return $packagetab{$package."&$name&default"};
                   11835: 	}
                   11836:     }
                   11837:     # look for a global default setting
                   11838:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11839: 	return $packagetab{"default&$name&default"};
                   11840:     }
1.395     albertel 11841:     return undef;
                   11842: }
                   11843: 
1.334     albertel 11844: sub add_prefix_and_part {
                   11845:     my ($prefix,$part)=@_;
                   11846:     my $keyroot;
                   11847:     if (defined($prefix) && $prefix !~ /^__/) {
                   11848: 	# prefix that has a part already
                   11849: 	$keyroot=$prefix;
                   11850:     } elsif (defined($prefix)) {
                   11851: 	# prefix that is missing a part
                   11852: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11853:     } else {
                   11854: 	# no prefix at all
                   11855: 	if (defined($part)) { $keyroot='_'.$part; }
                   11856:     }
                   11857:     return $keyroot;
                   11858: }
                   11859: 
1.71      www      11860: # ---------------------------------------------------------------- Get metadata
                   11861: 
1.599     albertel 11862: my %metaentry;
1.1070    www      11863: my %importedpartids;
1.1369    raeburn  11864: my %importedrespids;
1.71      www      11865: sub metadata {
1.1362    raeburn  11866:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11867:     $uri=&declutter($uri);
1.288     albertel 11868:     # if it is a non metadata possible uri return quickly
1.529     albertel 11869:     if (($uri eq '') || 
                   11870: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11871: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11872:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11873: 	return undef;
                   11874:     }
1.1261    raeburn  11875:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11876: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11877: 	return undef;
1.288     albertel 11878:     }
1.73      www      11879:     my $filename=$uri;
                   11880:     $uri=~s/\.meta$//;
1.172     www      11881: #
                   11882: # Is the metadata already cached?
1.177     www      11883: # Look at timestamp of caching
1.172     www      11884: # Everything is cached by the main uri, libraries are never directly cached
                   11885: #
1.428     albertel 11886:     if (!defined($liburi)) {
1.599     albertel 11887: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11888: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11889:     }
1.1362    raeburn  11890: 
                   11891: #
                   11892: # If the uri is for an external tool the file from
                   11893: # which metadata should be retrieved depends on whether
                   11894: # the tool had been configured to be gradable (set in the Course
                   11895: # Editor or Resource Editor).
                   11896: #
                   11897: # If a valid symb has been included as the third arg in the call
                   11898: # to &metadata() that can be used to retrieve the value of
                   11899: # parameter_0_gradable set for the resource, and included in the
                   11900: # uploaded map containing the tool. The value is retrieved via
                   11901: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11902: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11903: # is retrieved via &get().
                   11904: #
                   11905: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11906: # hiddenresource and encrypturl (during course initialization)
                   11907: # the map-level parameter for resource.0.gradable included in the 
                   11908: # uploaded map containing the tool will not yet have been stored
                   11909: # in the user_course_parms.db file for the user's session, so in 
                   11910: # this case fall back to retrieving gradable status from the
                   11911: # exttool_$marker.db file.
1.1362    raeburn  11912: #
                   11913: # In order to avoid an infinite loop, &metadata() will return
                   11914: # before a call to &EXT(), if the uri is for an external tool
                   11915: # and the $what for which metadata is being requested is
                   11916: # parameter_0_gradable or 0_gradable.
                   11917: #
                   11918: 
                   11919:     if ($uri =~ /ext\.tool$/) {
                   11920:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11921:             return;
                   11922:         } else {
                   11923:             my ($checked,$use_passback);
                   11924:             if ($toolsymb ne '') {
                   11925:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11926:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11927:                     $checked = 1;
                   11928:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11929:                         $use_passback = 1;
                   11930:                     }
                   11931:                 }
                   11932:             }
                   11933:             unless ($checked) {
                   11934:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11935:                 $marker=~s/\D//g;
1.1363    raeburn  11936:                 if ($marker) {
1.1362    raeburn  11937:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11938:                     $use_passback = $toolsettings{'gradable'};
                   11939:                 }
                   11940:             }
                   11941:             if ($use_passback) {
                   11942:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11943:             } else {
                   11944:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11945:             }
                   11946:         }
                   11947:     }
                   11948: 
1.428     albertel 11949:     {
1.1069    www      11950: # Imported parts would go here
1.1369    raeburn  11951:         my @origfiletagids=();
1.1069    www      11952:         my $importedparts=0;
1.1369    raeburn  11953: 
                   11954: # Imported responseids would go here
                   11955:         my $importedresponses=0;
1.172     www      11956: #
                   11957: # Is this a recursive call for a library?
                   11958: #
1.599     albertel 11959: #	if (! exists($metacache{$uri})) {
                   11960: #	    $metacache{$uri}={};
                   11961: #	}
1.924     albertel 11962: 	my $cachetime = 60*60;
1.171     www      11963:         if ($liburi) {
                   11964: 	    $liburi=&declutter($liburi);
                   11965:             $filename=$liburi;
1.401     bowersj2 11966:         } else {
1.599     albertel 11967: 	    &devalidate_cache_new('meta',$uri);
                   11968: 	    undef(%metaentry);
1.401     bowersj2 11969: 	}
1.140     www      11970:         my %metathesekeys=();
1.73      www      11971:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11972: 	my $metastring;
1.1140    www      11973: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11974: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11975: 	    $metastring = 
1.929     albertel 11976: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11977: 					  ('grade_target' => 'meta'));
                   11978: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11979: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11980:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11981: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11982: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11983: 	    $metastring=&getfile($file);
1.489     albertel 11984: 	}
1.208     albertel 11985:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11986:         my $token;
1.140     www      11987:         undef %metathesekeys;
1.71      www      11988:         while ($token=$parser->get_token) {
1.339     albertel 11989: 	    if ($token->[0] eq 'S') {
                   11990: 		if (defined($token->[2]->{'package'})) {
1.172     www      11991: #
                   11992: # This is a package - get package info
                   11993: #
1.339     albertel 11994: 		    my $package=$token->[2]->{'package'};
                   11995: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11996: 		    if (defined($token->[2]->{'id'})) { 
                   11997: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11998: 		    }
1.599     albertel 11999: 		    if ($metaentry{':packages'}) {
                   12000: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12001: 		    } else {
1.599     albertel 12002: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12003: 		    }
1.736     albertel 12004: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12005: 			my $part=$keyroot;
                   12006: 			$part=~s/^\_//;
1.736     albertel 12007: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12008: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12009: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12010: 			    # ignore package.tab specified default values
                   12011:                             # here &package_tab_default() will fetch those
                   12012: 			    if ($subp eq 'default') { next; }
1.736     albertel 12013: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12014: 			    my $unikey;
                   12015: 			    if ($pack =~ /_0$/) {
                   12016: 				$unikey='parameter_0_'.$name;
                   12017: 				$part=0;
                   12018: 			    } else {
                   12019: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12020: 			    }
1.339     albertel 12021: 			    if ($subp eq 'display') {
                   12022: 				$value.=' [Part: '.$part.']';
                   12023: 			    }
1.599     albertel 12024: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12025: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12026: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12027: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12028: 			    }
1.599     albertel 12029: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12030: 				$metaentry{':'.$unikey}=
                   12031: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12032: 			    }
1.339     albertel 12033: 			}
                   12034: 		    }
                   12035: 		} else {
1.172     www      12036: #
                   12037: # This is not a package - some other kind of start tag
1.339     albertel 12038: #
                   12039: 		    my $entry=$token->[1];
1.1068    www      12040: 		    my $unikey='';
1.175     www      12041: 
1.339     albertel 12042: 		    if ($entry eq 'import') {
1.175     www      12043: #
                   12044: # Importing a library here
1.339     albertel 12045: #
1.1067    www      12046:                         my $location=$parser->get_text('/import');
                   12047:                         my $dir=$filename;
                   12048:                         $dir=~s|[^/]*$||;
                   12049:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12050: 
                   12051:                         my $importid=$token->[2]->{'id'};
1.1068    www      12052:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12053: #
                   12054: # Check metadata for imported file to
                   12055: # see if it contained response items
                   12056: #
1.1372    raeburn  12057:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12058:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12059:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12060:                                                            $depthcount+1));
                   12061:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12062:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12063:                                                              undef,$depthcount+1);
                   12064:                             if ($libresponseorder ne '') {
                   12065:                                 if ($#origfiletagids<0) {
                   12066:                                     undef(%importedrespids);
                   12067:                                     undef(%importedpartids);
                   12068:                                 }
1.1373    raeburn  12069:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12070:                                 if (@respids) {
                   12071:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12072:                                 }
                   12073:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12074:                                     $importedresponses = 1;
1.1369    raeburn  12075: # We need to get the original file and the imported file to get the response order correct
                   12076: # Load and inspect original file
1.1372    raeburn  12077:                                     if ($#origfiletagids<0) {
                   12078:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12079:                                         $origfile=&getfile($origfilelocation);
                   12080:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12081:                                     }
1.1369    raeburn  12082:                                 }
                   12083:                             }
                   12084:                         }
1.1370    raeburn  12085: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12086: # hash populated for imported library file
                   12087:                         %metaentry = %currmetaentry;
                   12088:                         undef(%currmetaentry);
1.1374    raeburn  12089:                         if ($importmode eq 'part') {
1.1068    www      12090: # Import as part(s)
1.1069    www      12091:                            $importedparts=1;
                   12092: # We need to get the original file and the imported file to get the part order correct
                   12093: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12094: # Load and inspect original file if we didn't do that already
                   12095:                            if ($#origfiletagids<0) {
                   12096:                                undef(%importedrespids);
                   12097:                                undef(%importedpartids);
                   12098:                                if ($origfile eq '') {
                   12099:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12100:                                    $origfile=&getfile($origfilelocation);
                   12101:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12102:                                }
1.1070    www      12103:                            }
1.1372    raeburn  12104:                            my @impfilepartids;
                   12105: # If <partorder> tag is included in metadata for the imported file
                   12106: # get the parts in the imported file from that.
                   12107:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12108:                                %currmetaentry = %metaentry;
                   12109:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12110:                                                             $depthcount+1);
                   12111:                                %metaentry = %currmetaentry;
                   12112:                                undef(%currmetaentry);
                   12113:                                if ($libpartorder ne '') {
                   12114:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12115:                                }
                   12116:                            } else {
                   12117: # If no <partorder> tag available, load and inspect imported file
                   12118:                                my $impfile=&getfile($location);
                   12119:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12120:                            }
1.1069    www      12121:                            if ($#impfilepartids>=0) {
                   12122: # This problem had parts
1.1070    www      12123:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12124:                            } else {
                   12125: # Importing by turning a single problem into a problem part
                   12126: # It gets the import-tags ID as part-ID
                   12127:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12128:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12129:                            }
1.1068    www      12130:                         } else {
1.1374    raeburn  12131: # Import as problem or as normal import
                   12132:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12133:                             unless ($importmode eq 'problem') {
1.1068    www      12134: # Normal import
1.1374    raeburn  12135:                                 if (defined($token->[2]->{'id'})) {
                   12136:                                     $unikey.='_'.$token->[2]->{'id'};
                   12137:                                 }
                   12138:                             }
                   12139: # Check metadata for imported file to
                   12140: # see if it contained parts
                   12141:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12142:                                 %currmetaentry = %metaentry;
                   12143:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12144:                                                              $depthcount+1);
                   12145:                                 %metaentry = %currmetaentry;
                   12146:                                 undef(%currmetaentry);
                   12147:                                 if ($libpartorder ne '') {
                   12148:                                     $importedparts = 1;
                   12149:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12150:                                 }
                   12151:                             }
1.1067    www      12152:                         }
1.339     albertel 12153: 			if ($depthcount<20) {
1.736     albertel 12154: 			    my $metadata = 
1.1362    raeburn  12155: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12156: 					  $depthcount+1);
                   12157: 			    foreach my $meta (split(',',$metadata)) {
                   12158: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12159: 				$metathesekeys{$meta}=1;
1.339     albertel 12160: 			    }
1.1068    www      12161:                         }
1.1067    www      12162: 		    } else {
                   12163: #
                   12164: # Not importing, some other kind of non-package, non-library start tag
                   12165: # 
                   12166:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12167:                         if (defined($token->[2]->{'id'})) {
                   12168:                             $unikey.='_'.$token->[2]->{'id'};
                   12169:                         }
1.339     albertel 12170: 			if (defined($token->[2]->{'name'})) { 
                   12171: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12172: 			}
                   12173: 			$metathesekeys{$unikey}=1;
1.736     albertel 12174: 			foreach my $param (@{$token->[3]}) {
                   12175: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12176: 				$token->[2]->{$param};
1.339     albertel 12177: 			}
                   12178: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12179: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12180: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12181: 		 # only ws inside the tag, and not in default, so use default
                   12182: 		 # as value
1.599     albertel 12183: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12184: 			} elsif ( $internaltext =~ /\S/ ) {
                   12185: 		  # something interesting inside the tag
                   12186: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12187: 			} else {
1.908     albertel 12188: 		  # no interesting values, don't set a default
1.339     albertel 12189: 			}
1.172     www      12190: # end of not-a-package not-a-library import
1.339     albertel 12191: 		    }
1.172     www      12192: # end of not-a-package start tag
1.339     albertel 12193: 		}
1.172     www      12194: # the next is the end of "start tag"
1.339     albertel 12195: 	    }
                   12196: 	}
1.483     albertel 12197: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12198: 	$extension = lc($extension);
                   12199: 	if ($extension eq 'htm') { $extension='html'; }
                   12200: 
1.737     albertel 12201: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12202: 	    #no specific packages #how's our extension
                   12203: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12204: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12205: 					 \%metathesekeys);
                   12206: 	}
1.883     albertel 12207: 
                   12208: 	if (!exists($metaentry{':packages'})
                   12209: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12210: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12211: 		#no specific packages well let's get default then
                   12212: 		if ($key!~/^default&/) { next; }
1.488     albertel 12213: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12214: 					     \%metathesekeys);
                   12215: 	    }
                   12216: 	}
1.338     www      12217: # are there custom rights to evaluate
1.599     albertel 12218: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12219: 
1.338     www      12220:     #
                   12221:     # Importing a rights file here
1.339     albertel 12222:     #
                   12223: 	    unless ($depthcount) {
1.599     albertel 12224: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12225: 		my $dir=$filename;
                   12226: 		$dir=~s|[^/]*$||;
                   12227: 		$location=&filelocation($dir,$location);
1.736     albertel 12228: 		my $rights_metadata =
1.1362    raeburn  12229: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12230: 			      $depthcount+1);
                   12231: 		foreach my $rights (split(',',$rights_metadata)) {
                   12232: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12233: 		    $metathesekeys{$rights}=1;
1.339     albertel 12234: 		}
                   12235: 	    }
                   12236: 	}
1.737     albertel 12237: 	# uniqifiy package listing
                   12238: 	my %seen;
                   12239: 	my @uniq_packages =
                   12240: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12241: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12242: 
1.1369    raeburn  12243:         if (($importedresponses) || ($importedparts)) {
                   12244:             if ($importedparts) {
1.1070    www      12245: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12246:                 $metaentry{':partorder'}='';
                   12247:                 $metathesekeys{'partorder'}=1;
                   12248:             }
                   12249:             if ($importedresponses) {
                   12250: # We had imported responses and need to rebuil responseorder
                   12251:                 $metaentry{':responseorder'}='';
                   12252:                 $metathesekeys{'responseorder'}=1;
                   12253:             }
                   12254:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12255:                 my $origid = $origfiletagids[$index+1];
                   12256:                 if ($origfiletagids[$index] eq 'part') {
                   12257: # Original part, part of the problem
                   12258:                     if ($importedparts) {
                   12259:                         $metaentry{':partorder'}.=','.$origid;
                   12260:                     }
                   12261:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12262:                     if ($importedparts) {
                   12263: # We have imported parts at this position
1.1373    raeburn  12264:                         if ($importedpartids{$origid} ne '') {
                   12265:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12266:                         }
1.1369    raeburn  12267:                     }
                   12268:                     if ($importedresponses) {
                   12269: # We have imported responses at this position
1.1373    raeburn  12270:                         if ($importedrespids{$origid} ne '') {
                   12271:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12272:                         }
                   12273:                     }
                   12274:                 } else {
                   12275: # Original response item, part of the problem
                   12276:                     if ($importedresponses) {
                   12277:                         $metaentry{':responseorder'}.=','.$origid;
                   12278:                     }
                   12279:                 }
                   12280:             }
                   12281:             if ($importedparts) {
                   12282:                 $metaentry{':partorder'}=~s/^\,//;
                   12283:             }
                   12284:             if ($importedresponses) {
                   12285:                 $metaentry{':responseorder'}=~s/^\,//;
                   12286:             }
1.1070    www      12287:         }
1.737     albertel 12288: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12289: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12290: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12291:         unless ($liburi) {
                   12292: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12293:         }
1.177     www      12294: # this is the end of "was not already recently cached
1.71      www      12295:     }
1.599     albertel 12296:     return $metaentry{':'.$what};
1.261     albertel 12297: }
                   12298: 
1.488     albertel 12299: sub metadata_create_package_def {
1.483     albertel 12300:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12301:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12302:     if ($subp eq 'default') { next; }
                   12303:     
1.599     albertel 12304:     if (defined($metaentry{':packages'})) {
                   12305: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12306:     } else {
1.599     albertel 12307: 	$metaentry{':packages'}=$package;
1.483     albertel 12308:     }
                   12309:     my $value=$packagetab{$key};
                   12310:     my $unikey;
                   12311:     $unikey='parameter_0_'.$name;
1.599     albertel 12312:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12313:     $$metathesekeys{$unikey}=1;
1.599     albertel 12314:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12315: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12316:     }
1.599     albertel 12317:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12318: 	$metaentry{':'.$unikey}=
                   12319: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12320:     }
                   12321: }
                   12322: 
1.261     albertel 12323: sub metadata_generate_part0 {
                   12324:     my ($metadata,$metacache,$uri) = @_;
                   12325:     my %allnames;
1.737     albertel 12326:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12327: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12328: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12329: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12330: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12331: 	    $allnames{$name}=$part;
                   12332: 	  }
                   12333: 	}
                   12334:     }
                   12335:     foreach my $name (keys(%allnames)) {
                   12336:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12337:       my $key=":parameter_0_$name";
1.261     albertel 12338:       $$metacache{"$key.part"}='0';
                   12339:       $$metacache{"$key.name"}=$name;
1.428     albertel 12340:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12341: 					   $allnames{$name}.'_'.$name.
                   12342: 					   '.type'};
1.428     albertel 12343:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12344: 			     '.display'};
1.644     www      12345:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12346:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12347:       $$metacache{"$key.display"}=$olddis;
                   12348:     }
1.71      www      12349: }
                   12350: 
1.764     albertel 12351: # ------------------------------------------------------ Devalidate title cache
                   12352: 
                   12353: sub devalidate_title_cache {
                   12354:     my ($url)=@_;
                   12355:     if (!$env{'request.course.id'}) { return; }
                   12356:     my $symb=&symbread($url);
                   12357:     if (!$symb) { return; }
                   12358:     my $key=$env{'request.course.id'}."\0".$symb;
                   12359:     &devalidate_cache_new('title',$key);
                   12360: }
                   12361: 
1.1014    droeschl 12362: # ------------------------------------------------- Get the title of a course
                   12363: 
                   12364: sub current_course_title {
                   12365:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12366: }
1.301     www      12367: # ------------------------------------------------- Get the title of a resource
                   12368: 
                   12369: sub gettitle {
                   12370:     my $urlsymb=shift;
                   12371:     my $symb=&symbread($urlsymb);
1.534     albertel 12372:     if ($symb) {
1.620     albertel 12373: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12374: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12375: 	if (defined($cached)) { 
                   12376: 	    return $result;
                   12377: 	}
1.534     albertel 12378: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12379: 	my $title='';
1.907     albertel 12380: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12381: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12382: 	} else {
                   12383: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12384: 		    &GDBM_READER(),0640)) {
                   12385: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12386: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12387: 		untie(%bighash);
                   12388: 	    }
1.534     albertel 12389: 	}
                   12390: 	$title=~s/\&colon\;/\:/gs;
                   12391: 	if ($title) {
1.1159    www      12392: # Remember both $symb and $title for dynamic metadata
                   12393:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12394:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12395: # Cache this title and then return it
1.599     albertel 12396: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12397: 	}
                   12398: 	$urlsymb=$url;
                   12399:     }
                   12400:     my $title=&metadata($urlsymb,'title');
                   12401:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12402:     return $title;
1.301     www      12403: }
1.613     albertel 12404: 
1.614     albertel 12405: sub get_slot {
                   12406:     my ($which,$cnum,$cdom)=@_;
                   12407:     if (!$cnum || !$cdom) {
1.790     albertel 12408: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12409: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12410: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12411:     }
1.703     albertel 12412:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12413:     my %slotinfo;
                   12414:     if (exists($remembered{$key})) {
                   12415: 	$slotinfo{$which} = $remembered{$key};
                   12416:     } else {
                   12417: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12418: 	&Apache::lonhomework::showhash(%slotinfo);
                   12419: 	my ($tmp)=keys(%slotinfo);
                   12420: 	if ($tmp=~/^error:/) { return (); }
                   12421: 	$remembered{$key} = $slotinfo{$which};
                   12422:     }
1.616     albertel 12423:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12424: 	return %{$slotinfo{$which}};
                   12425:     }
                   12426:     return $slotinfo{$which};
1.614     albertel 12427: }
1.1150    raeburn  12428: 
                   12429: sub get_reservable_slots {
                   12430:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12431:     my $now = time;
                   12432:     my $reservable_info;
                   12433:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12434:     if (exists($remembered{$key})) {
                   12435:         $reservable_info = $remembered{$key};
                   12436:     } else {
                   12437:         my %resv;
                   12438:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12439:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12440:         $reservable_info = \%resv;
                   12441:         $remembered{$key} = $reservable_info;
                   12442:     }
                   12443:     return $reservable_info;
                   12444: }
                   12445: 
                   12446: sub get_course_slots {
                   12447:     my ($cnum,$cdom) = @_;
                   12448:     my $hashid=$cnum.':'.$cdom;
                   12449:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12450:     if (defined($cached)) {
                   12451:         if (ref($result) eq 'HASH') {
                   12452:             return %{$result};
                   12453:         }
                   12454:     } else {
                   12455:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12456:         my ($tmp) = keys(%slots);
                   12457:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12458:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12459:             return %slots;
                   12460:         }
                   12461:     }
                   12462:     return;
                   12463: }
                   12464: 
                   12465: sub devalidate_slots_cache {
                   12466:     my ($cnum,$cdom)=@_;
                   12467:     my $hashid=$cnum.':'.$cdom;
                   12468:     &devalidate_cache_new('allslots',$hashid);
                   12469: }
                   12470: 
1.1181    raeburn  12471: sub get_coursechange {
                   12472:     my ($cdom,$cnum) = @_;
                   12473:     if ($cdom eq '' || $cnum eq '') {
                   12474:         return unless ($env{'request.course.id'});
                   12475:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12476:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12477:     }
                   12478:     my $hashid=$cdom.'_'.$cnum;
                   12479:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12480:     if ((defined($cached)) && ($change ne '')) {
                   12481:         return $change;
                   12482:     } else {
                   12483:         my %crshash;
                   12484:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12485:         if ($crshash{'internal.contentchange'} eq '') {
                   12486:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12487:             if ($change eq '') {
                   12488:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12489:                 $change = $crshash{'internal.created'};
                   12490:             }
                   12491:         } else {
                   12492:             $change = $crshash{'internal.contentchange'};
                   12493:         }
                   12494:         my $cachetime = 600;
                   12495:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12496:     }
                   12497:     return $change;
                   12498: }
                   12499: 
                   12500: sub devalidate_coursechange_cache {
                   12501:     my ($cnum,$cdom)=@_;
                   12502:     my $hashid=$cnum.':'.$cdom;
                   12503:     &devalidate_cache_new('crschange',$hashid);
                   12504: }
                   12505: 
1.31      www      12506: # ------------------------------------------------- Update symbolic store links
                   12507: 
                   12508: sub symblist {
                   12509:     my ($mapname,%newhash)=@_;
1.438     www      12510:     $mapname=&deversion(&declutter($mapname));
1.31      www      12511:     my %hash;
1.620     albertel 12512:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12513:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12514:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12515: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12516: 		next if ($url eq 'last_known'
                   12517: 			 && $env{'form.no_update_last_known'});
                   12518: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12519: 						    $newhash{$url}->[1],
                   12520: 						    $newhash{$url}->[0]);
1.191     harris41 12521:             }
1.31      www      12522:             if (untie(%hash)) {
                   12523: 		return 'ok';
                   12524:             }
                   12525:         }
                   12526:     }
                   12527:     return 'error';
1.212     www      12528: }
                   12529: 
                   12530: # --------------------------------------------------------------- Verify a symb
                   12531: 
                   12532: sub symbverify {
1.1190    raeburn  12533:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12534:     my $thisfn=$thisurl;
1.439     www      12535:     $thisfn=&declutter($thisfn);
1.215     www      12536: # direct jump to resource in page or to a sequence - will construct own symbs
                   12537:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12538: # check URL part
1.409     www      12539:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12540: 
1.431     www      12541:     unless ($url eq $thisfn) { return 0; }
1.213     www      12542: 
1.216     www      12543:     $symb=&symbclean($symb);
1.510     www      12544:     $thisurl=&deversion($thisurl);
1.439     www      12545:     $thisfn=&deversion($thisfn);
1.213     www      12546: 
                   12547:     my %bighash;
                   12548:     my $okay=0;
1.431     www      12549: 
1.620     albertel 12550:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12551:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12552:         my $noclutter;
1.1032    raeburn  12553:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12554:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12555:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12556:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12557:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12558:                 $noclutter = 1;
                   12559:             }
                   12560:         }
                   12561:         my $ids;
                   12562:         if ($noclutter) {
                   12563:             $ids=$bighash{'ids_'.$thisurl};
                   12564:         } else {
                   12565:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12566:         }
1.1102    raeburn  12567:         unless ($ids) {
                   12568:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12569:             $ids=$bighash{$idkey};
1.216     www      12570:         }
                   12571:         if ($ids) {
                   12572: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12573:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12574:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12575:             }
1.800     albertel 12576: 	    foreach my $id (split(/\,/,$ids)) {
                   12577: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12578:                if (
                   12579:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12580:    eq $symb) {
                   12581:                    if (ref($encstate)) {
                   12582:                        $$encstate = $bighash{'encrypted_'.$id};
                   12583:                    }
1.620     albertel 12584: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12585: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12586:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12587: 		       $okay=1;
1.1202    raeburn  12588:                        last;
1.582     albertel 12589: 		   }
                   12590: 	       }
1.216     www      12591: 	   }
                   12592:         }
1.213     www      12593: 	untie(%bighash);
                   12594:     }
                   12595:     return $okay;
1.31      www      12596: }
                   12597: 
1.210     www      12598: # --------------------------------------------------------------- Clean-up symb
                   12599: 
                   12600: sub symbclean {
                   12601:     my $symb=shift;
1.568     albertel 12602:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12603: # remove version from map
                   12604:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12605: 
1.210     www      12606: # remove version from URL
                   12607:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12608: 
1.507     www      12609: # remove wrapper
                   12610: 
1.510     www      12611:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12612:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12613:     return $symb;
1.409     www      12614: }
                   12615: 
                   12616: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12617: 
                   12618: sub encode_symb {
                   12619:     my ($map,$resid,$url)=@_;
                   12620:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12621: }
1.409     www      12622: 
                   12623: sub decode_symb {
1.568     albertel 12624:     my $symb=shift;
                   12625:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12626:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12627:     return (&fixversion($map),$resid,&fixversion($url));
                   12628: }
                   12629: 
                   12630: sub fixversion {
                   12631:     my $fn=shift;
1.609     banghart 12632:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12633:     my %bighash;
                   12634:     my $uri=&clutter($fn);
1.620     albertel 12635:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12636: # is this cached?
1.599     albertel 12637:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12638:     if (defined($cached)) { return $result; }
                   12639: # unfortunately not cached, or expired
1.620     albertel 12640:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12641: 	    &GDBM_READER(),0640)) {
                   12642:  	if ($bighash{'version_'.$uri}) {
                   12643:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12644:  	    unless (($version eq 'mostrecent') || 
                   12645: 		    ($version==&getversion($uri))) {
1.440     www      12646:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12647:  	    }
                   12648:  	}
                   12649:  	untie %bighash;
1.413     www      12650:     }
1.599     albertel 12651:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12652: }
                   12653: 
                   12654: sub deversion {
                   12655:     my $url=shift;
                   12656:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12657:     return $url;
1.210     www      12658: }
                   12659: 
1.31      www      12660: # ------------------------------------------------------ Return symb list entry
                   12661: 
                   12662: sub symbread {
1.1282    raeburn  12663:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12664:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12665:     if (defined($env{$cache_str})) {
                   12666:         if ($ignorecachednull) {
                   12667:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12668:         } else {
                   12669:             return $env{$cache_str};
                   12670:         }
                   12671:     }
1.242     www      12672: # no filename provided? try from environment
1.1265    raeburn  12673:     unless ($thisfn) {
1.620     albertel 12674:         if ($env{'request.symb'}) {
                   12675: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12676: 	}
1.620     albertel 12677: 	$thisfn=$env{'request.filename'};
1.44      www      12678:     }
1.569     albertel 12679:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12680: # is that filename actually a symb? Verify, clean, and return
                   12681:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12682: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12683: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12684: 	}
1.242     www      12685:     }
1.44      www      12686:     $thisfn=declutter($thisfn);
1.31      www      12687:     my %hash;
1.37      www      12688:     my %bighash;
                   12689:     my $syval='';
1.620     albertel 12690:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12691:         my $targetfn = $thisfn;
1.609     banghart 12692:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12693:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12694:         }
1.687     albertel 12695: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12696: 	    $targetfn=$1;
                   12697: 	}
1.620     albertel 12698:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12699:                       &GDBM_READER(),0640)) {
1.481     raeburn  12700: 	    $syval=$hash{$targetfn};
1.37      www      12701:             untie(%hash);
                   12702:         }
                   12703: # ---------------------------------------------------------- There was an entry
                   12704:         if ($syval) {
1.601     albertel 12705: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12706: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12707: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12708: 		    #return $env{$cache_str}='';
1.601     albertel 12709: 		#}    
                   12710: 		#$syval.=$1;
                   12711: 	    #}
1.37      www      12712:         } else {
                   12713: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12714:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12715:                             &GDBM_READER(),0640)) {
1.37      www      12716: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12717:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12718:               unless ($ids) { 
                   12719:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12720:               }
                   12721:               unless ($ids) {
                   12722: # alias?
                   12723: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12724:               }
1.37      www      12725:               if ($ids) {
                   12726: # ------------------------------------------------------------------- Has ID(s)
                   12727:                  my @possibilities=split(/\,/,$ids);
1.39      www      12728:                  if ($#possibilities==0) {
                   12729: # ----------------------------------------------- There is only one possibility
1.37      www      12730: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12731: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12732: 						    $resid,$thisfn);
1.1282    raeburn  12733:                      if (ref($possibles) eq 'HASH') {
                   12734:                          $possibles->{$syval} = 1;    
                   12735:                      }
                   12736:                      if ($checkforblock) {
                   12737:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12738:                          if (@blockers) {
                   12739:                              $syval = '';
                   12740:                              return;
                   12741:                          }
                   12742:                      }
                   12743:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12744: # ------------------------------------------ There is more than one possibility
                   12745:                      my $realpossible=0;
1.800     albertel 12746:                      foreach my $id (@possibilities) {
                   12747: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12748:                          my $canaccess;
                   12749:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12750:                              $canaccess = 1;
                   12751:                          } else { 
                   12752:                              $canaccess = &allowed('bre',$file);
                   12753:                          }
                   12754:                          if ($canaccess) {
                   12755:          		     my ($mapid,$resid)=split(/\./,$id);
                   12756:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12757:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12758: 						             $resid,$thisfn);
                   12759:                                  if (ref($possibles) eq 'HASH') {
                   12760:                                      $possibles->{$syval} = 1;
                   12761:                                  }
                   12762:                                  if ($checkforblock) {
                   12763:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12764:                                      unless (@blockers > 0) {
                   12765:                                          $syval = $poss_syval;
                   12766:                                          $realpossible++;
                   12767:                                      }
                   12768:                                  } else {
                   12769:                                      $syval = $poss_syval;
                   12770:                                      $realpossible++;
                   12771:                                  }
                   12772:                              }
1.39      www      12773: 			 }
1.191     harris41 12774:                      }
1.39      www      12775: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12776:                  } else {
                   12777:                      $syval='';
1.37      www      12778:                  }
                   12779: 	      }
1.1282    raeburn  12780:               untie(%bighash);
1.481     raeburn  12781:            }
1.31      www      12782:         }
1.62      www      12783:         if ($syval) {
1.620     albertel 12784: 	    return $env{$cache_str}=$syval;
1.62      www      12785:         }
1.31      www      12786:     }
1.949     raeburn  12787:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12788:     return $env{$cache_str}='';
1.31      www      12789: }
                   12790: 
                   12791: # ---------------------------------------------------------- Return random seed
                   12792: 
1.32      www      12793: sub numval {
                   12794:     my $txt=shift;
                   12795:     $txt=~tr/A-J/0-9/;
                   12796:     $txt=~tr/a-j/0-9/;
                   12797:     $txt=~tr/K-T/0-9/;
                   12798:     $txt=~tr/k-t/0-9/;
                   12799:     $txt=~tr/U-Z/0-5/;
                   12800:     $txt=~tr/u-z/0-5/;
                   12801:     $txt=~s/\D//g;
1.564     albertel 12802:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12803:     return int($txt);
1.368     albertel 12804: }
                   12805: 
1.484     albertel 12806: sub numval2 {
                   12807:     my $txt=shift;
                   12808:     $txt=~tr/A-J/0-9/;
                   12809:     $txt=~tr/a-j/0-9/;
                   12810:     $txt=~tr/K-T/0-9/;
                   12811:     $txt=~tr/k-t/0-9/;
                   12812:     $txt=~tr/U-Z/0-5/;
                   12813:     $txt=~tr/u-z/0-5/;
                   12814:     $txt=~s/\D//g;
                   12815:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12816:     my $total;
                   12817:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12818:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12819:     return int($total);
                   12820: }
                   12821: 
1.575     albertel 12822: sub numval3 {
                   12823:     use integer;
                   12824:     my $txt=shift;
                   12825:     $txt=~tr/A-J/0-9/;
                   12826:     $txt=~tr/a-j/0-9/;
                   12827:     $txt=~tr/K-T/0-9/;
                   12828:     $txt=~tr/k-t/0-9/;
                   12829:     $txt=~tr/U-Z/0-5/;
                   12830:     $txt=~tr/u-z/0-5/;
                   12831:     $txt=~s/\D//g;
                   12832:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12833:     my $total;
                   12834:     foreach my $val (@txts) { $total+=$val; }
                   12835:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12836:     return $total;
                   12837: }
                   12838: 
1.675     albertel 12839: sub digest {
                   12840:     my ($data)=@_;
                   12841:     my $digest=&Digest::MD5::md5($data);
                   12842:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12843:     my ($e,$f);
                   12844:     {
                   12845:         use integer;
                   12846:         $e=($a+$b);
                   12847:         $f=($c+$d);
                   12848:         if ($_64bit) {
                   12849:             $e=(($e<<32)>>32);
                   12850:             $f=(($f<<32)>>32);
                   12851:         }
                   12852:     }
                   12853:     if (wantarray) {
                   12854: 	return ($e,$f);
                   12855:     } else {
                   12856: 	my $g;
                   12857: 	{
                   12858: 	    use integer;
                   12859: 	    $g=($e+$f);
                   12860: 	    if ($_64bit) {
                   12861: 		$g=(($g<<32)>>32);
                   12862: 	    }
                   12863: 	}
                   12864: 	return $g;
                   12865:     }
                   12866: }
                   12867: 
1.368     albertel 12868: sub latest_rnd_algorithm_id {
1.675     albertel 12869:     return '64bit5';
1.366     albertel 12870: }
1.32      www      12871: 
1.503     albertel 12872: sub get_rand_alg {
                   12873:     my ($courseid)=@_;
1.790     albertel 12874:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12875:     if ($courseid) {
1.620     albertel 12876: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12877:     }
                   12878:     return &latest_rnd_algorithm_id();
                   12879: }
                   12880: 
1.562     albertel 12881: sub validCODE {
                   12882:     my ($CODE)=@_;
                   12883:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12884:     return 0;
                   12885: }
                   12886: 
1.491     albertel 12887: sub getCODE {
1.620     albertel 12888:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12889:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12890: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12891: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12892: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12893:     }
                   12894:     return undef;
                   12895: }
1.1133    foxr     12896: #
                   12897: #  Determines the random seed for a specific context:
                   12898: #
                   12899: # parameters:
                   12900: #   symb      - in course context the symb for the seed.
                   12901: #   course_id - The course id of the form domain_coursenum.
                   12902: #   domain    - Domain for the user.
                   12903: #   course    - Course for the user.
                   12904: #   cenv      - environment of the course.
                   12905: #
                   12906: # NOTE:
                   12907: #   All parameters are picked out of the environment if missing
                   12908: #   or not defined.
                   12909: #   If a symb cannot be determined the current time is used instead.
                   12910: #
                   12911: #  For a given well defined symb, courside, domain, username,
                   12912: #  and course environment, the seed is reproducible.
                   12913: #
1.31      www      12914: sub rndseed {
1.1133    foxr     12915:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12916:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12917:     if (!defined($symb)) {
1.366     albertel 12918: 	unless ($symb=$wsymb) { return time; }
                   12919:     }
1.1146    foxr     12920:     if (!defined $courseid) { 
                   12921: 	$courseid=$wcourseid; 
                   12922:     }
                   12923:     if (!defined $domain) { $domain=$wdomain; }
                   12924:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12925: 
                   12926:     my $which;
                   12927:     if (defined($cenv->{'rndseed'})) {
                   12928: 	$which = $cenv->{'rndseed'};
                   12929:     } else {
                   12930: 	$which =&get_rand_alg($courseid);
                   12931:     }
1.491     albertel 12932:     if (defined(&getCODE())) {
1.1133    foxr     12933: 
1.675     albertel 12934: 	if ($which eq '64bit5') {
                   12935: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12936: 	} elsif ($which eq '64bit4') {
1.575     albertel 12937: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12938: 	} else {
                   12939: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12940: 	}
1.675     albertel 12941:     } elsif ($which eq '64bit5') {
                   12942: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12943:     } elsif ($which eq '64bit4') {
                   12944: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12945:     } elsif ($which eq '64bit3') {
                   12946: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12947:     } elsif ($which eq '64bit2') {
                   12948: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12949:     } elsif ($which eq '64bit') {
                   12950: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12951:     }
                   12952:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12953: }
                   12954: 
                   12955: sub rndseed_32bit {
                   12956:     my ($symb,$courseid,$domain,$username)=@_;
                   12957:     {
                   12958: 	use integer;
                   12959: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12960: 	my $symbseed=numval($symb) << 22;
                   12961: 	my $namechck=unpack("%32C*",$username) << 17;
                   12962: 	my $nameseed=numval($username) << 12;
                   12963: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12964: 	my $courseseed=unpack("%32C*",$courseid);
                   12965: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12966: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12967: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12968: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12969: 	return $num;
                   12970:     }
                   12971: }
                   12972: 
                   12973: sub rndseed_64bit {
                   12974:     my ($symb,$courseid,$domain,$username)=@_;
                   12975:     {
                   12976: 	use integer;
                   12977: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12978: 	my $symbseed=numval($symb) << 10;
                   12979: 	my $namechck=unpack("%32S*",$username);
                   12980: 	
                   12981: 	my $nameseed=numval($username) << 21;
                   12982: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12983: 	my $courseseed=unpack("%32S*",$courseid);
                   12984: 	
                   12985: 	my $num1=$symbchck+$symbseed+$namechck;
                   12986: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12987: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12988: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12989: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12990: 	return "$num1,$num2";
1.155     albertel 12991:     }
1.366     albertel 12992: }
                   12993: 
1.443     albertel 12994: sub rndseed_64bit2 {
                   12995:     my ($symb,$courseid,$domain,$username)=@_;
                   12996:     {
                   12997: 	use integer;
                   12998: 	# strings need to be an even # of cahracters long, it it is odd the
                   12999:         # last characters gets thrown away
                   13000: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13001: 	my $symbseed=numval($symb) << 10;
                   13002: 	my $namechck=unpack("%32S*",$username.' ');
                   13003: 	
                   13004: 	my $nameseed=numval($username) << 21;
1.501     albertel 13005: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13006: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13007: 	
                   13008: 	my $num1=$symbchck+$symbseed+$namechck;
                   13009: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13010: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13011: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13012: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13013: 	return "$num1,$num2";
                   13014:     }
                   13015: }
                   13016: 
                   13017: sub rndseed_64bit3 {
                   13018:     my ($symb,$courseid,$domain,$username)=@_;
                   13019:     {
                   13020: 	use integer;
                   13021: 	# strings need to be an even # of cahracters long, it it is odd the
                   13022:         # last characters gets thrown away
                   13023: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13024: 	my $symbseed=numval2($symb) << 10;
                   13025: 	my $namechck=unpack("%32S*",$username.' ');
                   13026: 	
                   13027: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13028: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13029: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13030: 	
                   13031: 	my $num1=$symbchck+$symbseed+$namechck;
                   13032: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13033: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13034: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13035: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13036: 	
1.503     albertel 13037: 	return "$num1:$num2";
1.443     albertel 13038:     }
                   13039: }
                   13040: 
1.575     albertel 13041: sub rndseed_64bit4 {
                   13042:     my ($symb,$courseid,$domain,$username)=@_;
                   13043:     {
                   13044: 	use integer;
                   13045: 	# strings need to be an even # of cahracters long, it it is odd the
                   13046:         # last characters gets thrown away
                   13047: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13048: 	my $symbseed=numval3($symb) << 10;
                   13049: 	my $namechck=unpack("%32S*",$username.' ');
                   13050: 	
                   13051: 	my $nameseed=numval3($username) << 21;
                   13052: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13053: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13054: 	
                   13055: 	my $num1=$symbchck+$symbseed+$namechck;
                   13056: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13057: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13058: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13059: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13060: 	
1.575     albertel 13061: 	return "$num1:$num2";
                   13062:     }
                   13063: }
                   13064: 
1.675     albertel 13065: sub rndseed_64bit5 {
                   13066:     my ($symb,$courseid,$domain,$username)=@_;
                   13067:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13068:     return "$num1:$num2";
                   13069: }
                   13070: 
1.366     albertel 13071: sub rndseed_CODE_64bit {
                   13072:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13073:     {
1.366     albertel 13074: 	use integer;
1.443     albertel 13075: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13076: 	my $symbseed=numval2($symb);
1.491     albertel 13077: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13078: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13079: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13080: 	my $num1=$symbseed+$CODEchck;
                   13081: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13082: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13083: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13084: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13085: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13086: 	return "$num1:$num2";
1.366     albertel 13087:     }
                   13088: }
                   13089: 
1.575     albertel 13090: sub rndseed_CODE_64bit4 {
                   13091:     my ($symb,$courseid,$domain,$username)=@_;
                   13092:     {
                   13093: 	use integer;
                   13094: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13095: 	my $symbseed=numval3($symb);
                   13096: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13097: 	my $CODEseed=numval3(&getCODE());
                   13098: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13099: 	my $num1=$symbseed+$CODEchck;
                   13100: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13101: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13102: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13103: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13104: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13105: 	return "$num1:$num2";
                   13106:     }
                   13107: }
                   13108: 
1.675     albertel 13109: sub rndseed_CODE_64bit5 {
                   13110:     my ($symb,$courseid,$domain,$username)=@_;
                   13111:     my $code = &getCODE();
                   13112:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13113:     return "$num1:$num2";
                   13114: }
                   13115: 
1.366     albertel 13116: sub setup_random_from_rndseed {
                   13117:     my ($rndseed)=@_;
1.503     albertel 13118:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13119:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13120:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13121:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13122:         } else {
                   13123:             &Math::Random::random_set_seed($num1,$num2);
                   13124:         }
1.366     albertel 13125:     } else {
                   13126: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13127:     }
1.36      albertel 13128: }
                   13129: 
1.474     albertel 13130: sub latest_receipt_algorithm_id {
1.835     albertel 13131:     return 'receipt3';
1.474     albertel 13132: }
                   13133: 
1.480     www      13134: sub recunique {
                   13135:     my $fucourseid=shift;
                   13136:     my $unique;
1.835     albertel 13137:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13138: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13139: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13140:     } else {
                   13141: 	$unique=$perlvar{'lonReceipt'};
                   13142:     }
                   13143:     return unpack("%32C*",$unique);
                   13144: }
                   13145: 
                   13146: sub recprefix {
                   13147:     my $fucourseid=shift;
                   13148:     my $prefix;
1.835     albertel 13149:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13150: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13151: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13152:     } else {
                   13153: 	$prefix=$perlvar{'lonHostID'};
                   13154:     }
                   13155:     return unpack("%32C*",$prefix);
                   13156: }
                   13157: 
1.76      www      13158: sub ireceipt {
1.474     albertel 13159:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13160: 
                   13161:     my $return =&recprefix($fucourseid).'-';
                   13162: 
                   13163:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13164: 	$env{'request.state'} eq 'construct') {
                   13165: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13166: 	return $return;
                   13167:     }
                   13168: 
1.76      www      13169:     my $cuname=unpack("%32C*",$funame);
                   13170:     my $cudom=unpack("%32C*",$fudom);
                   13171:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13172:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13173:     my $cunique=&recunique($fucourseid);
1.474     albertel 13174:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13175:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13176: 
1.790     albertel 13177: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13178: 			       
                   13179: 	$return.= ($cunique%$cuname+
                   13180: 		   $cunique%$cudom+
                   13181: 		   $cusymb%$cuname+
                   13182: 		   $cusymb%$cudom+
                   13183: 		   $cucourseid%$cuname+
                   13184: 		   $cucourseid%$cudom+
                   13185: 		   $cpart%$cuname+
                   13186: 		   $cpart%$cudom);
                   13187:     } else {
                   13188: 	$return.= ($cunique%$cuname+
                   13189: 		   $cunique%$cudom+
                   13190: 		   $cusymb%$cuname+
                   13191: 		   $cusymb%$cudom+
                   13192: 		   $cucourseid%$cuname+
                   13193: 		   $cucourseid%$cudom);
                   13194:     }
                   13195:     return $return;
1.76      www      13196: }
                   13197: 
                   13198: sub receipt {
1.474     albertel 13199:     my ($part)=@_;
1.790     albertel 13200:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13201:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13202: }
1.260     ng       13203: 
1.790     albertel 13204: sub whichuser {
                   13205:     my ($passedsymb)=@_;
                   13206:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13207:     if (defined($env{'form.grade_symb'})) {
                   13208: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13209: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13210: 	if (!$allowed &&
                   13211: 	    exists($env{'request.course.sec'}) &&
                   13212: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13213: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13214: 			      '/'.$env{'request.course.sec'});
                   13215: 	}
                   13216: 	if ($allowed) {
                   13217: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13218: 	    $courseid=$tmp_courseid;
                   13219: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13220: 	    ($name)=&get_env_multiple('form.grade_username');
                   13221: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13222: 	}
                   13223:     }
                   13224:     if (!$passedsymb) {
                   13225: 	$symb=&symbread();
                   13226:     } else {
                   13227: 	$symb=$passedsymb;
                   13228:     }
                   13229:     $courseid=$env{'request.course.id'};
                   13230:     $domain=$env{'user.domain'};
                   13231:     $name=$env{'user.name'};
                   13232:     if ($name eq 'public' && $domain eq 'public') {
                   13233: 	if (!defined($env{'form.username'})) {
                   13234: 	    $env{'form.username'}.=time.rand(10000000);
                   13235: 	}
                   13236: 	$name.=$env{'form.username'};
                   13237:     }
                   13238:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13239: 
                   13240: }
                   13241: 
1.36      albertel 13242: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13243: # returns either the contents of the file or 
                   13244: # -1 if the file doesn't exist
1.481     raeburn  13245: #
                   13246: # if the target is a file that was uploaded via DOCS, 
                   13247: # a check will be made to see if a current copy exists on the local server,
                   13248: # if it does this will be served, otherwise a copy will be retrieved from
                   13249: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13250: # the local server.   
1.472     albertel 13251: 
1.36      albertel 13252: sub getfile {
1.538     albertel 13253:     my ($file) = @_;
1.609     banghart 13254:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13255:     &repcopy($file);
                   13256:     return &readfile($file);
                   13257: }
                   13258: 
                   13259: sub repcopy_userfile {
                   13260:     my ($file)=@_;
1.1142    raeburn  13261:     my $londocroot = $perlvar{'lonDocRoot'};
                   13262:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13263:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13264:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13265: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13266:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13267:     if (-e "$file") {
1.828     www      13268: # we already have a local copy, check it out
1.538     albertel 13269: 	my @fileinfo = stat($file);
1.828     www      13270: 	my $rtncode;
                   13271: 	my $info;
1.538     albertel 13272: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13273: 	if ($lwpresp ne 'ok') {
1.828     www      13274: # there is no such file anymore, even though we had a local copy
1.482     albertel 13275: 	    if ($rtncode eq '404') {
1.538     albertel 13276: 		unlink($file);
1.482     albertel 13277: 	    }
                   13278: 	    return -1;
                   13279: 	}
                   13280: 	if ($info < $fileinfo[9]) {
1.828     www      13281: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13282: 	    return 'ok';
1.828     www      13283: 	} else {
                   13284: # the file is outdated, get rid of it
                   13285: 	    unlink($file);
1.482     albertel 13286: 	}
1.828     www      13287:     }
                   13288: # one way or the other, at this point, we don't have the file
                   13289: # construct the correct path for the file
                   13290:     my @parts = ($cdom,$cnum); 
                   13291:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13292: 	push @parts, split(/\//,$1);
                   13293:     }
                   13294:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13295:     foreach my $part (@parts) {
                   13296: 	$path .= '/'.$part;
                   13297: 	if (!-e $path) {
                   13298: 	    mkdir($path,0770);
1.482     albertel 13299: 	}
                   13300:     }
1.828     www      13301: # now the path exists for sure
                   13302: # get a user agent
                   13303:     my $transferfile=$file.'.in.transfer';
                   13304: # FIXME: this should flock
                   13305:     if (-e $transferfile) { return 'ok'; }
                   13306:     my $request;
                   13307:     $uri=~s/^\///;
1.980     raeburn  13308:     my $homeserver = &homeserver($cnum,$cdom);
                   13309:     my $protocol = $protocol{$homeserver};
                   13310:     $protocol = 'http' if ($protocol ne 'https');
                   13311:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13312:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13313: # did it work?
                   13314:     if ($response->is_error()) {
                   13315: 	unlink($transferfile);
                   13316: 	&logthis("Userfile repcopy failed for $uri");
                   13317: 	return -1;
                   13318:     }
                   13319: # worked, rename the transfer file
                   13320:     rename($transferfile,$file);
1.607     raeburn  13321:     return 'ok';
1.481     raeburn  13322: }
                   13323: 
1.517     albertel 13324: sub tokenwrapper {
                   13325:     my $uri=shift;
1.980     raeburn  13326:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13327:     $uri=~s|^/||;
1.620     albertel 13328:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13329:     my $token=$1;
1.552     albertel 13330:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13331:     if ($udom && $uname && $file) {
                   13332: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13333:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13334:         my $homeserver = &homeserver($uname,$udom);
                   13335:         my $protocol = $protocol{$homeserver};
                   13336:         $protocol = 'http' if ($protocol ne 'https');
                   13337:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13338:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13339:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13340:     } else {
                   13341:         return '/adm/notfound.html';
                   13342:     }
                   13343: }
                   13344: 
1.828     www      13345: # call with reqtype HEAD: get last modification time
                   13346: # call with reqtype GET: get the file contents
                   13347: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13348: #
1.481     raeburn  13349: sub getuploaded {
                   13350:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13351:     $uri=~s/^\///;
1.980     raeburn  13352:     my $homeserver = &homeserver($cnum,$cdom);
                   13353:     my $protocol = $protocol{$homeserver};
                   13354:     $protocol = 'http' if ($protocol ne 'https');
                   13355:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13356:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13357:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13358:     $$rtncode = $response->code;
1.482     albertel 13359:     if (! $response->is_success()) {
                   13360: 	return 'failed';
                   13361:     }      
                   13362:     if ($reqtype eq 'HEAD') {
1.486     www      13363: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13364:     } elsif ($reqtype eq 'GET') {
                   13365: 	$$info = $response->content;
1.472     albertel 13366:     }
1.482     albertel 13367:     return 'ok';
1.36      albertel 13368: }
                   13369: 
1.481     raeburn  13370: sub readfile {
                   13371:     my $file = shift;
                   13372:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13373:     my $fh;
1.1359    raeburn  13374:     open($fh,"<",$file);
1.481     raeburn  13375:     my $a='';
1.800     albertel 13376:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13377:     return $a;
                   13378: }
                   13379: 
1.36      albertel 13380: sub filelocation {
1.590     banghart 13381:     my ($dir,$file) = @_;
                   13382:     my $location;
                   13383:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13384: 
                   13385:     if ($file =~ m-^/adm/-) {
                   13386: 	$file=~s-^/adm/wrapper/-/-;
                   13387: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13388:     }
1.882     albertel 13389: 
1.1139    www      13390:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13391:         $location = $file;
1.609     banghart 13392:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13393:         my ($udom,$uname,$filename)=
1.811     albertel 13394:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13395:         my $home=&homeserver($uname,$udom);
                   13396:         my $is_me=0;
                   13397:         my @ids=&current_machine_ids();
                   13398:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13399:         if ($is_me) {
1.1117    foxr     13400:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13401:         } else {
                   13402:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13403:   	      $udom.'/'.$uname.'/'.$filename;
                   13404:         }
1.882     albertel 13405:     } elsif ($file =~ m-^/adm/-) {
                   13406: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13407:     } else {
                   13408:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13409:         $file=~s:^/(res|priv)/:/:;
                   13410:         my $space=$1;
1.590     banghart 13411:         if ( !( $file =~ m:^/:) ) {
                   13412:             $location = $dir. '/'.$file;
                   13413:         } else {
1.1142    raeburn  13414:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13415:         }
1.59      albertel 13416:     }
1.590     banghart 13417:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13418:     while ($location=~m{/\.\./}) {
                   13419: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13420: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13421: 	} else {
                   13422: 	    $location=~ s{/\.\./}{/}g;
                   13423: 	}
                   13424:     } #remove dir/..
1.590     banghart 13425:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13426:     return $location;
1.46      www      13427: }
1.36      albertel 13428: 
1.46      www      13429: sub hreflocation {
                   13430:     my ($dir,$file)=@_;
1.980     raeburn  13431:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13432: 	$file=filelocation($dir,$file);
1.700     albertel 13433:     } elsif ($file=~m-^/adm/-) {
                   13434: 	$file=~s-^/adm/wrapper/-/-;
                   13435: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13436:     }
                   13437:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13438: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13439:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13440: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13441: 	        {/uploaded/$1/$2/}x;
1.46      www      13442:     }
1.913     albertel 13443:     if ($file=~ m{^/userfiles/}) {
                   13444: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13445:     }
1.462     albertel 13446:     return $file;
1.465     albertel 13447: }
                   13448: 
1.1139    www      13449: 
                   13450: 
                   13451: 
                   13452: 
1.465     albertel 13453: sub current_machine_domains {
1.853     albertel 13454:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13455: }
                   13456: 
                   13457: sub machine_domains {
                   13458:     my ($hostname) = @_;
1.465     albertel 13459:     my @domains;
1.838     albertel 13460:     my %hostname = &all_hostnames();
1.465     albertel 13461:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13462: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13463: 	if ($hostname eq $name) {
1.844     albertel 13464: 	    push(@domains,&host_domain($id));
1.465     albertel 13465: 	}
                   13466:     }
                   13467:     return @domains;
                   13468: }
                   13469: 
                   13470: sub current_machine_ids {
1.853     albertel 13471:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13472: }
                   13473: 
                   13474: sub machine_ids {
                   13475:     my ($hostname) = @_;
                   13476:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13477:     my @ids;
1.888     albertel 13478:     my %name_to_host = &all_names();
1.889     albertel 13479:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13480: 	return @{ $name_to_host{$hostname} };
                   13481:     }
                   13482:     return;
1.31      www      13483: }
                   13484: 
1.824     raeburn  13485: sub additional_machine_domains {
                   13486:     my @domains;
1.1359    raeburn  13487:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13488:     while( my $line = <$fh>) {
                   13489:         $line =~ s/\s//g;
                   13490:         push(@domains,$line);
                   13491:     }
                   13492:     return @domains;
                   13493: }
                   13494: 
                   13495: sub default_login_domain {
                   13496:     my $domain = $perlvar{'lonDefDomain'};
                   13497:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13498:     foreach my $posdom (&current_machine_domains(),
                   13499:                         &additional_machine_domains()) {
                   13500:         if (lc($posdom) eq lc($testdomain)) {
                   13501:             $domain=$posdom;
                   13502:             last;
                   13503:         }
                   13504:     }
                   13505:     return $domain;
                   13506: }
                   13507: 
1.31      www      13508: # ------------------------------------------------------------- Declutters URLs
                   13509: 
                   13510: sub declutter {
                   13511:     my $thisfn=shift;
1.569     albertel 13512:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13513:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13514:         $thisfn=~s{^/home/httpd/html}{};
                   13515:     }
1.31      www      13516:     $thisfn=~s/^\///;
1.697     albertel 13517:     $thisfn=~s|^adm/wrapper/||;
                   13518:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13519:     $thisfn=~s/^res\///;
1.1172    bisitz   13520:     $thisfn=~s/^priv\///;
1.1032    raeburn  13521:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13522:         $thisfn=~s/\?.+$//;
                   13523:     }
1.268     www      13524:     return $thisfn;
                   13525: }
                   13526: 
                   13527: # ------------------------------------------------------------- Clutter up URLs
                   13528: 
                   13529: sub clutter {
                   13530:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13531:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13532: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13533:        $thisfn='/res'.$thisfn; 
                   13534:     }
1.1031    raeburn  13535:     if ($thisfn !~m|^/adm|) {
                   13536: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13537: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13538: 	} else {
                   13539: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13540: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13541: 	    if ($embstyle eq 'ssi'
                   13542: 		|| ($embstyle eq 'hdn')
                   13543: 		|| ($embstyle eq 'rat')
                   13544: 		|| ($embstyle eq 'prv')
                   13545: 		|| ($embstyle eq 'ign')) {
                   13546: 		#do nothing with these
                   13547: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13548: 		|| ($embstyle eq 'emb')
                   13549: 		|| ($embstyle eq 'wrp')) {
                   13550: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13551: 	    } elsif ($embstyle eq 'unk'
                   13552: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13553: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13554: 	    } else {
1.718     www      13555: #		&logthis("Got a blank emb style");
1.695     albertel 13556: 	    }
1.694     albertel 13557: 	}
1.1343    raeburn  13558:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13559:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13560:     }
1.31      www      13561:     return $thisfn;
1.12      www      13562: }
                   13563: 
1.787     albertel 13564: sub clutter_with_no_wrapper {
                   13565:     my $uri = &clutter(shift);
                   13566:     if ($uri =~ m-^/adm/-) {
                   13567: 	$uri =~ s-^/adm/wrapper/-/-;
                   13568: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13569:     }
                   13570:     return $uri;
                   13571: }
                   13572: 
1.557     albertel 13573: sub freeze_escape {
                   13574:     my ($value)=@_;
                   13575:     if (ref($value)) {
                   13576: 	$value=&nfreeze($value);
                   13577: 	return '__FROZEN__'.&escape($value);
                   13578:     }
                   13579:     return &escape($value);
                   13580: }
                   13581: 
1.11      www      13582: 
1.557     albertel 13583: sub thaw_unescape {
                   13584:     my ($value)=@_;
                   13585:     if ($value =~ /^__FROZEN__/) {
                   13586: 	substr($value,0,10,undef);
                   13587: 	$value=&unescape($value);
                   13588: 	return &thaw($value);
                   13589:     }
                   13590:     return &unescape($value);
                   13591: }
                   13592: 
1.436     albertel 13593: sub correct_line_ends {
                   13594:     my ($result)=@_;
                   13595:     $$result =~s/\r\n/\n/mg;
                   13596:     $$result =~s/\r/\n/mg;
1.415     albertel 13597: }
1.1       albertel 13598: # ================================================================ Main Program
                   13599: 
1.184     www      13600: sub goodbye {
1.204     albertel 13601:    &logthis("Starting Shut down");
1.443     albertel 13602: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13603:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13604: #converted
1.599     albertel 13605: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13606:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13607: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13608: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13609: #1.1 only
1.870     albertel 13610: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13611: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13612: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13613: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13614:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13615:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13616:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13617:    &flushcourselogs();
                   13618:    &logthis("Shutting down");
                   13619: }
                   13620: 
1.852     albertel 13621: sub get_dns {
1.1210    raeburn  13622:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13623:     if (!$ignore_cache) {
                   13624: 	my ($content,$cached)=
                   13625: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13626: 	if ($cached) {
1.1210    raeburn  13627: 	    &$func($content,$hashref);
1.869     albertel 13628: 	    return;
                   13629: 	}
                   13630:     }
                   13631: 
                   13632:     my %alldns;
1.1379    raeburn  13633:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13634:         foreach my $dns (<$config>) {
                   13635: 	    next if ($dns !~ /^\^(\S*)/x);
                   13636:             my $line = $1;
                   13637:             my ($host,$protocol) = split(/:/,$line);
                   13638:             if ($protocol ne 'https') {
                   13639:                 $protocol = 'http';
                   13640:             }
                   13641: 	    $alldns{$host} = $protocol;
1.979     raeburn  13642:         }
1.1379    raeburn  13643:         close($config);
1.869     albertel 13644:     }
                   13645:     while (%alldns) {
1.1263    raeburn  13646: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13647: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13648:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13649:         delete($alldns{$dns});
1.852     albertel 13650: 	next if ($response->is_error());
1.1379    raeburn  13651:         if ($url eq '/adm/dns/loncapaCRL') {
                   13652:             return &$func($response);
                   13653:         } else {
                   13654: 	    my @content = split("\n",$response->content);
                   13655: 	    unless ($nocache) {
                   13656: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   13657: 	    }
                   13658: 	    &$func(\@content,$hashref);
                   13659:             return;
                   13660:         }
                   13661:     }
                   13662:     my $which = (split('/',$url,4))[3];
                   13663:     if ($which eq 'loncapaCRL') {
                   13664:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   13665:         if (-e $diskfile) {
                   13666:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   13667:         } else {
                   13668:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   13669:         }
                   13670:     } else {
                   13671:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13672:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13673:             my @content = <$config>;
                   13674:             close($config);
                   13675:             &$func(\@content,$hashref);
                   13676:         }
1.852     albertel 13677:     }
1.1210    raeburn  13678:     return;
                   13679: }
                   13680: 
                   13681: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13682: sub parse_dns_checksums_tab {
1.1210    raeburn  13683:     my ($lines,$hashref) = @_;
1.1264    raeburn  13684:     my $lonhost = $perlvar{'lonHostID'};
                   13685:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13686:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13687:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13688:     my $webconfdir = '/etc/httpd/conf';
                   13689:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13690:         $webconfdir = '/etc/apache2';
                   13691:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13692:         if ($1 >= 10) {
                   13693:             $webconfdir = '/etc/apache2';
                   13694:         }
                   13695:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13696:         if ($1 >= 10.0) {
                   13697:             $webconfdir = '/etc/apache2';
                   13698:         }
                   13699:     }
1.1210    raeburn  13700:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13701:     my (%chksum,%revnum);
                   13702:     if (ref($lines) eq 'ARRAY') {
                   13703:         chomp(@{$lines});
1.1238    raeburn  13704:         my $version = shift(@{$lines});
                   13705:         if ($version eq $release) {  
1.1210    raeburn  13706:             foreach my $line (@{$lines}) {
1.1238    raeburn  13707:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13708:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13709:                     if ($webconfdir eq '/etc/apache2') {
                   13710:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13711:                     }
                   13712:                 }
1.1238    raeburn  13713:                 $chksum{$file} = $shasum;
                   13714:                 $revnum{$file} = $version;
1.1210    raeburn  13715:             }
                   13716:             if (ref($hashref) eq 'HASH') {
                   13717:                 %{$hashref} = (
                   13718:                                 sums     => \%chksum,
                   13719:                                 versions => \%revnum,
                   13720:                               );
                   13721:             }
                   13722:         }
                   13723:     }
1.869     albertel 13724:     return;
1.852     albertel 13725: }
1.1210    raeburn  13726: 
                   13727: sub fetch_dns_checksums {
1.1238    raeburn  13728:     my %checksums;
                   13729:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13730:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13731:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13732:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13733:              \%checksums);
1.1210    raeburn  13734:     return \%checksums;
                   13735: }
                   13736: 
1.1379    raeburn  13737: sub fetch_crl_pemfile {
                   13738:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   13739: }
                   13740: 
                   13741: sub save_crl_pem {
                   13742:     my ($response) = @_;
1.1380    raeburn  13743:     my ($msg,$hadchanges);
1.1379    raeburn  13744:     if (ref($response)) {
                   13745:         my $now = time;
                   13746:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   13747:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   13748:         if (open(my $fh,'>',"$tmpcrl")) {
                   13749:             print $fh $response->content;
                   13750:             close($fh);
                   13751:             if (-e $lonca) {
                   13752:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   13753:                     my $check = <PIPE>;
                   13754:                     close(PIPE);
                   13755:                     chomp($check);
                   13756:                     if ($check eq 'verify OK') {
                   13757:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  13758:                         my $backup;
1.1379    raeburn  13759:                         if (-e $dest) {
1.1380    raeburn  13760:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   13761:                                 $backup = 'ok';
                   13762:                             }
1.1379    raeburn  13763:                         }
                   13764:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   13765:                             $msg = 'ok';
1.1380    raeburn  13766:                             if ($backup) {
                   13767:                                 my (%oldnums,%newnums);
                   13768:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   13769:                                     while (<PIPE>) {
                   13770:                                         $oldnums{(split(/:/))[1]} = 1;
                   13771:                                     }
                   13772:                                     close(PIPE);
                   13773:                                 }
                   13774:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   13775:                                     while(<PIPE>) {
                   13776:                                         $newnums{(split(/:/))[1]} = 1;
                   13777:                                     }
                   13778:                                     close(PIPE);
                   13779:                                 }
                   13780:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   13781:                                     unless (exists($oldnums{$key})) {
                   13782:                                         $hadchanges = 1;
                   13783:                                         last;
                   13784:                                     }
                   13785:                                 }
                   13786:                                 unless ($hadchanges) {
                   13787:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   13788:                                         unless (exists($newnums{$key})) {
                   13789:                                             $hadchanges = 1;
                   13790:                                             last;
                   13791:                                         }
                   13792:                                     }
                   13793:                                 }
                   13794:                             }
1.1379    raeburn  13795:                         }
                   13796:                     } else {
                   13797:                         unlink($tmpcrl);
                   13798:                     }
                   13799:                 } else {
                   13800:                     unlink($tmpcrl);
                   13801:                 }
                   13802:             } else {
                   13803:                 unlink($tmpcrl);
                   13804:             }
                   13805:         }
                   13806:     }
1.1380    raeburn  13807:     return ($msg,$hadchanges);
1.1379    raeburn  13808: }
                   13809: 
1.327     albertel 13810: # ------------------------------------------------------------ Read domain file
                   13811: {
1.852     albertel 13812:     my $loaded;
1.846     albertel 13813:     my %domain;
                   13814: 
1.852     albertel 13815:     sub parse_domain_tab {
                   13816: 	my ($lines) = @_;
                   13817: 	foreach my $line (@$lines) {
                   13818: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13819: 
1.846     albertel 13820: 	    chomp($line);
1.852     albertel 13821: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13822: 	    my %this_domain;
                   13823: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13824: 			       'lang_def', 'city', 'longi', 'lati',
                   13825: 			       'primary') {
                   13826: 		$this_domain{$field} = shift(@elements);
                   13827: 	    }
                   13828: 	    $domain{$name} = \%this_domain;
1.852     albertel 13829: 	}
                   13830:     }
1.864     albertel 13831: 
                   13832:     sub reset_domain_info {
                   13833: 	undef($loaded);
                   13834: 	undef(%domain);
                   13835:     }
                   13836: 
1.852     albertel 13837:     sub load_domain_tab {
1.1293    raeburn  13838: 	my ($ignore_cache,$nocache) = @_;
                   13839: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13840: 	my $fh;
1.1359    raeburn  13841: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13842: 	    my @lines = <$fh>;
                   13843: 	    &parse_domain_tab(\@lines);
1.448     albertel 13844: 	}
1.852     albertel 13845: 	close($fh);
                   13846: 	$loaded = 1;
1.327     albertel 13847:     }
1.846     albertel 13848: 
                   13849:     sub domain {
1.852     albertel 13850: 	&load_domain_tab() if (!$loaded);
                   13851: 
1.846     albertel 13852: 	my ($name,$what) = @_;
                   13853: 	return if ( !exists($domain{$name}) );
                   13854: 
                   13855: 	if (!$what) {
                   13856: 	    return $domain{$name}{'description'};
                   13857: 	}
                   13858: 	return $domain{$name}{$what};
                   13859:     }
1.974     raeburn  13860: 
                   13861:     sub domain_info {
                   13862:         &load_domain_tab() if (!$loaded);
                   13863:         return %domain;
                   13864:     }
                   13865: 
1.327     albertel 13866: }
                   13867: 
                   13868: 
1.1       albertel 13869: # ------------------------------------------------------------- Read hosts file
                   13870: {
1.838     albertel 13871:     my %hostname;
1.844     albertel 13872:     my %hostdom;
1.845     albertel 13873:     my %libserv;
1.852     albertel 13874:     my $loaded;
1.888     albertel 13875:     my %name_to_host;
1.1074    raeburn  13876:     my %internetdom;
1.1107    raeburn  13877:     my %LC_dns_serv;
1.852     albertel 13878: 
                   13879:     sub parse_hosts_tab {
                   13880: 	my ($file) = @_;
                   13881: 	foreach my $configline (@$file) {
                   13882: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13883:             chomp($configline);
                   13884: 	    if ($configline =~ /^\^/) {
                   13885:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13886:                     $LC_dns_serv{$1} = 1;
                   13887:                 }
                   13888:                 next;
                   13889:             }
1.1074    raeburn  13890: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13891: 	    $name=~s/\s//g;
                   13892: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13893:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13894:                     my $curr = $hostname{$id};
                   13895:                     my $skip;
                   13896:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13897:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13898:                             $skip = 1;
                   13899:                         } else {
                   13900:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13901:                         }
                   13902:                     }
                   13903:                     unless ($skip) {
                   13904:                         push(@{$name_to_host{$name}},$id);
                   13905:                     }
                   13906:                 } else {
                   13907:                     push(@{$name_to_host{$name}},$id);
                   13908:                 }
1.852     albertel 13909: 		$hostname{$id}=$name;
                   13910: 		$hostdom{$id}=$domain;
                   13911: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13912:                 if (defined($protocol)) {
                   13913:                     if ($protocol eq 'https') {
                   13914:                         $protocol{$id} = $protocol;
                   13915:                     } else {
                   13916:                         $protocol{$id} = 'http'; 
                   13917:                     }
1.968     raeburn  13918:                 } else {
1.969     raeburn  13919:                     $protocol{$id} = 'http';
1.968     raeburn  13920:                 }
1.1074    raeburn  13921:                 if (defined($intdom)) {
                   13922:                     $internetdom{$id} = $intdom;
                   13923:                 }
1.852     albertel 13924: 	    }
                   13925: 	}
                   13926:     }
1.864     albertel 13927:     
                   13928:     sub reset_hosts_info {
1.897     albertel 13929: 	&purge_remembered();
1.864     albertel 13930: 	&reset_domain_info();
                   13931: 	&reset_hosts_ip_info();
1.1339    raeburn  13932:         undef(%internetdom);
1.892     albertel 13933: 	undef(%name_to_host);
1.864     albertel 13934: 	undef(%hostname);
                   13935: 	undef(%hostdom);
                   13936: 	undef(%libserv);
                   13937: 	undef($loaded);
                   13938:     }
1.1       albertel 13939: 
1.852     albertel 13940:     sub load_hosts_tab {
1.1293    raeburn  13941: 	my ($ignore_cache,$nocache) = @_;
                   13942: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13943: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13944: 	my @config = <$config>;
                   13945: 	&parse_hosts_tab(\@config);
                   13946: 	close($config);
                   13947: 	$loaded=1;
1.1       albertel 13948:     }
1.852     albertel 13949: 
1.838     albertel 13950:     sub hostname {
1.852     albertel 13951: 	&load_hosts_tab() if (!$loaded);
                   13952: 
1.838     albertel 13953: 	my ($lonid) = @_;
                   13954: 	return $hostname{$lonid};
                   13955:     }
1.845     albertel 13956: 
1.838     albertel 13957:     sub all_hostnames {
1.852     albertel 13958: 	&load_hosts_tab() if (!$loaded);
                   13959: 
1.838     albertel 13960: 	return %hostname;
                   13961:     }
1.845     albertel 13962: 
1.888     albertel 13963:     sub all_names {
1.1293    raeburn  13964:         my ($ignore_cache,$nocache) = @_;
                   13965: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13966: 
                   13967: 	return %name_to_host;
                   13968:     }
                   13969: 
1.974     raeburn  13970:     sub all_host_domain {
                   13971:         &load_hosts_tab() if (!$loaded);
                   13972:         return %hostdom;
                   13973:     }
                   13974: 
1.1339    raeburn  13975:     sub all_host_intdom {
                   13976:         &load_hosts_tab() if (!$loaded);
                   13977:         return %internetdom;
                   13978:     }
                   13979: 
1.845     albertel 13980:     sub is_library {
1.852     albertel 13981: 	&load_hosts_tab() if (!$loaded);
                   13982: 
1.845     albertel 13983: 	return exists($libserv{$_[0]});
                   13984:     }
                   13985: 
                   13986:     sub all_library {
1.852     albertel 13987: 	&load_hosts_tab() if (!$loaded);
                   13988: 
1.845     albertel 13989: 	return %libserv;
                   13990:     }
                   13991: 
1.1062    droeschl 13992:     sub unique_library {
                   13993: 	#2x reverse removes all hostnames that appear more than once
                   13994:         my %unique = reverse &all_library();
                   13995:         return reverse %unique;
                   13996:     }
                   13997: 
1.841     albertel 13998:     sub get_servers {
1.852     albertel 13999: 	&load_hosts_tab() if (!$loaded);
                   14000: 
1.841     albertel 14001: 	my ($domain,$type) = @_;
                   14002: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14003: 	                                          : %hostname;
                   14004: 	my %result;
1.842     albertel 14005: 	if (ref($domain) eq 'ARRAY') {
                   14006: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14007: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14008: 		    $result{$host} = $hostname;
                   14009: 		}
                   14010: 	    }
                   14011: 	} else {
                   14012: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14013: 		if ($hostdom{$host} eq $domain) {
                   14014: 		    $result{$host} = $hostname;
                   14015: 		}
1.841     albertel 14016: 	    }
                   14017: 	}
                   14018: 	return %result;
                   14019:     }
1.845     albertel 14020: 
1.1062    droeschl 14021:     sub get_unique_servers {
                   14022:         my %unique = reverse &get_servers(@_);
                   14023: 	return reverse %unique;
                   14024:     }
                   14025: 
1.844     albertel 14026:     sub host_domain {
1.852     albertel 14027: 	&load_hosts_tab() if (!$loaded);
                   14028: 
1.844     albertel 14029: 	my ($lonid) = @_;
                   14030: 	return $hostdom{$lonid};
                   14031:     }
                   14032: 
1.841     albertel 14033:     sub all_domains {
1.852     albertel 14034: 	&load_hosts_tab() if (!$loaded);
                   14035: 
1.841     albertel 14036: 	my %seen;
                   14037: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14038: 	return @uniq;
                   14039:     }
1.1074    raeburn  14040: 
                   14041:     sub internet_dom {
                   14042:         &load_hosts_tab() if (!$loaded);
                   14043: 
                   14044:         my ($lonid) = @_;
                   14045:         return $internetdom{$lonid};
                   14046:     }
1.1107    raeburn  14047: 
                   14048:     sub is_LC_dns {
                   14049:         &load_hosts_tab() if (!$loaded);
                   14050: 
                   14051:         my ($hostname) = @_;
                   14052:         return exists($LC_dns_serv{$hostname});
                   14053:     }
                   14054: 
1.1       albertel 14055: }
                   14056: 
1.847     albertel 14057: { 
                   14058:     my %iphost;
1.856     albertel 14059:     my %name_to_ip;
                   14060:     my %lonid_to_ip;
1.869     albertel 14061: 
1.847     albertel 14062:     sub get_hosts_from_ip {
                   14063: 	my ($ip) = @_;
                   14064: 	my %iphosts = &get_iphost();
                   14065: 	if (ref($iphosts{$ip})) {
                   14066: 	    return @{$iphosts{$ip}};
                   14067: 	}
                   14068: 	return;
1.839     albertel 14069:     }
1.864     albertel 14070:     
                   14071:     sub reset_hosts_ip_info {
                   14072: 	undef(%iphost);
                   14073: 	undef(%name_to_ip);
                   14074: 	undef(%lonid_to_ip);
                   14075:     }
1.856     albertel 14076: 
                   14077:     sub get_host_ip {
                   14078: 	my ($lonid) = @_;
                   14079: 	if (exists($lonid_to_ip{$lonid})) {
                   14080: 	    return $lonid_to_ip{$lonid};
                   14081: 	}
                   14082: 	my $name=&hostname($lonid);
                   14083:    	my $ip = gethostbyname($name);
                   14084: 	return if (!$ip || length($ip) ne 4);
                   14085: 	$ip=inet_ntoa($ip);
                   14086: 	$name_to_ip{$name}   = $ip;
                   14087: 	$lonid_to_ip{$lonid} = $ip;
                   14088: 	return $ip;
                   14089:     }
1.847     albertel 14090:     
                   14091:     sub get_iphost {
1.1293    raeburn  14092: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14093: 
1.869     albertel 14094: 	if (!$ignore_cache) {
                   14095: 	    if (%iphost) {
                   14096: 		return %iphost;
                   14097: 	    }
                   14098: 	    my ($ip_info,$cached)=
                   14099: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14100: 	    if ($cached) {
                   14101: 		%iphost      = %{$ip_info->[0]};
                   14102: 		%name_to_ip  = %{$ip_info->[1]};
                   14103: 		%lonid_to_ip = %{$ip_info->[2]};
                   14104: 		return %iphost;
                   14105: 	    }
                   14106: 	}
1.894     albertel 14107: 
                   14108: 	# get yesterday's info for fallback
                   14109: 	my %old_name_to_ip;
                   14110: 	my ($ip_info,$cached)=
                   14111: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14112: 	if ($cached) {
                   14113: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14114: 	}
                   14115: 
1.1293    raeburn  14116: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14117: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14118: 	    my $ip;
                   14119: 	    if (!exists($name_to_ip{$name})) {
                   14120: 		$ip = gethostbyname($name);
                   14121: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14122: 		    if (defined($old_name_to_ip{$name})) {
                   14123: 			$ip = $old_name_to_ip{$name};
                   14124: 			&logthis("Can't find $name defaulting to old $ip");
                   14125: 		    } else {
                   14126: 			&logthis("Name $name no IP found");
                   14127: 			next;
                   14128: 		    }
                   14129: 		} else {
                   14130: 		    $ip=inet_ntoa($ip);
1.847     albertel 14131: 		}
                   14132: 		$name_to_ip{$name} = $ip;
                   14133: 	    } else {
                   14134: 		$ip = $name_to_ip{$name};
1.653     albertel 14135: 	    }
1.888     albertel 14136: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14137: 		$lonid_to_ip{$id} = $ip;
                   14138: 	    }
                   14139: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14140: 	}
1.1293    raeburn  14141:         unless ($nocache) {
                   14142: 	    &do_cache_new('iphost','iphost',
                   14143: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14144: 		          48*60*60);
                   14145:         }
1.869     albertel 14146: 
1.847     albertel 14147: 	return %iphost;
1.598     albertel 14148:     }
                   14149: 
1.992     raeburn  14150:     #
                   14151:     #  Given a DNS returns the loncapa host name for that DNS 
                   14152:     # 
                   14153:     sub host_from_dns {
                   14154:         my ($dns) = @_;
                   14155:         my @hosts;
                   14156:         my $ip;
                   14157: 
1.993     raeburn  14158:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14159:             $ip = $name_to_ip{$dns};
                   14160:         }
                   14161:         if (!$ip) {
                   14162:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14163:             if (length($ip) == 4) { 
                   14164: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14165:             }
                   14166:         }
                   14167:         if ($ip) {
                   14168: 	    @hosts = get_hosts_from_ip($ip);
                   14169: 	    return $hosts[0];
                   14170:         }
                   14171:         return undef;
1.986     foxr     14172:     }
1.992     raeburn  14173: 
1.1074    raeburn  14174:     sub get_internet_names {
                   14175:         my ($lonid) = @_;
                   14176:         return if ($lonid eq '');
                   14177:         my ($idnref,$cached)=
                   14178:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14179:         if ($cached) {
                   14180:             return $idnref;
                   14181:         }
                   14182:         my $ip = &get_host_ip($lonid);
                   14183:         my @hosts = &get_hosts_from_ip($ip);
                   14184:         my %iphost = &get_iphost();
                   14185:         my (@idns,%seen);
                   14186:         foreach my $id (@hosts) {
                   14187:             my $dom = &host_domain($id);
                   14188:             my $prim_id = &domain($dom,'primary');
                   14189:             my $prim_ip = &get_host_ip($prim_id);
                   14190:             next if ($seen{$prim_ip});
                   14191:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14192:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14193:                     my $intdom = &internet_dom($id);
                   14194:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14195:                         push(@idns,$intdom);
                   14196:                     }
                   14197:                 }
                   14198:             }
                   14199:             $seen{$prim_ip} = 1;
                   14200:         }
1.1219    raeburn  14201:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14202:     }
                   14203: 
1.986     foxr     14204: }
                   14205: 
1.1079    raeburn  14206: sub all_loncaparevs {
1.1249    raeburn  14207:     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  14208: }
                   14209: 
1.1227    raeburn  14210: # ---------------------------------------------------------- Read loncaparev table
                   14211: {
                   14212:     sub load_loncaparevs { 
                   14213:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14214:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14215:                 while (my $configline=<$config>) {
                   14216:                     chomp($configline);
                   14217:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14218:                     $loncaparevs{$hostid}=$loncaparev;
                   14219:                 }
                   14220:                 close($config);
                   14221:             }
                   14222:         }
                   14223:     }
                   14224: }
                   14225: 
                   14226: # ---------------------------------------------------------- Read serverhostID table
                   14227: {
                   14228:     sub load_serverhomeIDs {
                   14229:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14230:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14231:                 while (my $configline=<$config>) {
                   14232:                     chomp($configline);
                   14233:                     my ($name,$id)=split(/:/,$configline);
                   14234:                     $serverhomeIDs{$name}=$id;
                   14235:                 }
                   14236:                 close($config);
                   14237:             }
                   14238:         }
                   14239:     }
                   14240: }
                   14241: 
                   14242: 
1.862     albertel 14243: BEGIN {
                   14244: 
                   14245: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14246:     unless ($readit) {
                   14247: {
                   14248:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14249:     %perlvar = (%perlvar,%{$configvars});
                   14250: }
                   14251: 
                   14252: 
1.1       albertel 14253: # ------------------------------------------------------ Read spare server file
                   14254: {
1.1359    raeburn  14255:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14256: 
                   14257:     while (my $configline=<$config>) {
                   14258:        chomp($configline);
1.284     matthew  14259:        if ($configline) {
1.784     albertel 14260: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14261: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14262: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14263:        }
                   14264:     }
1.448     albertel 14265:     close($config);
1.1       albertel 14266: }
1.11      www      14267: # ------------------------------------------------------------ Read permissions
                   14268: {
1.1359    raeburn  14269:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14270: 
                   14271:     while (my $configline=<$config>) {
1.448     albertel 14272: 	chomp($configline);
                   14273: 	if ($configline) {
                   14274: 	    my ($role,$perm)=split(/ /,$configline);
                   14275: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14276: 	}
1.11      www      14277:     }
1.448     albertel 14278:     close($config);
1.11      www      14279: }
                   14280: 
                   14281: # -------------------------------------------- Read plain texts for permissions
                   14282: {
1.1359    raeburn  14283:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14284: 
                   14285:     while (my $configline=<$config>) {
1.448     albertel 14286: 	chomp($configline);
                   14287: 	if ($configline) {
1.742     raeburn  14288: 	    my ($short,@plain)=split(/:/,$configline);
                   14289:             %{$prp{$short}} = ();
                   14290: 	    if (@plain > 0) {
                   14291:                 $prp{$short}{'std'} = $plain[0];
                   14292:                 for (my $i=1; $i<@plain; $i++) {
                   14293:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14294:                 }
                   14295:             }
1.448     albertel 14296: 	}
1.135     www      14297:     }
1.448     albertel 14298:     close($config);
1.135     www      14299: }
                   14300: 
                   14301: # ---------------------------------------------------------- Read package table
                   14302: {
1.1359    raeburn  14303:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14304: 
                   14305:     while (my $configline=<$config>) {
1.483     albertel 14306: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14307: 	chomp($configline);
                   14308: 	my ($short,$plain)=split(/:/,$configline);
                   14309: 	my ($pack,$name)=split(/\&/,$short);
                   14310: 	if ($plain ne '') {
                   14311: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14312: 	    $packagetab{$short}=$plain; 
                   14313: 	}
1.11      www      14314:     }
1.448     albertel 14315:     close($config);
1.329     matthew  14316: }
                   14317: 
1.1073    raeburn  14318: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14319: 
                   14320: &load_loncaparevs();
1.1073    raeburn  14321: 
1.1074    raeburn  14322: # ---------------------------------------------------------- Read serverhostID table
                   14323: 
1.1227    raeburn  14324: &load_serverhomeIDs();
                   14325: 
                   14326: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14327: {
                   14328:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14329:     if (-e $file) {
                   14330:         my $parser = HTML::LCParser->new($file);
                   14331:         while (my $token = $parser->get_token()) {
                   14332:             if ($token->[0] eq 'S') {
                   14333:                 my $item = $token->[1];
                   14334:                 my $name = $token->[2]{'name'};
                   14335:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14336:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14337:                 my $namematch = $token->[2]{'namematch'};
                   14338:                 if ($item eq 'parameter') {
                   14339:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14340:                         my $release = $parser->get_text();
                   14341:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14342:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14343:                     }
                   14344:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14345:                     my $release = $parser->get_text();
                   14346:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14347:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14348:                 }
                   14349:             }
                   14350:         }
                   14351:     }
1.1073    raeburn  14352: }
                   14353: 
1.1138    raeburn  14354: # ---------------------------------------------------------- Read managers table
                   14355: {
                   14356:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14357:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14358:             while (my $configline=<$config>) {
                   14359:                 chomp($configline);
                   14360:                 next if ($configline =~ /^\#/);
                   14361:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14362:                     $managerstab{$configline} = 1;
                   14363:                 }
                   14364:             }
                   14365:             close($config);
                   14366:         }
                   14367:     }
                   14368: }
                   14369: 
1.329     matthew  14370: # ------------- set up temporary directory
                   14371: {
1.1117    foxr     14372:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14373: 
1.11      www      14374: }
                   14375: 
1.794     albertel 14376: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14377: 				'compress_threshold'=> 20_000,
                   14378:  			        });
1.185     www      14379: 
1.281     www      14380: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14381: $dumpcount=0;
1.958     www      14382: $locknum=0;
1.22      www      14383: 
1.163     harris41 14384: &logtouch();
1.672     albertel 14385: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14386: $readit=1;
1.564     albertel 14387:     {
                   14388: 	use integer;
                   14389: 	my $test=(2**32)+1;
1.568     albertel 14390: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14391: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14392:     }
1.195     www      14393: }
1.1       albertel 14394: }
1.179     www      14395: 
1.1       albertel 14396: 1;
1.191     harris41 14397: __END__
                   14398: 
1.243     albertel 14399: =pod
                   14400: 
1.191     harris41 14401: =head1 NAME
                   14402: 
1.243     albertel 14403: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14404: 
                   14405: =head1 SYNOPSIS
                   14406: 
1.243     albertel 14407: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14408: 
                   14409:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14410: 
1.243     albertel 14411: Common parameters:
                   14412: 
                   14413: =over 4
                   14414: 
                   14415: =item *
                   14416: 
                   14417: $uname : an internal username (if $cname expecting a course Id specifically)
                   14418: 
                   14419: =item *
                   14420: 
                   14421: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14422: 
                   14423: =item *
                   14424: 
                   14425: $symb : a resource instance identifier
                   14426: 
                   14427: =item *
                   14428: 
                   14429: $namespace : the name of a .db file that contains the data needed or
                   14430: being set.
                   14431: 
                   14432: =back
                   14433: 
1.394     bowersj2 14434: =head1 OVERVIEW
1.191     harris41 14435: 
1.394     bowersj2 14436: lonnet provides subroutines which interact with the
                   14437: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14438: about classes, users, and resources.
1.243     albertel 14439: 
                   14440: For many of these objects you can also use this to store data about
                   14441: them or modify them in various ways.
1.191     harris41 14442: 
1.394     bowersj2 14443: =head2 Symbs
1.191     harris41 14444: 
1.394     bowersj2 14445: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14446: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14447: map, the resource number of the resource in the map, and the URL of
                   14448: the resource itself. The latter is somewhat redundant, but might help
                   14449: if maps change.
                   14450: 
                   14451: An example is
                   14452: 
                   14453:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14454: 
                   14455: The respective map entry is
                   14456: 
                   14457:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14458:   title="Problem 2">
                   14459:  </resource>
                   14460: 
                   14461: Symbs are used by the random number generator, as well as to store and
                   14462: restore data specific to a certain instance of for example a problem.
                   14463: 
                   14464: =head2 Storing And Retrieving Data
                   14465: 
                   14466: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14467: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14468: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14469: is is the non-critical message twin of cstore. These functions are for
                   14470: handlers to store a perl hash to a user's permanent data space in an
                   14471: easy manner, and to retrieve it again on another call. It is expected
                   14472: that a handler would use this once at the beginning to retrieve data,
                   14473: and then again once at the end to send only the new data back.
                   14474: 
                   14475: The data is stored in the user's data directory on the user's
                   14476: homeserver under the ID of the course.
                   14477: 
                   14478: The hash that is returned by restore will have all of the previous
                   14479: value for all of the elements of the hash.
                   14480: 
                   14481: Example:
                   14482: 
                   14483:  #creating a hash
                   14484:  my %hash;
                   14485:  $hash{'foo'}='bar';
                   14486: 
                   14487:  #storing it
                   14488:  &Apache::lonnet::cstore(\%hash);
                   14489: 
                   14490:  #changing a value
                   14491:  $hash{'foo'}='notbar';
                   14492: 
                   14493:  #adding a new value
                   14494:  $hash{'bar'}='foo';
                   14495:  &Apache::lonnet::cstore(\%hash);
                   14496: 
                   14497:  #retrieving the hash
                   14498:  my %history=&Apache::lonnet::restore();
                   14499: 
                   14500:  #print the hash
                   14501:  foreach my $key (sort(keys(%history))) {
                   14502:    print("\%history{$key} = $history{$key}");
                   14503:  }
                   14504: 
                   14505: Will print out:
1.191     harris41 14506: 
1.394     bowersj2 14507:  %history{1:foo} = bar
                   14508:  %history{1:keys} = foo:timestamp
                   14509:  %history{1:timestamp} = 990455579
                   14510:  %history{2:bar} = foo
                   14511:  %history{2:foo} = notbar
                   14512:  %history{2:keys} = foo:bar:timestamp
                   14513:  %history{2:timestamp} = 990455580
                   14514:  %history{bar} = foo
                   14515:  %history{foo} = notbar
                   14516:  %history{timestamp} = 990455580
                   14517:  %history{version} = 2
                   14518: 
                   14519: Note that the special hash entries C<keys>, C<version> and
                   14520: C<timestamp> were added to the hash. C<version> will be equal to the
                   14521: total number of versions of the data that have been stored. The
                   14522: C<timestamp> attribute will be the UNIX time the hash was
                   14523: stored. C<keys> is available in every historical section to list which
                   14524: keys were added or changed at a specific historical revision of a
                   14525: hash.
                   14526: 
                   14527: B<Warning>: do not store the hash that restore returns directly. This
                   14528: will cause a mess since it will restore the historical keys as if the
                   14529: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14530: 
1.394     bowersj2 14531: Calling convention:
1.191     harris41 14532: 
1.1225    raeburn  14533:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14534:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14535: 
1.394     bowersj2 14536: For more detailed information, see lonnet specific documentation.
1.191     harris41 14537: 
1.394     bowersj2 14538: =head1 RETURN MESSAGES
1.191     harris41 14539: 
1.394     bowersj2 14540: =over 4
1.191     harris41 14541: 
1.394     bowersj2 14542: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14543: 
1.394     bowersj2 14544: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14545: when the connection is brought back up
1.191     harris41 14546: 
1.394     bowersj2 14547: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14548: for later delivery
1.191     harris41 14549: 
1.967     bisitz   14550: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14551: 
1.394     bowersj2 14552: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14553: that was requested
1.191     harris41 14554: 
1.243     albertel 14555: =back
1.191     harris41 14556: 
1.243     albertel 14557: =head1 PUBLIC SUBROUTINES
1.191     harris41 14558: 
1.243     albertel 14559: =head2 Session Environment Functions
1.191     harris41 14560: 
1.243     albertel 14561: =over 4
1.191     harris41 14562: 
1.394     bowersj2 14563: =item * 
                   14564: X<appenv()>
1.949     raeburn  14565: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14566: the user envirnoment file, and will be restored for each access this
1.620     albertel 14567: user makes during this session, also modifies the %env for the current
1.949     raeburn  14568: process. Optional rolesarrayref - if defined contains a reference to an array
                   14569: of roles which are exempt from the restriction on modifying user.role entries 
                   14570: in the user's environment.db and in %env.    
1.191     harris41 14571: 
                   14572: =item *
1.394     bowersj2 14573: X<delenv()>
1.987     raeburn  14574: B<delenv($delthis,$regexp)>: removes all items from the session
                   14575: environment file that begin with $delthis. If the 
                   14576: optional second arg - $regexp - is true, $delthis is treated as a 
                   14577: regular expression, otherwise \Q$delthis\E is used. 
                   14578: The values are also deleted from the current processes %env.
1.191     harris41 14579: 
1.795     albertel 14580: =item * get_env_multiple($name) 
                   14581: 
                   14582: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14583: values may be defined and end up as an array ref.
                   14584: 
                   14585: returns an array of values
                   14586: 
1.243     albertel 14587: =back
                   14588: 
                   14589: =head2 User Information
1.191     harris41 14590: 
1.243     albertel 14591: =over 4
1.191     harris41 14592: 
                   14593: =item *
1.394     bowersj2 14594: X<queryauthenticate()>
                   14595: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14596: authentication scheme
                   14597: 
                   14598: =item *
1.394     bowersj2 14599: X<authenticate()>
1.1073    raeburn  14600: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14601: authenticate user from domain's lib servers (first use the current
                   14602: one). C<$upass> should be the users password.
1.1073    raeburn  14603: $checkdefauth is optional (value is 1 if a check should be made to
                   14604:    authenticate user using default authentication method, and allow
                   14605:    account creation if username does not have account in the domain).
                   14606: $clientcancheckhost is optional (value is 1 if checking whether the
                   14607:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14608: 
                   14609: =item *
1.394     bowersj2 14610: X<homeserver()>
                   14611: B<homeserver($uname,$udom)>: find the server which has
                   14612: the user's directory and files (there must be only one), this caches
                   14613: the answer, and also caches if there is a borken connection.
1.191     harris41 14614: 
                   14615: =item *
1.394     bowersj2 14616: X<idget()>
1.1300    raeburn  14617: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14618: a list of student/employee IDs or clicker IDs
                   14619: (student/employee IDs are a unique resource in a domain, there must be 
                   14620: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14621: clickerIDs are not necessarily unique, as students might share clickers.
                   14622: (returns hash: id=>name,id=>name)
1.191     harris41 14623: 
                   14624: =item *
1.394     bowersj2 14625: X<idrget()>
                   14626: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14627: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14628: 
                   14629: =item *
1.394     bowersj2 14630: X<idput()>
1.1300    raeburn  14631: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14632: names and associated student/employee IDs or clicker IDs.
                   14633: 
                   14634: =item *
                   14635: X<iddel()>
                   14636: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14637: student/employee ID or clicker ID username look-ups from domain.
                   14638: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14639: If no $uhome is provided, it will be determined usig &homeserver()
                   14640: for each user.  If no $namespace is provided, the default is ids.
                   14641: 
                   14642: =item *
                   14643: X<updateclickers()>
                   14644: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14645: clicker ID-to-username look-ups in clickers.db on library server.
                   14646: Permitted actions are add or del (i.e., add or delete). The 
                   14647: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14648: value is an escaped comma-separated list of usernames (for whom the
                   14649: library server is the homeserver), who registered that particular ID.
                   14650: If $critical is true, the update will be sent via &critical, otherwise
                   14651: &reply() will be used.
1.191     harris41 14652: 
                   14653: =item *
1.394     bowersj2 14654: X<rolesinit()>
1.1169    droeschl 14655: B<rolesinit($udom,$username)>: get user privileges.
                   14656: returns user role, first access and timer interval hashes
1.243     albertel 14657: 
                   14658: =item *
1.1171    droeschl 14659: X<privileged()>
                   14660: B<privileged($username,$domain)>: returns a true if user has a
                   14661: privileged and active role (i.e. su or dc), false otherwise.
                   14662: 
                   14663: =item *
1.551     albertel 14664: X<getsection()>
                   14665: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14666: course $cname, return section name/number or '' for "not in course"
                   14667: and '-1' for "no section"
                   14668: 
                   14669: =item *
1.394     bowersj2 14670: X<userenvironment()>
                   14671: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14672: passed in @what from the requested user's environment, returns a hash
                   14673: 
1.858     raeburn  14674: =item * 
                   14675: X<userlog_query()>
1.859     albertel 14676: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14677: activity.log file. %filters defines filters applied when parsing the
                   14678: log file. These can be start or end timestamps, or the type of action
                   14679: - log to look for Login or Logout events, check for Checkin or
                   14680: Checkout, role for role selection. The response is in the form
                   14681: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14682: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14683: 
1.243     albertel 14684: =back
                   14685: 
                   14686: =head2 User Roles
                   14687: 
                   14688: =over 4
                   14689: 
                   14690: =item *
                   14691: 
1.1284    raeburn  14692: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14693: returns codes for allowed actions.
                   14694: 
                   14695: The first argument is required, all others are optional.
                   14696: 
                   14697: $priv is the privilege being checked.
                   14698: $uri contains additional information about what is being checked for access (e.g.,
                   14699: URL, course ID etc.). 
                   14700: $symb is the unique resource instance identifier in a course; if needed,
                   14701: but not provided, it will be retrieved via a call to &symbread(). 
                   14702: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14703: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14704: files).
                   14705: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14706: prevents recursive calls to &allowed.
                   14707: 
1.243     albertel 14708:  F: full access
                   14709:  U,I,K: authentication modes (cxx only)
                   14710:  '': forbidden
                   14711:  1: user needs to choose course
                   14712:  2: browse allowed
1.766     albertel 14713:  A: passphrase authentication needed
1.1284    raeburn  14714:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14715: 
                   14716: =item *
                   14717: 
1.1192    raeburn  14718: constructaccess($url,$setpriv) : check for access to construction space URL
                   14719: 
                   14720: See if the owner domain and name in the URL match those in the
                   14721: expected environment.  If so, return three element list
                   14722: ($ownername,$ownerdomain,$ownerhome).
                   14723: 
                   14724: Otherwise return the null string.
                   14725: 
                   14726: If second argument 'setpriv' is true, it assigns the privileges,
                   14727: and returns the same three element list, unless the owner has
                   14728: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14729: in which case the null string is returned.
                   14730: 
                   14731: =item *
                   14732: 
1.1326    raeburn  14733: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14734: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14735: for system, domain, and course level. $uname and $udom are optional (current
                   14736: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14737: 
                   14738: =item *
                   14739: 
1.988     raeburn  14740: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14741: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14742: $type is Course (default) or Community.
1.988     raeburn  14743: If $forcedefault evaluates to true, text returned will be default 
                   14744: text for $type. Otherwise, if this is a course, the text returned 
                   14745: will be a custom name for the role (if defined in the course's 
                   14746: environment).  If no custom name is defined the default is returned.
                   14747:    
1.832     raeburn  14748: =item *
                   14749: 
1.1219    raeburn  14750: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14751: All arguments are optional. Returns a hash of a roles, either for
                   14752: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14753: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14754: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14755: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14756: For each key, value is set to colon-separated start and end times for
                   14757: the role.  If no username and domain are specified, will default to
1.934     raeburn  14758: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14759: of role statuses (active, future or previous), roles 
                   14760: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14761: to restrict the list of roles reported. If no array ref is 
                   14762: provided for types, will default to return only active roles.
1.834     albertel 14763: 
1.1195    raeburn  14764: =item *
                   14765: 
                   14766: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14767: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14768: 
                   14769: Additional optional arguments are: $type (if role checking is to be restricted 
                   14770: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14771: available roles) or future (roles available in the future), and
                   14772: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14773: have active Domain Coordinator role in course's domain or in additional
                   14774: domains (specified in 'Domains to check for privileged users' in course
                   14775: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14776: 
                   14777: =item *
                   14778: 
                   14779: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14780: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14781: $possdomains and $possroles are optional array refs -- to domains to check and
                   14782: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14783: users' roles.db to check for a dc or su role in any domain. This can be
                   14784: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14785: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14786: this then allows &privileged_by_domain() to be used, which caches the identity
                   14787: of privileged users, eliminating the need for repeated calls to &dump().
                   14788: 
                   14789: =item *
                   14790: 
                   14791: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14792: where the outer hash keys are domains specified in the $possdomains array ref,
                   14793: next inner hash keys are privileged roles specified in the $roles array ref,
                   14794: and the innermost hash contains key = value pairs for username:domain = end:start
                   14795: for active or future "privileged" users with that role in that domain. To avoid
                   14796: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14797: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14798: 
1.243     albertel 14799: =back
                   14800: 
                   14801: =head2 User Modification
                   14802: 
                   14803: =over 4
                   14804: 
                   14805: =item *
                   14806: 
1.957     raeburn  14807: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14808: user for the level given by URL.  Optional start and end dates (leave empty
                   14809: string or zero for "no date")
1.191     harris41 14810: 
                   14811: =item *
                   14812: 
1.243     albertel 14813: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14814: change a users, password, possible return values are: ok,
                   14815: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14816: refused
1.191     harris41 14817: 
                   14818: =item *
                   14819: 
1.243     albertel 14820: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14821: 
                   14822: =item *
                   14823: 
1.1058    raeburn  14824: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14825:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14826: 
                   14827: will update user information (firstname,middlename,lastname,generation,
                   14828: permanentemail), and if forceid is true, student/employee ID also.
                   14829: A user's institutional affiliation(s) can also be updated.
                   14830: User information fields will not be overwritten with empty entries 
                   14831: unless the field is included in the $candelete array reference.
                   14832: This array is included when a single user is modified via "Manage Users",
                   14833: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14834: 
                   14835: =item *
                   14836: 
1.286     matthew  14837: modifystudent
                   14838: 
1.957     raeburn  14839: modify a student's enrollment and identification information.
1.1235    raeburn  14840: The course id is resolved based on the current user's environment.  
                   14841: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14842: associated with a course.
                   14843: 
1.297     matthew  14844: This call is essentially a wrapper for lonnet::modifyuser and
                   14845: lonnet::modify_student_enrollment
1.286     matthew  14846: 
                   14847: Inputs: 
                   14848: 
                   14849: =over 4
                   14850: 
1.957     raeburn  14851: =item B<$udom> Student's loncapa domain
1.286     matthew  14852: 
1.957     raeburn  14853: =item B<$uname> Student's loncapa login name
1.286     matthew  14854: 
1.964     bisitz   14855: =item B<$uid> Student/Employee ID
1.286     matthew  14856: 
1.957     raeburn  14857: =item B<$umode> Student's authentication mode
1.286     matthew  14858: 
1.957     raeburn  14859: =item B<$upass> Student's password
1.286     matthew  14860: 
1.957     raeburn  14861: =item B<$first> Student's first name
1.286     matthew  14862: 
1.957     raeburn  14863: =item B<$middle> Student's middle name
1.286     matthew  14864: 
1.957     raeburn  14865: =item B<$last> Student's last name
1.286     matthew  14866: 
1.957     raeburn  14867: =item B<$gene> Student's generation
1.286     matthew  14868: 
1.957     raeburn  14869: =item B<$usec> Student's section in course
1.286     matthew  14870: 
                   14871: =item B<$end> Unix time of the roles expiration
                   14872: 
                   14873: =item B<$start> Unix time of the roles start date
                   14874: 
                   14875: =item B<$forceid> If defined, allow $uid to be changed
                   14876: 
                   14877: =item B<$desiredhome> server to use as home server for student
                   14878: 
1.957     raeburn  14879: =item B<$email> Student's permanent e-mail address
                   14880: 
                   14881: =item B<$type> Type of enrollment (auto or manual)
                   14882: 
1.963     raeburn  14883: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14884: 
                   14885: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14886: 
1.963     raeburn  14887: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14888: 
1.963     raeburn  14889: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14890: 
1.1216    raeburn  14891: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14892: 
                   14893: =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  14894: 
1.286     matthew  14895: =back
1.297     matthew  14896: 
                   14897: =item *
                   14898: 
                   14899: modify_student_enrollment
                   14900: 
1.1235    raeburn  14901: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14902: 'role.request.course' must be defined for this function to proceed.
                   14903: 
                   14904: Inputs:
                   14905: 
                   14906: =over 4
                   14907: 
1.1235    raeburn  14908: =item $udom, student's domain
1.297     matthew  14909: 
1.1235    raeburn  14910: =item $uname, student's name
1.297     matthew  14911: 
1.1235    raeburn  14912: =item $uid, student's user id
1.297     matthew  14913: 
1.1235    raeburn  14914: =item $first, student's first name
1.297     matthew  14915: 
                   14916: =item $middle
                   14917: 
                   14918: =item $last
                   14919: 
                   14920: =item $gene
                   14921: 
                   14922: =item $usec
                   14923: 
                   14924: =item $end
                   14925: 
                   14926: =item $start
                   14927: 
1.957     raeburn  14928: =item $type
                   14929: 
                   14930: =item $locktype
                   14931: 
                   14932: =item $cid
                   14933: 
                   14934: =item $selfenroll
                   14935: 
                   14936: =item $context
                   14937: 
1.1216    raeburn  14938: =item $credits, number of credits student will earn from this class
                   14939: 
1.1314    raeburn  14940: =item $instsec, institutional course section code for student
                   14941: 
1.297     matthew  14942: =back
                   14943: 
1.191     harris41 14944: 
                   14945: =item *
                   14946: 
1.243     albertel 14947: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14948: custom role; give a custom role to a user for the level given by URL.  Specify
                   14949: name and domain of role author, and role name
1.191     harris41 14950: 
                   14951: =item *
                   14952: 
1.243     albertel 14953: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14954: 
                   14955: =item *
                   14956: 
1.243     albertel 14957: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14958: 
                   14959: =back
                   14960: 
                   14961: =head2 Course Infomation
                   14962: 
                   14963: =over 4
1.191     harris41 14964: 
                   14965: =item *
                   14966: 
1.1118    foxr     14967: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14968: specified course id, including all environment settings for the
                   14969: course, the description of the course will be in the hash under the
                   14970: key 'description'
1.191     harris41 14971: 
1.1118    foxr     14972: $options is an optional parameter that if supplied is a hash reference that controls
                   14973: what how this function works.  It has the following key/values:
                   14974: 
                   14975: =over 4
                   14976: 
                   14977: =item freshen_cache
                   14978: 
                   14979: If defined, and the environment cache for the course is valid, it is 
                   14980: returned in the returned hash.
                   14981: 
                   14982: =item one_time
                   14983: 
                   14984: If defined, the last cache time is set to _now_
                   14985: 
                   14986: =item user
                   14987: 
                   14988: If defined, the supplied username is used instead of the current user.
                   14989: 
                   14990: 
                   14991: =back
                   14992: 
1.191     harris41 14993: =item *
                   14994: 
1.624     albertel 14995: resdata($name,$domain,$type,@which) : request for current parameter
                   14996: setting for a specific $type, where $type is either 'course' or 'user',
                   14997: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14998: answers for 10 minutes.
1.243     albertel 14999: 
1.877     foxr     15000: =item *
                   15001: 
                   15002: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15003: data base, returning a hash that is keyed by the resource name and has
                   15004: values that are the resource value.  I believe that the timestamps and
                   15005: versions are also returned.
                   15006: 
1.1236    raeburn  15007: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15008: supplemental content area. This routine caches the number of files for 
                   15009: 10 minutes.
                   15010: 
1.243     albertel 15011: =back
                   15012: 
                   15013: =head2 Course Modification
                   15014: 
                   15015: =over 4
1.191     harris41 15016: 
                   15017: =item *
                   15018: 
1.243     albertel 15019: writecoursepref($courseid,%prefs) : write preferences (environment
                   15020: database) for a course
1.191     harris41 15021: 
                   15022: =item *
                   15023: 
1.1011    raeburn  15024: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15025: 
                   15026: =item *
                   15027: 
1.1038    raeburn  15028: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15029: 
1.1167    droeschl 15030: =item *
                   15031: 
                   15032: is_course($courseid), is_course($cdom, $cnum)
                   15033: 
                   15034: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15035: two component version $cdom, $cnum. It checks if the specified course exists.
                   15036: 
                   15037: Returns:
                   15038:     undef if the course doesn't exist, otherwise
                   15039:     in scalar context the combined courseid.
                   15040:     in list context the two components of the course identifier, domain and 
                   15041:     courseid.    
                   15042: 
1.243     albertel 15043: =back
                   15044: 
                   15045: =head2 Resource Subroutines
                   15046: 
                   15047: =over 4
1.191     harris41 15048: 
                   15049: =item *
                   15050: 
1.243     albertel 15051: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15052: 
                   15053: =item *
                   15054: 
1.243     albertel 15055: repcopy($filename) : subscribes to the requested file, and attempts to
                   15056: replicate from the owning library server, Might return
1.607     raeburn  15057: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15058: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15059: resource. Expects the local filesystem pathname
                   15060: (/home/httpd/html/res/....)
                   15061: 
                   15062: =back
                   15063: 
                   15064: =head2 Resource Information
                   15065: 
                   15066: =over 4
1.191     harris41 15067: 
                   15068: =item *
                   15069: 
1.1228    raeburn  15070: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15071: and returns the value of a variety of different possible values,
                   15072: $varname should be a request string, and the other parameters can be
                   15073: used to specify who and what one is asking about. Ordinarily, $cid 
                   15074: does not need to be specified, as it is retrived from 
                   15075: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15076: within lonuserstate::loadmap() when initializing a course, before
                   15077: $env{'request.course.id'} has been set, so it needs to be provided
                   15078: in that one case.
1.243     albertel 15079: 
                   15080: Possible values for $varname are environment.lastname (or other item
                   15081: from the envirnment hash), user.name (or someother aspect about the
                   15082: user), resource.0.maxtries (or some other part and parameter of a
                   15083: resource)
1.204     albertel 15084: 
                   15085: =item *
                   15086: 
1.243     albertel 15087: directcondval($number) : get current value of a condition; reads from a state
                   15088: string
1.204     albertel 15089: 
                   15090: =item *
                   15091: 
1.243     albertel 15092: condval($condidx) : value of condition index based on state
1.204     albertel 15093: 
                   15094: =item *
                   15095: 
1.1362    raeburn  15096: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15097: resource's metadata, $what should be either a specific key, or either
                   15098: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15099: packages that this resource currently uses, the last 3 arguments are 
                   15100: only used internally for recursive metadata.
                   15101: 
                   15102: the toolsymb is only used where the uri is for an external tool (for which
                   15103: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15104: 
1.1371    raeburn  15105: this function automatically caches all requests except any made recursively
                   15106: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15107: defined).
1.191     harris41 15108: 
                   15109: =item *
                   15110: 
1.243     albertel 15111: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15112: network of library servers; returns file handle of where SQL and regex results
                   15113: will be stored for query
1.191     harris41 15114: 
                   15115: =item *
                   15116: 
1.1282    raeburn  15117: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15118: return symbolic list entry (all arguments optional). 
                   15119: 
                   15120: Args: filename is the filename (including path) for the file for which a symb 
                   15121: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15122: to check access status if more than one resource was found in the bighash 
                   15123: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15124: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15125: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15126: cause possible symbs to be checked to determine if they are subject to content
                   15127: blocking, if so they will not be included as possible symbs; possibles is a
                   15128: ref to a hash, which, as a side effect, will be populated with all possible 
                   15129: symbs (content blocking not tested).
                   15130:  
1.243     albertel 15131: returns the data handle
1.191     harris41 15132: 
                   15133: =item *
                   15134: 
1.1190    raeburn  15135: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15136: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15137: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15138: on failure, user must be in a course, as it assumes the existence of
                   15139: the course initial hash, and uses $env('request.course.id'}.  The third
                   15140: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15141: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15142: encrypted; otherwise it will be null.  
1.191     harris41 15143: 
                   15144: =item *
                   15145: 
1.243     albertel 15146: symbclean($symb) : removes versions numbers from a symb, returns the
                   15147: cleaned symb
1.191     harris41 15148: 
                   15149: =item *
                   15150: 
1.243     albertel 15151: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15152: course map, user must be in a course for it to work.
1.191     harris41 15153: 
                   15154: =item *
                   15155: 
1.243     albertel 15156: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15157: 
                   15158: =item *
                   15159: 
1.243     albertel 15160: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15161: a random seed, all arguments are optional, if they aren't sent it uses the
                   15162: environment to derive them. Note: if symb isn't sent and it can't get one
                   15163: from &symbread it will use the current time as its return value
1.191     harris41 15164: 
                   15165: =item *
                   15166: 
1.243     albertel 15167: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15168: unfakeable, receipt
1.191     harris41 15169: 
                   15170: =item *
                   15171: 
1.620     albertel 15172: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15173: 
                   15174: =item *
                   15175: 
1.243     albertel 15176: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15177: 
                   15178: =item *
                   15179: 
1.243     albertel 15180: 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 15181: 
                   15182: =item *
                   15183: 
1.243     albertel 15184: 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 15185: 
                   15186: =item *
                   15187: 
1.243     albertel 15188: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15189: 
                   15190: =item *
                   15191: 
1.243     albertel 15192: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15193: forcing spreadsheet to reevaluate the resource scores next time.
                   15194: 
1.1195    raeburn  15195: =item * 
                   15196: 
1.1196    raeburn  15197: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15198: when viewing in course context.
1.1195    raeburn  15199: 
1.1196    raeburn  15200:  input: six args -- filename (decluttered), course number, course domain,
                   15201:                     url, symb (if registered) and group (if this is a 
                   15202:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15203: 
1.1196    raeburn  15204:  output: array of five scalars --
1.1195    raeburn  15205:          $cfile -- url for file editing if editable on current server
                   15206:          $home -- homeserver of resource (i.e., for author if published,
                   15207:                                           or course if uploaded.).
                   15208:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15209:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15210:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15211: 
                   15212: =item *
                   15213: 
                   15214: is_course_upload($file,$cnum,$cdom)
                   15215: 
                   15216: Used in course context to determine if current file was uploaded to 
                   15217: the course (i.e., would be found in /userfiles/docs on the course's 
                   15218: homeserver.
                   15219: 
                   15220:   input: 3 args -- filename (decluttered), course number and course domain.
                   15221:   output: boolean -- 1 if file was uploaded.
                   15222: 
1.243     albertel 15223: =back
                   15224: 
                   15225: =head2 Storing/Retreiving Data
                   15226: 
                   15227: =over 4
1.191     harris41 15228: 
                   15229: =item *
                   15230: 
1.1269    raeburn  15231: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15232: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15233: the remaining args aren't required and if they aren't passed or are '' they will
                   15234: be derived from the env (with the exception of $laststore, which is an 
                   15235: optional arg used when a user's submission is stored in grading).
                   15236: $laststore is $version=$timestamp, where $version is the most recent version
                   15237: number retrieved for the corresponding $symb in the $namespace db file, and
                   15238: $timestamp is the timestamp for that transaction (UNIX time).
                   15239: $laststore is currently only passed when cstore() is called by 
                   15240: structuretags::finalize_storage().
1.191     harris41 15241: 
                   15242: =item *
                   15243: 
1.1269    raeburn  15244: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15245: but uses critical subroutine
1.191     harris41 15246: 
                   15247: =item *
                   15248: 
1.243     albertel 15249: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15250: all args are optional
1.191     harris41 15251: 
                   15252: =item *
                   15253: 
1.717     albertel 15254: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15255: dumps the complete (or key matching regexp) namespace into a hash
                   15256: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15257: normally &store()ed into
                   15258: 
                   15259: $range should be either an integer '100' (give me the first 100
                   15260:                                            matching records)
                   15261:               or be  two integers sperated by a - with no spaces
                   15262:                  '30-50' (give me the 30th through the 50th matching
                   15263:                           records)
                   15264: 
                   15265: 
                   15266: =item *
                   15267: 
1.1269    raeburn  15268: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15269: replaces a &store() version of data with a replacement set of data
                   15270: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15271: reference. If $tolog is true, the transaction is logged in the courselog
                   15272: with an action=PUTSTORE.
1.717     albertel 15273: 
                   15274: =item *
                   15275: 
1.243     albertel 15276: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15277: works very similar to store/cstore, but all data is stored in a
                   15278: temporary location and can be reset using tmpreset, $storehash should
                   15279: be a hash reference, returns nothing on success
1.191     harris41 15280: 
                   15281: =item *
                   15282: 
1.243     albertel 15283: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15284: similar to restore, but all data is stored in a temporary location and
                   15285: can be reset using tmpreset. Returns a hash of values on success,
                   15286: error string otherwise.
1.191     harris41 15287: 
                   15288: =item *
                   15289: 
1.243     albertel 15290: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15291: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15292: 
                   15293: =item *
                   15294: 
1.243     albertel 15295: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15296: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15297: 
                   15298: =item *
                   15299: 
1.243     albertel 15300: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15301: namesp ($udom and $uname are optional)
1.191     harris41 15302: 
                   15303: =item *
                   15304: 
1.702     albertel 15305: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15306: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15307: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15308: 
1.702     albertel 15309: $range should be either an integer '100' (give me the first 100
                   15310:                                            matching records)
                   15311:               or be  two integers sperated by a - with no spaces
                   15312:                  '30-50' (give me the 30th through the 50th matching
                   15313:                           records)
1.449     matthew  15314: =item *
                   15315: 
                   15316: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15317: $store can be a scalar, an array reference, or if the amount to be 
                   15318: incremented is > 1, a hash reference.
                   15319: 
                   15320: ($udom and $uname are optional)
1.191     harris41 15321: 
                   15322: =item *
                   15323: 
1.243     albertel 15324: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15325: ($udom and $uname are optional)
1.191     harris41 15326: 
                   15327: =item *
                   15328: 
1.243     albertel 15329: cput($namespace,$storehash,$udom,$uname) : critical put
                   15330: ($udom and $uname are optional)
1.191     harris41 15331: 
                   15332: =item *
                   15333: 
1.748     albertel 15334: newput($namespace,$storehash,$udom,$uname) :
                   15335: 
                   15336: Attempts to store the items in the $storehash, but only if they don't
                   15337: currently exist, if this succeeds you can be certain that you have 
                   15338: successfully created a new key value pair in the $namespace db.
                   15339: 
                   15340: 
                   15341: Args:
                   15342:  $namespace: name of database to store values to
                   15343:  $storehash: hashref to store to the db
                   15344:  $udom: (optional) domain of user containing the db
                   15345:  $uname: (optional) name of user caontaining the db
                   15346: 
                   15347: Returns:
                   15348:  'ok' -> succeeded in storing all keys of $storehash
                   15349:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15350:                         least <key> already existed in the db (other
                   15351:                         requested keys may also already exist)
1.967     bisitz   15352:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15353:  'con_lost' -> unable to contact request server
                   15354:  'refused' -> action was not allowed by remote machine
                   15355: 
                   15356: 
                   15357: =item *
                   15358: 
1.243     albertel 15359: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15360: reference filled in from namesp (encrypts the return communication)
                   15361: ($udom and $uname are optional)
1.191     harris41 15362: 
                   15363: =item *
                   15364: 
1.243     albertel 15365: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15366: critical subroutine
                   15367: 
1.806     raeburn  15368: =item *
                   15369: 
1.860     raeburn  15370: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15371: array reference filled in from namespace found in domain level on either
                   15372: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15373: 
                   15374: =item *
                   15375: 
1.860     raeburn  15376: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15377: domain level either on specified domain server ($uhome) or primary domain 
                   15378: server ($udom and $uhome are optional)
1.806     raeburn  15379: 
1.943     raeburn  15380: =item * 
                   15381: 
1.1240    raeburn  15382: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15383: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15384: the target domain.
                   15385: 
                   15386: May also include additional key => value pairs for the following groups:
                   15387: 
                   15388: =over
                   15389: 
                   15390: =item
                   15391: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15392: 
                   15393: =over
                   15394: 
                   15395: =item defaultquota, authorquota
                   15396: 
                   15397: =back
                   15398: 
                   15399: =item
                   15400: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15401: portfolio for users).
                   15402: 
                   15403: =over
                   15404: 
                   15405: =item
                   15406: aboutme, blog, webdav, portfolio
                   15407: 
                   15408: =back
                   15409: 
                   15410: =item
                   15411: requestcourses: ability to request courses, and how requests are processed.
                   15412: 
                   15413: =over
                   15414: 
                   15415: =item
1.1305    raeburn  15416: official, unofficial, community, textbook, placement
1.1240    raeburn  15417: 
                   15418: =back
                   15419: 
                   15420: =item
                   15421: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15422: 
                   15423: =over
                   15424: 
                   15425: =item
1.1256    raeburn  15426: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15427: 
                   15428: =back
                   15429: 
                   15430: =item
                   15431: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15432: for course's uploaded content.
                   15433: 
                   15434: =over
                   15435: 
                   15436: =item
1.1246    raeburn  15437: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15438: communityquota, textbookquota, placementquota
1.1240    raeburn  15439: 
                   15440: =back
                   15441: 
                   15442: =item
                   15443: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15444: on your servers.
                   15445: 
                   15446: =over
                   15447: 
                   15448: =item 
                   15449: remotesessions, hostedsessions
                   15450: 
                   15451: =back
                   15452: 
                   15453: =back
                   15454: 
                   15455: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15456: utility to create a configuration.db file on a domain's primary library server 
                   15457: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15458: -- corresponding values are authentication type (internal, krb4, krb5,
                   15459: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15460: will be available. Values are retrieved from cache (if current), unless the
                   15461: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15462: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15463: 
                   15464: Typical usage:
1.943     raeburn  15465: 
1.1240    raeburn  15466: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15467: 
1.243     albertel 15468: =back
                   15469: 
                   15470: =head2 Network Status Functions
                   15471: 
                   15472: =over 4
1.191     harris41 15473: 
                   15474: =item *
                   15475: 
1.1137    raeburn  15476: dirlist() : return directory list based on URI (first arg).
                   15477: 
                   15478: Inputs: 1 required, 5 optional.
                   15479: 
                   15480: =over
                   15481: 
                   15482: =item 
                   15483: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15484: 
                   15485: =item
                   15486: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15487: 
                   15488: =item
                   15489: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15490: 
                   15491: =item
                   15492: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15493: 
                   15494: =item
                   15495: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15496: 
                   15497: =item 
                   15498: $alternateRoot - path to prepend in place of path from $uri.
                   15499: 
                   15500: =back
                   15501: 
                   15502: Returns: Array of up to two items.
                   15503: 
                   15504: =over
                   15505: 
                   15506: a reference to an array of files/subdirectories
                   15507: 
                   15508: =over
                   15509: 
                   15510: Each element in the array of files/subdirectories is a & separated list of
                   15511: item name and the result of running stat on the item.  If dirlist was requested
                   15512: for a file instead of a directory, the item name will be ''. For a directory 
                   15513: listing, if the item is a metadata file, the element will end &N&M 
                   15514: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15515: default copyright set (1).  
                   15516: 
                   15517: =back
                   15518: 
                   15519: a scalar containing error condition (if encountered).
                   15520: 
                   15521: =over
                   15522: 
                   15523: =item 
                   15524: no_host (no homeserver identified for $username:$domain).
                   15525: 
                   15526: =item 
                   15527: no_such_host (server contacted for listing not identified as valid host).
                   15528: 
                   15529: =item 
                   15530: con_lost (connection to remote server failed).
                   15531: 
                   15532: =item 
                   15533: refused (invalid $username:$domain received on lond side).
                   15534: 
                   15535: =item 
                   15536: no_such_dir (directory at specified path on lond side does not exist). 
                   15537: 
                   15538: =item 
                   15539: empty (directory at specified path on lond side is empty).
                   15540: 
                   15541: =over
                   15542: 
                   15543: This is currently not encountered because the &ls3, &ls2, 
                   15544: &ls (_handler) routines on the lond side do not filter out
                   15545: . and .. from a directory listing. 
                   15546: 
                   15547: =back
                   15548: 
                   15549: =back
                   15550: 
                   15551: =back
1.191     harris41 15552: 
                   15553: =item *
                   15554: 
1.243     albertel 15555: spareserver() : find server with least workload from spare.tab
                   15556: 
1.986     foxr     15557: 
                   15558: =item *
                   15559: 
                   15560: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15561: if there is no corresponding loncapa host.
                   15562: 
1.243     albertel 15563: =back
                   15564: 
1.986     foxr     15565: 
1.243     albertel 15566: =head2 Apache Request
                   15567: 
                   15568: =over 4
1.191     harris41 15569: 
                   15570: =item *
                   15571: 
1.243     albertel 15572: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15573: localhost, posts hash
                   15574: 
                   15575: =back
                   15576: 
                   15577: =head2 Data to String to Data
                   15578: 
                   15579: =over 4
1.191     harris41 15580: 
                   15581: =item *
                   15582: 
1.243     albertel 15583: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15584: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15585: 
                   15586: =item *
                   15587: 
1.243     albertel 15588: hashref2str($hashref) : convert a hashref into a string complete with
                   15589: escaping and '=' and '&' separators, supports elements that are
                   15590: arrayrefs and hashrefs
1.191     harris41 15591: 
                   15592: =item *
                   15593: 
1.243     albertel 15594: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15595: with escaping and '&' separators, supports elements that are arrayrefs
                   15596: and hashrefs
1.191     harris41 15597: 
                   15598: =item *
                   15599: 
1.243     albertel 15600: str2hash($string) : convert string to hash using unescaping and
                   15601: splitting on '=' and '&', supports elements that are arrayrefs and
                   15602: hashrefs
1.191     harris41 15603: 
                   15604: =item *
                   15605: 
1.243     albertel 15606: str2array($string) : convert string to hash using unescaping and
                   15607: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15608: 
                   15609: =back
                   15610: 
                   15611: =head2 Logging Routines
                   15612: 
                   15613: 
                   15614: These routines allow one to make log messages in the lonnet.log and
                   15615: lonnet.perm logfiles.
1.191     harris41 15616: 
1.1119    foxr     15617: =over 4
                   15618: 
1.191     harris41 15619: =item *
                   15620: 
1.243     albertel 15621: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15622: 
                   15623: =item *
                   15624: 
1.243     albertel 15625: logthis() : append message to the normal lonnet.log file, it gets
                   15626: preiodically rolled over and deleted.
1.191     harris41 15627: 
                   15628: =item *
                   15629: 
1.243     albertel 15630: logperm() : append a permanent message to lonnet.perm.log, this log
                   15631: file never gets deleted by any automated portion of the system, only
                   15632: messages of critical importance should go in here.
                   15633: 
1.1119    foxr     15634: 
1.243     albertel 15635: =back
                   15636: 
                   15637: =head2 General File Helper Routines
                   15638: 
                   15639: =over 4
1.191     harris41 15640: 
                   15641: =item *
                   15642: 
1.481     raeburn  15643: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15644: (a) files in /uploaded
                   15645:   (i) If a local copy of the file exists - 
                   15646:       compares modification date of local copy with last-modified date for 
                   15647:       definitive version stored on home server for course. If local copy is 
                   15648:       stale, requests a new version from the home server and stores it. 
                   15649:       If the original has been removed from the home server, then local copy 
                   15650:       is unlinked.
                   15651:   (ii) If local copy does not exist -
                   15652:       requests the file from the home server and stores it. 
                   15653:   
                   15654:   If $caller is 'uploadrep':  
                   15655:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15656:     for request for files originally uploaded via DOCS. 
                   15657:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15658:   
                   15659:   Otherwise:
                   15660:      This indicates a call from the content generation phase of the request.
                   15661:      -  returns the entire contents of the file or -1.
                   15662:      
                   15663: (b) files in /res
                   15664:    - returns the entire contents of a file or -1; 
                   15665:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15666: 
1.712     albertel 15667: 
                   15668: =item *
                   15669: 
                   15670: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15671:                   reference
                   15672: 
                   15673: returns either a stat() list of data about the file or an empty list
                   15674: if the file doesn't exist or couldn't find out about it (connection
                   15675: problems or user unknown)
                   15676: 
1.191     harris41 15677: =item *
                   15678: 
1.243     albertel 15679: filelocation($dir,$file) : returns file system location of a file
                   15680: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15681: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15682: and a file of ../bob will become /a/bob)
1.191     harris41 15683: 
                   15684: =item *
                   15685: 
                   15686: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15687: filelocation except for hrefs
                   15688: 
                   15689: =item *
                   15690: 
1.1261    raeburn  15691: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15692: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15693: 
1.243     albertel 15694: =back
                   15695: 
1.608     albertel 15696: =head2 Usererfile file routines (/uploaded*)
                   15697: 
                   15698: =over 4
                   15699: 
                   15700: =item *
                   15701: 
                   15702: userfileupload(): main rotine for putting a file in a user or course's
                   15703:                   filespace, arguments are,
                   15704: 
1.620     albertel 15705:  formname - required - this is the name of the element in $env where the
1.608     albertel 15706:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15707:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15708:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15709:  context - if coursedoc, store the file in the course of the active role
                   15710:              of the current user; 
                   15711:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15712:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15713:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15714:          if undefined, it will be placed in "unknown"
                   15715: 
                   15716:  (This routine calls clean_filename() to remove any dangerous
                   15717:  characters from the filename, and then calls finuserfileupload() to
                   15718:  complete the transaction)
                   15719: 
                   15720:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15721:  and /adm/notfound.html if unsuccessful
                   15722: 
                   15723: =item *
                   15724: 
                   15725: clean_filename(): routine for cleaing a filename up for storage in
                   15726:                  userfile space, argument is:
                   15727: 
                   15728:  filename - proposed filename
                   15729: 
                   15730: returns: the new clean filename
                   15731: 
                   15732: =item *
                   15733: 
1.1090    raeburn  15734: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15735: userspace, probably shouldn't be called directly
                   15736: 
                   15737:   docuname: username or courseid of destination for the file
                   15738:   docudom: domain of user/course of destination for the file
                   15739:   formname: same as for userfileupload()
1.1090    raeburn  15740:   fname: filename (including subdirectories) for the file
                   15741:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15742:   allfiles: reference to hash used to store objects found by parser
                   15743:   codebase: reference to hash used for codebases of java objects found by parser
                   15744:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15745:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15746:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15747:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15748:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15749:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15750:   mimetype: reference to scalar to accommodate mime type determined
                   15751:             from File::MMagic if $parser = parse.
1.608     albertel 15752: 
                   15753:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15754:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15755:  was 'overwrite').
                   15756:  
1.608     albertel 15757: 
                   15758: =item *
                   15759: 
                   15760: renameuserfile(): renames an existing userfile to a new name
                   15761: 
                   15762:   Args:
                   15763:    docuname: username or courseid of destination for the file
                   15764:    docudom: domain of user/course of destination for the file
                   15765:    old: current file name (including any subdirs under userfiles)
                   15766:    new: desired file name (including any subdirs under userfiles)
                   15767: 
                   15768: =item *
                   15769: 
                   15770: mkdiruserfile(): creates a directory is a userfiles dir
                   15771: 
                   15772:   Args:
                   15773:    docuname: username or courseid of destination for the file
                   15774:    docudom: domain of user/course of destination for the file
                   15775:    dir: dir to create (including any subdirs under userfiles)
                   15776: 
                   15777: =item *
                   15778: 
                   15779: removeuserfile(): removes a file that exists in userfiles
                   15780: 
                   15781:   Args:
                   15782:    docuname: username or courseid of destination for the file
                   15783:    docudom: domain of user/course of destination for the file
                   15784:    fname: filname to delete (including any subdirs under userfiles)
                   15785: 
                   15786: =item *
                   15787: 
                   15788: removeuploadedurl(): convience function for removeuserfile()
                   15789: 
                   15790:   Args:
                   15791:    url:  a full /uploaded/... url to delete
                   15792: 
1.747     albertel 15793: =item * 
                   15794: 
                   15795: get_portfile_permissions():
                   15796:   Args:
                   15797:     domain: domain of user or course contain the portfolio files
                   15798:     user: name of user or num of course contain the portfolio files
                   15799:   Returns:
                   15800:     hashref of a dump of the proper file_permissions.db
                   15801:    
                   15802: 
                   15803: =item * 
                   15804: 
                   15805: get_access_controls():
                   15806: 
                   15807: Args:
                   15808:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15809:   group: (optional) the group you want the files associated with
                   15810:   file: (optional) the file you want access info on
                   15811: 
                   15812: Returns:
1.749     raeburn  15813:     a hash (keys are file names) of hashes containing
                   15814:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15815:         values are XML containing access control settings (see below) 
1.747     albertel 15816: 
                   15817: Internal notes:
                   15818: 
1.749     raeburn  15819:  access controls are stored in file_permissions.db as key=value pairs.
                   15820:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15821:         where scope -> public,guest,course,group,domains or users.
                   15822:               end -> UNIX time for end of access (0 -> no end date)
                   15823:               start -> UNIX time for start of access
                   15824: 
                   15825:     value -> XML description of access control
                   15826:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15827:             <start></start>
                   15828:             <end></end>
                   15829: 
                   15830:             <password></password>  for scope type = guest
                   15831: 
                   15832:             <domain></domain>     for scope type = course or group
                   15833:             <number></number>
                   15834:             <roles id="">
                   15835:              <role></role>
                   15836:              <access></access>
                   15837:              <section></section>
                   15838:              <group></group>
                   15839:             </roles>
                   15840: 
                   15841:             <dom></dom>         for scope type = domains
                   15842: 
                   15843:             <users>             for scope type = users
                   15844:              <user>
                   15845:               <uname></uname>
                   15846:               <udom></udom>
                   15847:              </user>
                   15848:             </users>
                   15849:            </scope> 
                   15850:               
                   15851:  Access data is also aggregated for each file in an additional key=value pair:
                   15852:  key -> path to file/file_name\0accesscontrol 
                   15853:  value -> reference to hash
                   15854:           hash contains key = value pairs
                   15855:           where key = uniqueID:scope_end_start
                   15856:                 value = UNIX time record was last updated
                   15857: 
                   15858:           Used to improve speed of look-ups of access controls for each file.  
                   15859:  
                   15860:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15861: 
1.1198    raeburn  15862: =item *
                   15863: 
1.749     raeburn  15864: modify_access_controls():
                   15865: 
                   15866: Modifies access controls for a portfolio file
                   15867: Args
                   15868: 1. file name
                   15869: 2. reference to hash of required changes,
                   15870: 3. domain
                   15871: 4. username
                   15872:   where domain,username are the domain of the portfolio owner 
                   15873:   (either a user or a course) 
                   15874: 
                   15875: Returns:
                   15876: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15877: 2. result of deletions ('ok' or 'error', with error message).
                   15878: 3. reference to hash of any new or updated access controls.
                   15879: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15880:    key = integer (inbound ID)
1.1198    raeburn  15881:    value = uniqueID
                   15882: 
                   15883: =item *
                   15884: 
                   15885: get_timebased_id():
                   15886: 
                   15887: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15888: course via the Course Editor (e.g., folders, composite pages, 
                   15889: group bulletin boards).
                   15890: 
                   15891: Args: (first three required; six others optional)
                   15892: 
                   15893: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15894:    docssequence, or name of group
                   15895: 
                   15896: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15897:    e.g., num, boardids
                   15898: 
                   15899: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15900:    file will be named nohist_namespace.db
                   15901: 
                   15902: 4. cdom: domain of course; default is current course domain from %env
                   15903: 
                   15904: 5. cnum: course number; default is current course number from %env
                   15905: 
                   15906: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15907:    unix timestamp to form the suffix, if the plain timestamp is already
                   15908:    in use.  Default is to not do this, but simply increment the unix 
                   15909:    timestamp by 1 until a unique key is obtained.
                   15910: 
                   15911: 7. who: holder of locking key; defaults to user:domain for user.
                   15912: 
                   15913: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15914:    retrying); default is 3.
                   15915: 
                   15916: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15917: 
                   15918: Returns:
                   15919: 
                   15920: 1. suffix obtained (numeric)
                   15921: 
                   15922: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15923: 
                   15924: 3. error: contains (localized) error message if an error occurred.
                   15925: 
1.747     albertel 15926: 
1.608     albertel 15927: =back
                   15928: 
1.243     albertel 15929: =head2 HTTP Helper Routines
                   15930: 
                   15931: =over 4
                   15932: 
1.191     harris41 15933: =item *
                   15934: 
                   15935: escape() : unpack non-word characters into CGI-compatible hex codes
                   15936: 
                   15937: =item *
                   15938: 
                   15939: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15940: 
1.243     albertel 15941: =back
                   15942: 
                   15943: =head1 PRIVATE SUBROUTINES
                   15944: 
                   15945: =head2 Underlying communication routines (Shouldn't call)
                   15946: 
                   15947: =over 4
                   15948: 
                   15949: =item *
                   15950: 
                   15951: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15952: 
                   15953: =item *
                   15954: 
                   15955: reply() : uses subreply to send a message to remote machine, logs all failures
                   15956: 
                   15957: =item *
                   15958: 
                   15959: critical() : passes a critical message to another server; if cannot
                   15960: get through then place message in connection buffer directory and
                   15961: returns con_delayed, if incapable of saving message, returns
                   15962: con_failed
                   15963: 
                   15964: =item *
                   15965: 
                   15966: reconlonc() : tries to reconnect lonc client processes.
                   15967: 
                   15968: =back
                   15969: 
                   15970: =head2 Resource Access Logging
                   15971: 
                   15972: =over 4
                   15973: 
                   15974: =item *
                   15975: 
                   15976: flushcourselogs() : flush (save) buffer logs and access logs
                   15977: 
                   15978: =item *
                   15979: 
                   15980: courselog($what) : save message for course in hash
                   15981: 
                   15982: =item *
                   15983: 
                   15984: courseacclog($what) : save message for course using &courselog().  Perform
                   15985: special processing for specific resource types (problems, exams, quizzes, etc).
                   15986: 
1.191     harris41 15987: =item *
                   15988: 
                   15989: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15990: as a PerlChildExitHandler
1.243     albertel 15991: 
                   15992: =back
                   15993: 
                   15994: =head2 Other
                   15995: 
                   15996: =over 4
                   15997: 
                   15998: =item *
                   15999: 
                   16000: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16001: 
                   16002: =back
                   16003: 
                   16004: =cut
1.877     foxr     16005: 

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